From 219f015c3a601c36420e8d1e2df9ed92efd9d052 Mon Sep 17 00:00:00 2001 From: Ayush Dattagupta Date: Tue, 20 Jun 2023 13:42:11 -0700 Subject: [PATCH 01/25] Add upper pin to pandas<2.0.0 (#1185) * Add upper pin to pandas<2.0.0 * add pin to conda meta yaml --- continuous_integration/environment-3.10-dev.yaml | 2 +- continuous_integration/environment-3.9-dev.yaml | 2 +- continuous_integration/gpuci/environment-3.10.yaml | 2 +- continuous_integration/gpuci/environment-3.9.yaml | 2 +- continuous_integration/recipe/meta.yaml | 2 +- docker/conda.txt | 2 +- docker/main.dockerfile | 2 +- docs/environment.yml | 2 +- docs/requirements-docs.txt | 2 +- setup.py | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/continuous_integration/environment-3.10-dev.yaml b/continuous_integration/environment-3.10-dev.yaml index 4926253d7..b7b65dd04 100644 --- a/continuous_integration/environment-3.10-dev.yaml +++ b/continuous_integration/environment-3.10-dev.yaml @@ -15,7 +15,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0 +- pandas>=1.4.0,<2.0.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/environment-3.9-dev.yaml b/continuous_integration/environment-3.9-dev.yaml index eec8142c3..a0edfd6f7 100644 --- a/continuous_integration/environment-3.9-dev.yaml +++ b/continuous_integration/environment-3.9-dev.yaml @@ -15,7 +15,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0 +- pandas>=1.4.0,<2.0.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index b5b4a7629..e47138a6a 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -18,7 +18,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0 +- pandas>=1.4.0,<2.0.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index 7f0bd0ade..7da94474c 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -18,7 +18,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0 +- pandas>=1.4.0,<2.0.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index 85dadc3a4..4d0c21d58 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -35,7 +35,7 @@ requirements: run: - python - dask >=2022.3.0,<=2023.5.1 - - pandas >=1.4.0 + - pandas >=1.4.0,<2.0.0 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi >=0.69.0,<0.87.0 - uvicorn >=0.13.4 diff --git a/docker/conda.txt b/docker/conda.txt index a081fc6b7..aa62b3b1c 100644 --- a/docker/conda.txt +++ b/docker/conda.txt @@ -1,6 +1,6 @@ python>=3.8 dask>=2022.3.0,<=2023.5.1 -pandas>=1.4.0 +pandas>=1.4.0,<2.0.0 jpype1>=1.0.2 openjdk>=8 maven>=3.6.0 diff --git a/docker/main.dockerfile b/docker/main.dockerfile index d13816fce..7fda7256e 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -17,7 +17,7 @@ RUN mamba install -y \ "setuptools-rust>=1.5.2" \ # core dependencies "dask>=2022.3.0,<=2023.5.1" \ - "pandas>=1.4.0" \ + "pandas>=1.4.0,<2.0.0" \ # FIXME: handling is needed for httpx-based fastapi>=0.87.0 "fastapi>=0.69.0,<0.87.0" \ "uvicorn>=0.13.4" \ diff --git a/docs/environment.yml b/docs/environment.yml index 1528211a1..c7213bb08 100644 --- a/docs/environment.yml +++ b/docs/environment.yml @@ -8,7 +8,7 @@ dependencies: - sphinx-tabs - dask-sphinx-theme>=2.0.3 - dask>=2022.3.0,<=2023.5.1 - - pandas>=1.4.0 + - pandas>=1.4.0,<2.0.0 - fugue>=0.7.3 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi>=0.69.0,<0.87.0 diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index 19849425d..81f3a944a 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -2,7 +2,7 @@ sphinx>=4.0.0 sphinx-tabs dask-sphinx-theme>=3.0.0 dask>=2022.3.0,<=2023.5.1 -pandas>=1.4.0 +pandas>=1.4.0,<2.0.0 fugue>=0.7.3 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 fastapi>=0.69.0,<0.87.0 diff --git a/setup.py b/setup.py index eaee4ea78..0f3c8a390 100644 --- a/setup.py +++ b/setup.py @@ -44,7 +44,7 @@ install_requires=[ "dask[dataframe]>=2022.3.0,<=2023.5.1", "distributed>=2022.3.0,<=2023.5.1", - "pandas>=1.4.0", + "pandas>=1.4.0,<2.0.0", # FIXME: handling is needed for httpx-based fastapi>=0.87.0 "fastapi>=0.69.0,<0.87.0", "uvicorn>=0.13.4", From 899170679b44b8eebd5efe1af373eded98cbe9aa Mon Sep 17 00:00:00 2001 From: Sarah Yurick <53962159+sarahyurick@users.noreply.github.com> Date: Tue, 20 Jun 2023 16:21:49 -0700 Subject: [PATCH 02/25] Add command line arguments for testing queries (#1161) * add filepath arg * data_dir and queries_dir --------- Co-authored-by: Ayush Dattagupta --- conftest.py | 12 ++++++++++++ tests/unit/test_queries.py | 28 ++++++++++++++++++---------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/conftest.py b/conftest.py index d840bfd86..0042c9ca7 100644 --- a/conftest.py +++ b/conftest.py @@ -7,6 +7,8 @@ def pytest_addoption(parser): parser.addoption("--rungpu", action="store_true", help="run tests meant for GPU") parser.addoption("--runqueries", action="store_true", help="run test queries") + parser.addoption("--data_dir", help="specify file path to the data") + parser.addoption("--queries_dir", help="specify file path to the queries") def pytest_runtest_setup(item): @@ -21,3 +23,13 @@ def pytest_runtest_setup(item): dask.config.set({"dataframe.shuffle.algorithm": None}) if "queries" in item.keywords and not item.config.getoption("--runqueries"): pytest.skip("need --runqueries option to run") + + +@pytest.fixture(scope="session") +def data_dir(request): + return request.config.getoption("--data_dir") + + +@pytest.fixture(scope="session") +def queries_dir(request): + return request.config.getoption("--queries_dir") diff --git a/tests/unit/test_queries.py b/tests/unit/test_queries.py index 42ef0c895..b32e9530f 100644 --- a/tests/unit/test_queries.py +++ b/tests/unit/test_queries.py @@ -51,15 +51,17 @@ @pytest.fixture(scope="module") -def c(): +def c(data_dir): # Lazy import, otherwise the pytest framework has problems from dask_sql.context import Context c = Context() - for table_name in os.listdir(f"{os.path.dirname(__file__)}/data/"): + if not data_dir: + data_dir = f"{os.path.dirname(__file__)}/data/" + for table_name in os.listdir(data_dir): c.create_table( table_name, - f"{os.path.dirname(__file__)}/data/{table_name}", + data_dir + "/" + table_name, format="parquet", gpu=False, ) @@ -68,17 +70,19 @@ def c(): @pytest.fixture(scope="module") -def gpu_c(): +def gpu_c(data_dir): pytest.importorskip("dask_cudf") # Lazy import, otherwise the pytest framework has problems from dask_sql.context import Context c = Context() - for table_name in os.listdir(f"{os.path.dirname(__file__)}/data/"): + if not data_dir: + data_dir = f"{os.path.dirname(__file__)}/data/" + for table_name in os.listdir(data_dir): c.create_table( table_name, - f"{os.path.dirname(__file__)}/data/{table_name}", + data_dir + "/" + table_name, format="parquet", gpu=True, ) @@ -88,8 +92,10 @@ def gpu_c(): @pytest.mark.queries @pytest.mark.parametrize("query", QUERIES) -def test_query(c, client, query): - with open(f"{os.path.dirname(__file__)}/queries/{query}") as f: +def test_query(c, client, query, queries_dir): + if not queries_dir: + queries_dir = f"{os.path.dirname(__file__)}/queries/" + with open(queries_dir + "/" + query) as f: sql = f.read() res = c.sql(sql) @@ -99,8 +105,10 @@ def test_query(c, client, query): @pytest.mark.gpu @pytest.mark.queries @pytest.mark.parametrize("query", QUERIES) -def test_gpu_query(gpu_c, gpu_client, query): - with open(f"{os.path.dirname(__file__)}/queries/{query}") as f: +def test_gpu_query(gpu_c, gpu_client, query, queries_dir): + if not queries_dir: + queries_dir = f"{os.path.dirname(__file__)}/queries/" + with open(queries_dir + "/" + query) as f: sql = f.read() res = gpu_c.sql(sql) From 68853a5f35d60aefcf0ecb41d6f2f3df513a27a7 Mon Sep 17 00:00:00 2001 From: "Richard (Rick) Zamora" Date: Wed, 21 Jun 2023 11:44:41 -0500 Subject: [PATCH 03/25] Add support for custom filters to `attempt_predicate_pushdown` (#1173) * add support for custom filters to attempt_predicate_pushdown * remove comments * fix preserve_filters=False bug --------- Co-authored-by: Ayush Dattagupta --- dask_sql/physical/utils/filter.py | 216 +++++++++++++++++++----------- tests/unit/test_utils.py | 53 ++++++++ 2 files changed, 193 insertions(+), 76 deletions(-) diff --git a/dask_sql/physical/utils/filter.py b/dask_sql/physical/utils/filter.py index 5ac82fdd0..0b4e0f40b 100644 --- a/dask_sql/physical/utils/filter.py +++ b/dask_sql/physical/utils/filter.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import itertools import logging import operator @@ -14,7 +16,12 @@ logger = logging.getLogger(__name__) -def attempt_predicate_pushdown(ddf: dd.DataFrame) -> dd.DataFrame: +def attempt_predicate_pushdown( + ddf: dd.DataFrame, + preserve_filters: bool = True, + extract_filters: bool = True, + add_filters: list | tuple | DNF | None = None, +) -> dd.DataFrame: """Use graph information to update IO-level filters The original `ddf` will be returned if/when the @@ -26,8 +33,27 @@ def attempt_predicate_pushdown(ddf: dd.DataFrame) -> dd.DataFrame: is due to the fact that `npartitions` and `divisions` may change when this optimization is applied (invalidating npartition/divisions-specific logic in following Layers). + + Parameters + ---------- + ddf + Dask-DataFrame target for predicate pushdown. + preserve_filters + Whether to preserve pre-existing filters in the case that either + `add_filters` is specified, or `extract_filters` is `True` and + filters are successfully extracted from `ddf`. Default is `True`. + extract_filters + Whether to extract filters from the task graph of `ddf`. Default + is `True`. + add_filters + Custom filters to manually add to the IO layer of `ddf`. """ + if not (extract_filters or add_filters): + # Not extracting filters from the graph or + # manually adding user-defined filters. Return + return ddf + # Check that we have a supported `ddf` object if not isinstance(ddf, dd.DataFrame): raise ValueError( @@ -50,23 +76,18 @@ def attempt_predicate_pushdown(ddf: dd.DataFrame) -> dd.DataFrame: creation_info = ( (v.creation_info or {}) if hasattr(v, "creation_info") else {} ) - if ( - "filters" not in creation_info.get("kwargs", {}) - or creation_info["kwargs"]["filters"] is not None - ): - # No filters support, or filters is already set + if "filters" not in creation_info.get("kwargs", {}): + # No filters support return ddf if len(io_layer) != 1: # Not a single IO layer return ddf io_layer = io_layer.pop() - # Bail if any filters are already present in ddf + # Get pre-existing filters existing_filters = ( ddf.dask.layers[io_layer].creation_info.get("kwargs", {}).get("filters") ) - if existing_filters: - return ddf # Start by converting the HLG to a `RegenerableGraph`. # Succeeding here means that all layers in the graph @@ -80,21 +101,31 @@ def attempt_predicate_pushdown(ddf: dd.DataFrame) -> dd.DataFrame: ) return ddf - # Extract a DNF-formatted filter expression name = ddf._name - try: - filters = dsk.layers[name]._dnf_filter_expression(dsk) - if not isinstance(filters, frozenset): - # No filters encountered - return ddf - filters = filters.to_list_tuple() - except (ValueError, TypeError): - # DNF dispatching failed for 1+ layers - logger.warning( - "Predicate pushdown optimization skipped. One or more " - "layers has an unknown filter expression." - ) + extracted_filters = DNF(None) + if extract_filters: + # Extract a DNF-formatted filter expression + try: + extracted_filters = dsk.layers[name]._dnf_filter_expression(dsk) + except (ValueError, TypeError): + # DNF dispatching failed for 1+ layers + logger.warning( + "Predicate pushdown optimization skipped. One or more " + "layers has an unknown filter expression." + ) + + # Combine filters + filters = DNF(None) + if preserve_filters: + filters = filters.combine(existing_filters) + if extract_filters: + filters = filters.combine(extracted_filters) + if add_filters: + filters = filters.combine(add_filters) + if not filters: + # No filters encountered return ddf + filters = filters.to_list_tuple() # Regenerate collection with filtered IO layer try: @@ -117,52 +148,85 @@ def attempt_predicate_pushdown(ddf: dd.DataFrame) -> dd.DataFrame: return ddf -class Or(frozenset): - """Helper class for 'OR' expressions""" +class DNF: + """Manage filters in Disjunctive Normal Form (DNF)""" - def to_list_tuple(self): - # NDF "or" is List[List[Tuple]] - def _maybe_list(val): - if isinstance(val, tuple) and val and isinstance(val[0], (tuple, list)): - return list(val) - return [val] + class _Or(frozenset): + """Fozen set of disjunctions""" - return [ - _maybe_list(val.to_list_tuple()) - if hasattr(val, "to_list_tuple") - else _maybe_list(val) - for val in self - ] + def to_list_tuple(self) -> list: + # DNF "or" is List[List[Tuple]] + def _maybe_list(val): + if isinstance(val, tuple) and val and isinstance(val[0], (tuple, list)): + return list(val) + return [val] + return [ + _maybe_list(val.to_list_tuple()) + if hasattr(val, "to_list_tuple") + else _maybe_list(val) + for val in self + ] -class And(frozenset): - """Helper class for 'AND' expressions""" + class _And(frozenset): + """Frozen set of conjunctions""" - def to_list_tuple(self): - # NDF "and" is List[Tuple] - return tuple( - val.to_list_tuple() if hasattr(val, "to_list_tuple") else val - for val in self - ) + def to_list_tuple(self) -> list: + # DNF "and" is List[Tuple] + return tuple( + val.to_list_tuple() if hasattr(val, "to_list_tuple") else val + for val in self + ) + + _filters: _And | _Or | None # Underlying filter expression + + def __init__(self, filters: DNF | _And | _Or | list | tuple | None) -> DNF: + if isinstance(filters, DNF): + self._filters = filters._filters + else: + self._filters = self.normalize(filters) + def to_list_tuple(self) -> list: + return self._filters.to_list_tuple() -def to_dnf(expr): - """Normalize a boolean filter expression to disjunctive normal form (DNF)""" + def __bool__(self) -> bool: + return bool(self._filters) - # Credit: https://stackoverflow.com/a/58372345 - if not isinstance(expr, (Or, And)): - if not isinstance(expr, tuple): - raise TypeError(f"expected tuple, got {expr}") - result = Or((And((expr,)),)) - elif isinstance(expr, Or): - result = Or(se for e in expr for se in to_dnf(e)) - elif isinstance(expr, And): - total = [] - for c in itertools.product(*[to_dnf(e) for e in expr]): - conjunction = [se for e in c for se in e if isinstance(se, tuple)] - total.append(And(conjunction)) - result = Or(total) - return result + @classmethod + def normalize(cls, filters: _And | _Or | list | tuple | None): + """Convert raw filters to the `_Or(_And)` DNF representation""" + if not filters: + result = None + elif isinstance(filters, list): + conjunctions = filters if isinstance(filters[0], list) else [filters] + result = cls._Or([cls._And(conjunction) for conjunction in conjunctions]) + elif isinstance(filters, tuple): + if isinstance(filters[0], tuple): + raise TypeError("filters must be List[Tuple] or List[List[Tuple]]") + result = cls._Or((cls._And((filters,)),)) + elif isinstance(filters, cls._Or): + result = cls._Or(se for e in filters for se in cls.normalize(e)) + elif isinstance(filters, cls._And): + total = [] + for c in itertools.product(*[cls.normalize(e) for e in filters]): + total.append(cls._And(se for e in c for se in e)) + result = cls._Or(total) + else: + raise TypeError(f"{type(filters)} not a supported type for DNF") + return result + + def combine(self, other: DNF | _And | _Or | list | tuple | None) -> DNF: + """Combine with another DNF object""" + if not isinstance(other, DNF): + other = DNF(other) + assert isinstance(other, DNF) + if self._filters is None: + result = other._filters + elif other._filters is None: + result = self._filters + else: + result = self._And([self._filters, other._filters]) + return DNF(result) # Define all supported comparison functions @@ -413,7 +477,7 @@ def _inv(symbol: str): }.get(symbol, symbol) -def _blockwise_comparison_dnf(op, indices: list, dsk: RegenerableGraph): +def _blockwise_comparison_dnf(op, indices: list, dsk: RegenerableGraph) -> DNF: # Return DNF expression pattern for a simple comparison left = _get_blockwise_input(0, indices, dsk) right = _get_blockwise_input(1, indices, dsk) @@ -421,27 +485,27 @@ def _blockwise_comparison_dnf(op, indices: list, dsk: RegenerableGraph): if is_arraylike(left) and hasattr(left, "item") and left.size == 1: left = left.item() # Need inverse comparison in read_parquet - return to_dnf((right, _inv(_comparison_symbols[op]), left)) + return DNF((right, _inv(_comparison_symbols[op]), left)) if is_arraylike(right) and hasattr(right, "item") and right.size == 1: right = right.item() - return to_dnf((left, _comparison_symbols[op], right)) + return DNF((left, _comparison_symbols[op], right)) -def _blockwise_logical_dnf(op, indices: list, dsk: RegenerableGraph): +def _blockwise_logical_dnf(op, indices: list, dsk: RegenerableGraph) -> DNF: # Return DNF expression pattern for logical "and" or "or" left = _get_blockwise_input(0, indices, dsk) right = _get_blockwise_input(1, indices, dsk) - vals = [] + filters = [] for val in [left, right]: - if not isinstance(val, (tuple, Or, And)): + if not isinstance(val, (tuple, DNF)): raise TypeError(f"Invalid logical operand: {val}") - vals.append(to_dnf(val)) + filters.append(DNF(val)._filters) if op == operator.or_: - return to_dnf(Or(vals)) + return DNF(DNF._Or(filters)) elif op == operator.and_: - return to_dnf(And(vals)) + return DNF(DNF._And(filters)) else: raise ValueError @@ -457,22 +521,22 @@ def _blockwise_pass_through_dnf(op, indices: list, dsk: RegenerableGraph): return _get_blockwise_input(0, indices, dsk) -def _blockwise_isin_dnf(op, indices: list, dsk: RegenerableGraph): +def _blockwise_isin_dnf(op, indices: list, dsk: RegenerableGraph) -> DNF: # Return DNF expression pattern for a simple "in" comparison left = _get_blockwise_input(0, indices, dsk) right = _get_blockwise_input(1, indices, dsk) - return to_dnf((left, "in", tuple(right))) + return DNF((left, "in", tuple(right))) -def _blockwise_isna_dnf(op, indices: list, dsk: RegenerableGraph): +def _blockwise_isna_dnf(op, indices: list, dsk: RegenerableGraph) -> DNF: # Return DNF expression pattern for `isna` if not PQ_IS_SUPPORT: raise ValueError("This version of dask does not support 'is' predicates.") left = _get_blockwise_input(0, indices, dsk) - return to_dnf((left, "is", None)) + return DNF((left, "is", None)) -def _blockwise_inv_dnf(op, indices: list, dsk: RegenerableGraph): +def _blockwise_inv_dnf(op, indices: list, dsk: RegenerableGraph) -> DNF: # Return DNF expression pattern for the inverse of a comparison expr = _get_blockwise_input(0, indices, dsk).to_list_tuple() new_expr = [] @@ -482,9 +546,9 @@ def _blockwise_inv_dnf(op, indices: list, dsk: RegenerableGraph): for col, op, val in conjunction: count += 1 new_conjunction.append((col, _inv(op), val)) - new_expr.append(And(new_conjunction)) + new_expr.append(DNF._And(new_conjunction)) if count > 1: # Havent taken the time to think through # general inversion yet. raise ValueError("inv(DNF) case not implemented.") - return to_dnf(Or(new_expr)) + return DNF(DNF._Or(new_expr)) diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 00eb5a885..7c5df717d 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -130,3 +130,56 @@ def test_predicate_pushdown_isna(parquet_ddf): ] expected_filters = frozenset(frozenset(v) for v in expected_filters) assert got_filters == expected_filters + + +def test_predicate_pushdown_add_filters(parquet_ddf): + filtered_df = parquet_ddf[(parquet_ddf["a"] > 1) | (parquet_ddf["a"] == -1)] + pushdown_df = attempt_predicate_pushdown( + filtered_df, + add_filters=("b", "<", 2), + ) + got_filters = hlg_layer(pushdown_df.dask, "read-parquet").creation_info["kwargs"][ + "filters" + ] + got_filters = frozenset(frozenset(v) for v in got_filters) + expected_filters = [ + [("a", ">", 1), ("b", "<", 2)], + [("a", "==", -1), ("b", "<", 2)], + ] + expected_filters = frozenset(frozenset(v) for v in expected_filters) + assert got_filters == expected_filters + + +def test_predicate_pushdown_add_filters_no_extract(parquet_ddf): + filtered_df = parquet_ddf[(parquet_ddf["a"] > 1) | (parquet_ddf["a"] == -1)] + pushdown_df = attempt_predicate_pushdown( + filtered_df, + extract_filters=False, + add_filters=("b", "<", 2), + ) + got_filters = hlg_layer(pushdown_df.dask, "read-parquet").creation_info["kwargs"][ + "filters" + ] + got_filters = frozenset(frozenset(v) for v in got_filters) + expected_filters = [[("b", "<", 2)]] + expected_filters = frozenset(frozenset(v) for v in expected_filters) + assert got_filters == expected_filters + + +def test_predicate_pushdown_add_filters_no_preserve(parquet_ddf): + filtered_df = parquet_ddf[(parquet_ddf["a"] > 1) | (parquet_ddf["a"] == -1)] + pushdown_df0 = attempt_predicate_pushdown(filtered_df) + pushdown_df = attempt_predicate_pushdown( + pushdown_df0, + preserve_filters=False, + extract_filters=False, + add_filters=("b", "<", 2), + ) + + got_filters = hlg_layer(pushdown_df.dask, "read-parquet").creation_info["kwargs"][ + "filters" + ] + got_filters = frozenset(frozenset(v) for v in got_filters) + expected_filters = [[("b", "<", 2)]] + expected_filters = frozenset(frozenset(v) for v in expected_filters) + assert got_filters == expected_filters From c9eeb2c119d0236d3c7fbec16c4d8b6b08c86c9b Mon Sep 17 00:00:00 2001 From: Ayush Dattagupta Date: Wed, 21 Jun 2023 11:02:53 -0700 Subject: [PATCH 04/25] Unpin dask for dev (#1186) --- continuous_integration/environment-3.10-dev.yaml | 2 +- continuous_integration/environment-3.9-dev.yaml | 2 +- continuous_integration/gpuci/environment-3.10.yaml | 2 +- continuous_integration/gpuci/environment-3.9.yaml | 2 +- continuous_integration/recipe/meta.yaml | 2 +- docker/conda.txt | 2 +- docker/main.dockerfile | 2 +- docs/environment.yml | 2 +- docs/requirements-docs.txt | 2 +- setup.py | 4 ++-- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/continuous_integration/environment-3.10-dev.yaml b/continuous_integration/environment-3.10-dev.yaml index b7b65dd04..6a3a37f0b 100644 --- a/continuous_integration/environment-3.10-dev.yaml +++ b/continuous_integration/environment-3.10-dev.yaml @@ -4,7 +4,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.5.1 +- dask>=2022.3.0 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi>=0.69.0,<0.87.0 - fugue>=0.7.3 diff --git a/continuous_integration/environment-3.9-dev.yaml b/continuous_integration/environment-3.9-dev.yaml index a0edfd6f7..d7b4700f8 100644 --- a/continuous_integration/environment-3.9-dev.yaml +++ b/continuous_integration/environment-3.9-dev.yaml @@ -4,7 +4,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.5.1 +- dask>=2022.3.0 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi>=0.69.0,<0.87.0 - fugue>=0.7.3 diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index e47138a6a..f1b76271a 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -7,7 +7,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.5.1 +- dask>=2022.3.0 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi>=0.69.0,<0.87.0 - fugue>=0.7.3 diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index 7da94474c..2ee59f6cb 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -7,7 +7,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.5.1 +- dask>=2022.3.0 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi>=0.69.0,<0.87.0 - fugue>=0.7.3 diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index 4d0c21d58..f2ad46249 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -34,7 +34,7 @@ requirements: - libprotobuf run: - python - - dask >=2022.3.0,<=2023.5.1 + - dask >=2022.3.0 - pandas >=1.4.0,<2.0.0 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi >=0.69.0,<0.87.0 diff --git a/docker/conda.txt b/docker/conda.txt index aa62b3b1c..0c57cf45d 100644 --- a/docker/conda.txt +++ b/docker/conda.txt @@ -1,5 +1,5 @@ python>=3.8 -dask>=2022.3.0,<=2023.5.1 +dask>=2022.3.0 pandas>=1.4.0,<2.0.0 jpype1>=1.0.2 openjdk>=8 diff --git a/docker/main.dockerfile b/docker/main.dockerfile index 7fda7256e..09d07834f 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -16,7 +16,7 @@ RUN mamba install -y \ # build requirements "setuptools-rust>=1.5.2" \ # core dependencies - "dask>=2022.3.0,<=2023.5.1" \ + "dask>=2022.3.0" \ "pandas>=1.4.0,<2.0.0" \ # FIXME: handling is needed for httpx-based fastapi>=0.87.0 "fastapi>=0.69.0,<0.87.0" \ diff --git a/docs/environment.yml b/docs/environment.yml index c7213bb08..ae25c9440 100644 --- a/docs/environment.yml +++ b/docs/environment.yml @@ -7,7 +7,7 @@ dependencies: - sphinx>=4.0.0 - sphinx-tabs - dask-sphinx-theme>=2.0.3 - - dask>=2022.3.0,<=2023.5.1 + - dask>=2022.3.0 - pandas>=1.4.0,<2.0.0 - fugue>=0.7.3 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index 81f3a944a..374528d89 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -1,7 +1,7 @@ sphinx>=4.0.0 sphinx-tabs dask-sphinx-theme>=3.0.0 -dask>=2022.3.0,<=2023.5.1 +dask>=2022.3.0 pandas>=1.4.0,<2.0.0 fugue>=0.7.3 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 diff --git a/setup.py b/setup.py index 0f3c8a390..085d362fe 100644 --- a/setup.py +++ b/setup.py @@ -42,8 +42,8 @@ python_requires=">=3.8", setup_requires=sphinx_requirements, install_requires=[ - "dask[dataframe]>=2022.3.0,<=2023.5.1", - "distributed>=2022.3.0,<=2023.5.1", + "dask[dataframe]>=2022.3.0", + "distributed>=2022.3.0", "pandas>=1.4.0,<2.0.0", # FIXME: handling is needed for httpx-based fastapi>=0.87.0 "fastapi>=0.69.0,<0.87.0", From f8bf06ca09459cc78426b5a9bc67d870c4d6fba9 Mon Sep 17 00:00:00 2001 From: Sarah Yurick <53962159+sarahyurick@users.noreply.github.com> Date: Thu, 22 Jun 2023 10:01:47 -0700 Subject: [PATCH 05/25] Dynamic partition pruning (#1102) * q3 functionality * style and minor functionality changes * some cleanup * save progress * use inlist instead of binaryexpr * fix cargo test * fix some queries * use with_max_passes=1 and remove todos * add warning * only run dpp once * null handling and double dtype * minor style fixes * clippy * use adp imports * add jeremy suggestions and better type logic * style fix * MORE int/float logic * style fix * fix some bugs * add dask_config * check for duplicate tablescans * fix row iterator * clippy * clippy again * add per-query config * style --------- Co-authored-by: Jeremy Dyer Co-authored-by: Ayush Dattagupta --- dask_planner/src/sql.rs | 34 +- dask_planner/src/sql/optimizer.rs | 22 + .../optimizer/dynamic_partition_pruning.rs | 1084 +++++++++++++++++ dask_planner/src/sql/table.rs | 1 - dask_sql/context.py | 7 + dask_sql/sql-schema.yaml | 5 + dask_sql/sql.yaml | 2 + 7 files changed, 1147 insertions(+), 8 deletions(-) create mode 100644 dask_planner/src/sql/optimizer/dynamic_partition_pruning.rs diff --git a/dask_planner/src/sql.rs b/dask_planner/src/sql.rs index 22f6d01ac..941eb9e02 100644 --- a/dask_planner/src/sql.rs +++ b/dask_planner/src/sql.rs @@ -99,6 +99,7 @@ pub struct DaskSQLContext { current_schema: String, schemas: HashMap, options: ConfigOptions, + dynamic_partition_pruning: bool, } impl ContextProvider for DaskSQLContext { @@ -457,9 +458,15 @@ impl DaskSQLContext { current_schema: default_schema_name.to_owned(), schemas: HashMap::new(), options: ConfigOptions::new(), + dynamic_partition_pruning: false, } } + pub fn apply_dynamic_partition_pruning(&mut self, config: bool) -> PyResult<()> { + self.dynamic_partition_pruning = config; + Ok(()) + } + /// Change the current schema pub fn use_schema(&mut self, schema_name: &str) -> PyResult<()> { if self.schemas.contains_key(schema_name) { @@ -546,13 +553,26 @@ impl DaskSQLContext { warn!("This LogicalPlan does not support Optimization. Returning original"); Ok(existing_plan) } - _ => optimizer::DaskSqlOptimizer::new() - .optimize(existing_plan.original_plan) - .map(|k| PyLogicalPlan { - original_plan: k, - current_node: None, - }) - .map_err(py_optimization_exp), + _ => { + let optimized_plan = optimizer::DaskSqlOptimizer::new() + .optimize(existing_plan.original_plan) + .map(|k| PyLogicalPlan { + original_plan: k, + current_node: None, + }) + .map_err(py_optimization_exp); + if self.dynamic_partition_pruning { + optimizer::DaskSqlOptimizer::dynamic_partition_pruner() + .optimize_once(optimized_plan.unwrap().original_plan) + .map(|k| PyLogicalPlan { + original_plan: k, + current_node: None, + }) + .map_err(py_optimization_exp) + } else { + optimized_plan + } + } } } Err(e) => Err(py_optimization_exp(e)), diff --git a/dask_planner/src/sql/optimizer.rs b/dask_planner/src/sql/optimizer.rs index 68577cf2c..bdaa30ea7 100644 --- a/dask_planner/src/sql/optimizer.rs +++ b/dask_planner/src/sql/optimizer.rs @@ -24,6 +24,9 @@ use datafusion_python::{ }; use log::{debug, trace}; +mod dynamic_partition_pruning; +use dynamic_partition_pruning::DynamicPartitionPruning; + mod join_reorder; use join_reorder::JoinReorder; @@ -86,6 +89,17 @@ impl DaskSqlOptimizer { } } + // Create a separate instance of this optimization rule, since we want to ensure that it only + // runs one time + pub fn dynamic_partition_pruner() -> Self { + let rule: Vec> = + vec![Arc::new(DynamicPartitionPruning::new())]; + + Self { + optimizer: Optimizer::with_rules(rule), + } + } + /// Iterates through the configured `OptimizerRule`(s) to transform the input `LogicalPlan` /// to its final optimized form pub(crate) fn optimize(&self, plan: LogicalPlan) -> Result { @@ -93,6 +107,14 @@ impl DaskSqlOptimizer { self.optimizer.optimize(&plan, &config, Self::observe) } + /// Iterates once through the configured `OptimizerRule`(s) to transform the input `LogicalPlan` + /// to its final optimized form + pub(crate) fn optimize_once(&self, plan: LogicalPlan) -> Result { + let mut config = OptimizerContext::new(); + config = OptimizerContext::with_max_passes(config, 1); + self.optimizer.optimize(&plan, &config, Self::observe) + } + fn observe(optimized_plan: &LogicalPlan, optimization: &dyn OptimizerRule) { trace!( "== AFTER APPLYING RULE {} ==\n{}\n", diff --git a/dask_planner/src/sql/optimizer/dynamic_partition_pruning.rs b/dask_planner/src/sql/optimizer/dynamic_partition_pruning.rs new file mode 100644 index 000000000..0ff48a682 --- /dev/null +++ b/dask_planner/src/sql/optimizer/dynamic_partition_pruning.rs @@ -0,0 +1,1084 @@ +//! Optimizer rule for dynamic partition pruning (DPP) +//! +//! DPP refers to a query optimization rule in which distinct values in an inner join are used as +//! filters in a table scan. This allows us to eliminate all other rows which do not fit the join +//! condition from being read at all. +//! +//! Furthermore, a table involved in a join may be filtered during a scan, which allows us to +//! further prune the values to be read. + +use std::{ + collections::{HashMap, HashSet}, + fs, + hash::{Hash, Hasher}, +}; + +use datafusion_python::{ + datafusion::parquet::{ + basic::Type as BasicType, + file::reader::{FileReader, SerializedFileReader}, + record::{reader::RowIter, RowAccessor}, + schema::{parser::parse_message_type, types::Type}, + }, + datafusion_common::{Column, Result, ScalarValue}, + datafusion_expr::{ + logical_plan::LogicalPlan, + utils::from_plan, + Expr, + JoinType, + Operator, + TableScan, + }, + datafusion_optimizer::{OptimizerConfig, OptimizerRule}, +}; +use log::warn; + +use crate::sql::table::DaskTableSource; + +// Optimizer rule for dynamic partition pruning +pub struct DynamicPartitionPruning {} + +impl DynamicPartitionPruning { + pub fn new() -> Self { + Self {} + } +} + +impl OptimizerRule for DynamicPartitionPruning { + fn name(&self) -> &str { + "dynamic_partition_pruning" + } + + fn try_optimize( + &self, + plan: &LogicalPlan, + _config: &dyn OptimizerConfig, + ) -> Result> { + // Parse the LogicalPlan and store tables and columns being (inner) joined upon. We do this + // by creating a HashSet of all InnerJoins' join.on and join.filters + let join_conds = gather_joins(plan); + let tables = gather_tables(plan); + let aliases = gather_aliases(plan); + + if join_conds.is_empty() || tables.is_empty() { + // No InnerJoins to optimize with + Ok(None) + } else { + // Find the size of the largest table in the query + let mut largest_size = 1_f64; + for table in &tables { + let table_size = table.1.size.unwrap_or(0) as f64; + if table_size > largest_size { + largest_size = table_size; + } + } + + let mut join_values = vec![]; + let mut join_tables = vec![]; + let mut join_fields = vec![]; + let mut fact_tables = HashSet::new(); + + // Iterate through all inner joins in the query + for join_cond in &join_conds { + let join_on = &join_cond.on; + for on_i in join_on { + // Obtain tables and columns (fields) involved in join + let (left_on, right_on) = (&on_i.0, &on_i.1); + let (mut left_table, mut right_table) = (None, None); + let (mut left_field, mut right_field) = (None, None); + + if let Expr::Column(c) = left_on { + left_table = Some(c.relation.clone().unwrap().to_string().clone()); + left_field = Some(c.name.clone()); + } + if let Expr::Column(c) = right_on { + right_table = Some(c.relation.clone().unwrap().to_string().clone()); + right_field = Some(c.name.clone()); + } + + // For now, if it is not a join between columns then we skip the rule + // TODO: https://github.com/dask-contrib/dask-sql/issues/1121 + if left_table.is_none() || right_table.is_none() { + continue; + } + + let (mut left_table, mut right_table) = + (left_table.unwrap(), right_table.unwrap()); + let (left_field, right_field) = (left_field.unwrap(), right_field.unwrap()); + + // TODO: Consider allowing the fact_dimension_ratio to be configured by the + // user. See issue: https://github.com/dask-contrib/dask-sql/issues/1121 + let fact_dimension_ratio = 0.3; + let (mut left_filtered_table, mut right_filtered_table) = (None, None); + + // Check if join uses an alias instead of the table name itself. Need to use + // the actual table name to obtain its filepath + let left_alias = aliases.get(&left_table.clone()); + if let Some(t) = left_alias { + left_table = t.to_string() + } + let right_alias = aliases.get(&right_table.clone()); + if let Some(t) = right_alias { + right_table = t.to_string() + } + + // A more complicated alias, e.g. an alias for a nested select, means it's not + // obvious which file(s) should be read + if !tables.contains_key(&left_table) || !tables.contains_key(&right_table) { + continue; + } + + // Determine whether a table is a fact or dimension table. If it's a dimension + // table, we should read it in and use the rule + if tables + .get(&left_table.clone()) + .unwrap() + .size + .unwrap_or(largest_size as usize) as f64 + / largest_size + < fact_dimension_ratio + { + left_filtered_table = + read_table(left_table.clone(), left_field.clone(), tables.clone()); + } else { + fact_tables.insert(left_table.clone()); + } + if tables + .get(&right_table.clone()) + .unwrap() + .size + .unwrap_or(largest_size as usize) as f64 + / largest_size + < fact_dimension_ratio + { + right_filtered_table = + read_table(right_table.clone(), right_field.clone(), tables.clone()); + } else { + fact_tables.insert(right_table.clone()); + } + + join_values.push((left_filtered_table, right_filtered_table)); + join_tables.push((left_table, right_table)); + join_fields.push((left_field, right_field)); + } + } + // Creates HashMap of all tables and field with their unique values to be set in the + // TableScan + let filter_values = combine_sets(join_values, join_tables, join_fields, fact_tables); + // Optimize and return the plan + optimize_table_scans(plan, filter_values) + } + } +} + +/// Represents relevant information in an InnerJoin +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct JoinInfo { + /// Equijoin clause expressed as pairs of (left, right) join expressions + on: Vec<(Expr, Expr)>, + /// Filters applied during join (non-equi conditions) + /// TODO: https://github.com/dask-contrib/dask-sql/issues/1121 + filter: Option, +} + +// This function parses through the LogicalPlan, grabs relevant information from an InnerJoin, and +// adds them to a HashSet +fn gather_joins(plan: &LogicalPlan) -> HashSet { + let mut current_plan = plan.clone(); + let mut join_info = HashSet::new(); + loop { + if current_plan.inputs().is_empty() { + break; + } else if current_plan.inputs().len() > 1 { + match current_plan { + LogicalPlan::Join(ref j) => { + if j.join_type == JoinType::Inner { + // Store tables and columns that are being (inner) joined upon + let info = JoinInfo { + on: j.on.clone(), + filter: j.filter.clone(), + }; + join_info.insert(info); + + // Recurse on left and right inputs of Join + let (left_joins, right_joins) = + (gather_joins(&j.left), gather_joins(&j.right)); + + // Add left_joins and right_joins to HashSet + join_info.extend(left_joins); + join_info.extend(right_joins); + } else { + // We don't run the rule if there are non-inner joins in the query + return HashSet::new(); + } + } + LogicalPlan::CrossJoin(ref c) => { + // Recurse on left and right inputs of CrossJoin + let (left_joins, right_joins) = (gather_joins(&c.left), gather_joins(&c.right)); + + // Add left_joins and right_joins to HashSet + join_info.extend(left_joins); + join_info.extend(right_joins); + } + LogicalPlan::Union(ref u) => { + // Recurse on inputs vector of Union + for input in &u.inputs { + let joins = gather_joins(input); + + // Add joins to HashSet + join_info.extend(joins); + } + } + _ => { + warn!("Skipping optimizer rule 'DynamicPartitionPruning'"); + return HashSet::new(); + } + } + break; + } else { + // Move on to next step + current_plan = current_plan.inputs()[0].clone(); + } + } + join_info +} + +/// Represents relevant information in a TableScan +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct TableInfo { + /// The name of the table + table_name: String, + /// The path and filename of the table + filepath: String, + /// The number of rows in the table + size: Option, + /// Optional expressions to be used as filters by the table provider + filters: Vec, +} + +// This function parses through the LogicalPlan, grabs relevant information from a TableScan, and +// adds them to a HashMap where the key is the table name +fn gather_tables(plan: &LogicalPlan) -> HashMap { + let mut current_plan = plan.clone(); + let mut tables = HashMap::new(); + loop { + if current_plan.inputs().is_empty() { + if let LogicalPlan::TableScan(ref t) = current_plan { + // Use TableScan to get the filepath and/or size + let filepath = get_filepath(¤t_plan); + let size = get_table_size(¤t_plan); + match filepath { + Some(f) => { + // TODO: Add better handling for when a table is read in more than once + // https://github.com/dask-contrib/dask-sql/issues/1121 + if tables.contains_key(&t.table_name.to_string()) { + return HashMap::new(); + } + + tables.insert( + t.table_name.to_string(), + TableInfo { + table_name: t.table_name.to_string(), + filepath: f.clone(), + size, + filters: t.filters.clone(), + }, + ); + break; + } + None => return HashMap::new(), + } + } + break; + } else if current_plan.inputs().len() > 1 { + match current_plan { + LogicalPlan::Join(ref j) => { + // Recurse on left and right inputs of Join + let (left_tables, right_tables) = + (gather_tables(&j.left), gather_tables(&j.right)); + + if check_table_overlaps(&tables, &left_tables, &right_tables) { + return HashMap::new(); + } + + // Add left_tables and right_tables to HashMap + tables.extend(left_tables); + tables.extend(right_tables); + } + LogicalPlan::CrossJoin(ref c) => { + // Recurse on left and right inputs of CrossJoin + let (left_tables, right_tables) = + (gather_tables(&c.left), gather_tables(&c.right)); + + if check_table_overlaps(&tables, &left_tables, &right_tables) { + return HashMap::new(); + } + + // Add left_tables and right_tables to HashMap + tables.extend(left_tables); + tables.extend(right_tables); + } + LogicalPlan::Union(ref u) => { + // Recurse on inputs vector of Union + for input in &u.inputs { + let union_tables = gather_tables(input); + + // TODO: Add better handling for when a table is read in more than once + // https://github.com/dask-contrib/dask-sql/issues/1121 + if tables.keys().any(|k| union_tables.contains_key(k)) + || union_tables.keys().any(|k| tables.contains_key(k)) + { + return HashMap::new(); + } + + // Add union_tables to HashMap + tables.extend(union_tables); + } + } + _ => { + warn!("Skipping optimizer rule 'DynamicPartitionPruning'"); + return HashMap::new(); + } + } + break; + } else { + // Move on to next step + current_plan = current_plan.inputs()[0].clone(); + } + } + tables +} + +// TODO: Add better handling for when a table is read in more than once +// https://github.com/dask-contrib/dask-sql/issues/1121 +fn check_table_overlaps( + m1: &HashMap, + m2: &HashMap, + m3: &HashMap, +) -> bool { + m1.keys().any(|k| m2.contains_key(k)) + || m2.keys().any(|k| m1.contains_key(k)) + || m1.keys().any(|k| m3.contains_key(k)) + || m3.keys().any(|k| m1.contains_key(k)) + || m2.keys().any(|k| m3.contains_key(k)) + || m3.keys().any(|k| m2.contains_key(k)) +} + +fn get_filepath(plan: &LogicalPlan) -> Option<&String> { + match plan { + LogicalPlan::TableScan(scan) => scan + .source + .as_any() + .downcast_ref::()? + .filepath(), + _ => None, + } +} + +fn get_table_size(plan: &LogicalPlan) -> Option { + match plan { + LogicalPlan::TableScan(scan) => scan + .source + .as_any() + .downcast_ref::()? + .statistics() + .map(|stats| stats.get_row_count() as usize), + _ => None, + } +} + +// This function parses through the LogicalPlan, grabs any aliases, and adds them to a HashMap +// where the key is the alias name and the value is the table name +fn gather_aliases(plan: &LogicalPlan) -> HashMap { + let mut current_plan = plan.clone(); + let mut aliases = HashMap::new(); + loop { + if current_plan.inputs().is_empty() { + break; + } else if current_plan.inputs().len() > 1 { + match current_plan { + LogicalPlan::Join(ref j) => { + // Recurse on left and right inputs of Join + let (left_aliases, right_aliases) = + (gather_aliases(&j.left), gather_aliases(&j.right)); + + // Add left_aliases and right_aliases to HashMap + aliases.extend(left_aliases); + aliases.extend(right_aliases); + } + LogicalPlan::CrossJoin(ref c) => { + // Recurse on left and right inputs of CrossJoin + let (left_aliases, right_aliases) = + (gather_aliases(&c.left), gather_aliases(&c.right)); + + // Add left_aliases and right_aliases to HashMap + aliases.extend(left_aliases); + aliases.extend(right_aliases); + } + LogicalPlan::Union(ref u) => { + // Recurse on inputs vector of Union + for input in &u.inputs { + let union_aliases = gather_aliases(input); + + // Add union_aliases to HashMap + aliases.extend(union_aliases); + } + } + _ => { + return HashMap::new(); + } + } + break; + } else { + if let LogicalPlan::SubqueryAlias(ref s) = current_plan { + match *s.input { + LogicalPlan::TableScan(ref t) => { + aliases.insert(s.alias.clone(), t.table_name.to_string().clone()); + } + // Sometimes a TableScan is immediately followed by a Projection, so we can + // still use the alias for the table + LogicalPlan::Projection(ref p) => { + if let LogicalPlan::TableScan(ref t) = *p.input { + aliases.insert(s.alias.clone(), t.table_name.to_string().clone()); + } + } + _ => (), + } + } + // Move on to next step + current_plan = current_plan.inputs()[0].clone(); + } + } + aliases +} + +// Wrapper for floats, since they are not hashable +#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] +struct FloatWrapper(f64); + +impl Eq for FloatWrapper {} + +impl Hash for FloatWrapper { + fn hash(&self, state: &mut H) { + // Convert the f64 to a u64 using transmute + let bits: u64 = self.0.to_bits(); + // Use the u64's hash implementation + bits.hash(state); + } +} + +// Wrapper for possible row value types +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +enum RowValue { + String(Option), + Int64(Option), + Int32(Option), + Double(Option), +} + +// This function uses the table name, column name, and filters to read in the relevant columns, +// filter out row values, and construct a HashSet of relevant row values for the specified column, +// i.e., the column involved in the join +fn read_table( + table_string: String, + field_string: String, + tables: HashMap, +) -> Option> { + // Obtain filepaths to all relevant Parquet files, e.g., in a directory of Parquet files + let paths = fs::read_dir(tables.get(&table_string).unwrap().filepath.clone()).unwrap(); + let mut files = vec![]; + for path in paths { + files.push(path.unwrap().path().display().to_string()) + } + + // Using the filepaths to the Parquet tables, obtain the schemas of the relevant tables + let schema: &Type = &SerializedFileReader::try_from(files[0].clone()) + .unwrap() + .metadata() + .file_metadata() + .schema() + .clone(); + + // Use the schemas of the relevant tables to obtain the physical type of the relevant columns + let physical_type = get_physical_type(schema, field_string.clone()); + + // A TableScan may include existing filters. These conditions should be used to filter the data + // after being read. Therefore, the columns involved in these filters should be read in as well + let filters = tables.get(&table_string).unwrap().filters.clone(); + let filtered_fields = get_filtered_fields(&filters, schema, field_string.clone()); + let filtered_string = filtered_fields.0; + let filtered_types = filtered_fields.1; + let filtered_names = filtered_fields.2; + + if filters.len() != filtered_names.len() { + warn!("Unable to check existing filters for optimizer rule 'DynamicPartitionPruning'"); + return None; + } + + // Specify which columns to include in the reader, then read in the rows + let repetition = get_repetition(schema, field_string.clone()); + let physical_type = physical_type.unwrap().to_string(); + let projection_schema = "message schema { ".to_owned() + + &filtered_string + + &repetition.unwrap() + + " " + + &physical_type + + " " + + &field_string + + "; }"; + let projection = parse_message_type(&projection_schema).ok(); + + let mut rows = Vec::new(); + for file in files { + let reader_result = SerializedFileReader::try_from(&*file.clone()); + if let Ok(reader) = reader_result { + let row_iter_result = RowIter::from_file_into(Box::new(reader)) + .project(projection.clone()) + .ok(); + if let Some(row_iter) = row_iter_result { + rows.extend(row_iter); + } else { + // TODO: Investigate cases when this would happen + rows.clear(); + break; + } + } else { + rows.clear(); + break; + } + } + if rows.is_empty() { + return None; + } + + // Create HashSets for the join column values + let mut value_set: HashSet = HashSet::new(); + for row in rows { + // Since a TableScan may have its own filters, we want to ensure that the values in + // value_set satisfy the TableScan filters + let mut satisfies_filters = true; + let mut row_index = 0; + for index in 0..filters.len() { + if filtered_names[index] != field_string { + let current_type = &filtered_types[index]; + match current_type.as_str() { + "BYTE_ARRAY" => { + let string_value = row.get_string(row_index).ok(); + if !satisfies_string(string_value, filters[index].clone()) { + satisfies_filters = false; + } + } + "INT64" => { + let long_value = row.get_long(row_index).ok(); + if !satisfies_int64(long_value, filters[index].clone()) { + satisfies_filters = false; + } + } + "INT32" => { + let int_value = row.get_int(row_index).ok(); + if !satisfies_int32(int_value, filters[index].clone()) { + satisfies_filters = false; + } + } + "DOUBLE" => { + let double_value = row.get_double(row_index).ok(); + if !satisfies_float(double_value, filters[index].clone()) { + satisfies_filters = false; + } + } + u => panic!("Unknown PhysicalType {u}"), + } + row_index += 1; + } + } + // After verifying that the row satisfies all existing filters, we add the column value to + // the HashSet + if satisfies_filters { + match physical_type.as_str() { + "BYTE_ARRAY" => { + let r = row.get_string(row_index).ok(); + value_set.insert(RowValue::String(r.cloned())); + } + "INT64" => { + let r = row.get_long(row_index).ok(); + value_set.insert(RowValue::Int64(r)); + } + "INT32" => { + let r = row.get_int(row_index).ok(); + value_set.insert(RowValue::Int32(r)); + } + "DOUBLE" => { + let r = row.get_double(row_index).ok(); + if let Some(f) = r { + value_set.insert(RowValue::Double(Some(FloatWrapper(f)))); + } else { + value_set.insert(RowValue::Double(None)); + } + } + _ => panic!("Unknown PhysicalType"), + } + } + } + + Some(value_set) +} + +// A column has a physical_type (INT64, etc.) that needs to be included when specifying which +// columns to read in. To get the physical_type, we grab it from the schema +fn get_physical_type(schema: &Type, field: String) -> Option { + match schema { + Type::GroupType { + basic_info: _, + fields, + } => { + for f in fields { + let match_field = &*f.clone(); + match match_field { + Type::PrimitiveType { + basic_info, + physical_type, + .. + } => { + if basic_info.name() == field { + return Some(*physical_type); + } + } + _ => return None, + } + } + None + } + _ => None, + } +} + +// A column has a repetition (i.e., REQUIRED or OPTIONAL) that needs to be included when specifying +// which columns to read in. To get the repetition, we grab it from the schema +fn get_repetition(schema: &Type, field: String) -> Option { + match schema { + Type::GroupType { + basic_info: _, + fields, + } => { + for f in fields { + let match_field = &*f.clone(); + match match_field { + Type::PrimitiveType { basic_info, .. } => { + if basic_info.name() == field { + return Some(basic_info.repetition().to_string()); + } + } + _ => return None, + } + } + None + } + _ => None, + } +} + +// This is a helper function to deal with TableScan filters for reading in the data. The first +// value returned is a string representation of the projection used to read in the relevant +// columns. The second value returned is a vector of the physical_type of each column that has has +// a filter, in the order that they are being read. The third value returned is a vector of the +// column names, in the order that they are being read. +fn get_filtered_fields( + filters: &Vec, + schema: &Type, + field: String, +) -> (String, Vec, Vec) { + // Used to create a string representation of the projection + // for the TableScan filters to be read + let mut filtered_fields = vec![]; + // All physical types involved in TableScan filters + let mut filtered_types = vec![]; + // All columns involved in TableScan filters + let mut filtered_columns = vec![]; + for filter in filters { + match filter { + Expr::BinaryExpr(b) => { + if let Expr::Column(column) = &*b.left { + push_filtered_fields( + column, + schema, + field.clone(), + &mut filtered_fields, + &mut filtered_columns, + &mut filtered_types, + ); + } + } + Expr::IsNotNull(e) => { + if let Expr::Column(column) = &**e { + push_filtered_fields( + column, + schema, + field.clone(), + &mut filtered_fields, + &mut filtered_columns, + &mut filtered_types, + ); + } + } + _ => (), + } + } + (filtered_fields.join(""), filtered_types, filtered_columns) +} + +// Helper function for get_filtered_fields +fn push_filtered_fields( + column: &Column, + schema: &Type, + field: String, + filtered_fields: &mut Vec, + filtered_columns: &mut Vec, + filtered_types: &mut Vec, +) { + let current_field = column.name.clone(); + let physical_type = get_physical_type(schema, current_field.clone()) + .unwrap() + .to_string(); + if current_field != field { + let repetition = get_repetition(schema, current_field.clone()); + filtered_fields.push(repetition.unwrap()); + filtered_fields.push(" ".to_string()); + + filtered_fields.push(physical_type.clone()); + filtered_fields.push(" ".to_string()); + + filtered_fields.push(current_field.clone()); + filtered_fields.push("; ".to_string()); + } + filtered_types.push(physical_type); + filtered_columns.push(current_field); +} + +// Returns a boolean representing whether a string satisfies a given filter +fn satisfies_string(string_value: Option<&String>, filter: Expr) -> bool { + match filter { + Expr::BinaryExpr(b) => match b.op { + Operator::Eq => Expr::Literal(ScalarValue::Utf8(string_value.cloned())) == *b.right, + Operator::NotEq => Expr::Literal(ScalarValue::Utf8(string_value.cloned())) != *b.right, + _ => { + panic!("Unknown satisfies_string operator"); + } + }, + Expr::IsNotNull(_) => string_value.is_some(), + _ => { + panic!("Unknown satisfies_string Expr"); + } + } +} + +// Returns a boolean representing whether an Int64 satisfies a given filter +fn satisfies_int64(long_value: Option, filter: Expr) -> bool { + match filter { + Expr::BinaryExpr(b) => { + let filter_value = *b.right; + let int_value: i64 = match filter_value { + Expr::Literal(ScalarValue::Int64(i)) => i.unwrap(), + Expr::Literal(ScalarValue::Int32(i)) => i64::from(i.unwrap()), + Expr::Literal(ScalarValue::Float64(i)) => i.unwrap() as i64, + Expr::Literal(ScalarValue::TimestampNanosecond(i, None)) => i.unwrap(), + _ => { + panic!("Unknown ScalarValue type {filter_value}"); + } + }; + let filter_value = Expr::Literal(ScalarValue::Int64(Some(int_value))); + match b.op { + Operator::Eq => Expr::Literal(ScalarValue::Int64(long_value)) == filter_value, + Operator::NotEq => Expr::Literal(ScalarValue::Int64(long_value)) != filter_value, + Operator::Gt => Expr::Literal(ScalarValue::Int64(long_value)) > filter_value, + Operator::Lt => Expr::Literal(ScalarValue::Int64(long_value)) < filter_value, + Operator::GtEq => Expr::Literal(ScalarValue::Int64(long_value)) >= filter_value, + Operator::LtEq => Expr::Literal(ScalarValue::Int64(long_value)) <= filter_value, + _ => { + panic!("Unknown satisfies_int64 operator"); + } + } + } + Expr::IsNotNull(_) => long_value.is_some(), + _ => { + panic!("Unknown satisfies_int64 Expr"); + } + } +} + +// Returns a boolean representing whether an Int32 satisfies a given filter +fn satisfies_int32(long_value: Option, filter: Expr) -> bool { + match filter { + Expr::BinaryExpr(b) => { + let filter_value = *b.right; + let int_value: i32 = match filter_value { + Expr::Literal(ScalarValue::Int64(i)) => i.unwrap() as i32, + Expr::Literal(ScalarValue::Int32(i)) => i.unwrap(), + Expr::Literal(ScalarValue::Float64(i)) => i.unwrap() as i32, + _ => { + panic!("Unknown ScalarValue type {filter_value}"); + } + }; + let filter_value = Expr::Literal(ScalarValue::Int32(Some(int_value))); + match b.op { + Operator::Eq => Expr::Literal(ScalarValue::Int32(long_value)) == filter_value, + Operator::NotEq => Expr::Literal(ScalarValue::Int32(long_value)) != filter_value, + Operator::Gt => Expr::Literal(ScalarValue::Int32(long_value)) > filter_value, + Operator::Lt => Expr::Literal(ScalarValue::Int32(long_value)) < filter_value, + Operator::GtEq => Expr::Literal(ScalarValue::Int32(long_value)) >= filter_value, + Operator::LtEq => Expr::Literal(ScalarValue::Int32(long_value)) <= filter_value, + _ => { + panic!("Unknown satisfies_int32 operator"); + } + } + } + Expr::IsNotNull(_) => long_value.is_some(), + _ => { + panic!("Unknown satisfies_int32 Expr"); + } + } +} + +// Returns a boolean representing whether an Float64 satisfies a given filter +fn satisfies_float(long_value: Option, filter: Expr) -> bool { + match filter { + Expr::BinaryExpr(b) => { + let filter_value = *b.right; + let float_value: f64 = match filter_value { + Expr::Literal(ScalarValue::Int64(i)) => i.unwrap() as f64, + Expr::Literal(ScalarValue::Int32(i)) => i.unwrap() as f64, + Expr::Literal(ScalarValue::Float64(i)) => i.unwrap(), + _ => { + panic!("Unknown ScalarValue type {filter_value}"); + } + }; + let filter_value = Expr::Literal(ScalarValue::Float64(Some(float_value))); + match b.op { + Operator::Eq => Expr::Literal(ScalarValue::Float64(long_value)) == filter_value, + Operator::NotEq => Expr::Literal(ScalarValue::Float64(long_value)) != filter_value, + Operator::Gt => Expr::Literal(ScalarValue::Float64(long_value)) > filter_value, + Operator::Lt => Expr::Literal(ScalarValue::Float64(long_value)) < filter_value, + Operator::GtEq => Expr::Literal(ScalarValue::Float64(long_value)) >= filter_value, + Operator::LtEq => Expr::Literal(ScalarValue::Float64(long_value)) <= filter_value, + _ => { + panic!("Unknown satisfies_float operator"); + } + } + } + Expr::IsNotNull(_) => long_value.is_some(), + _ => { + panic!("Unknown satisfies_float Expr"); + } + } +} + +// Used to simplify the signature of combine_sets +type RowHashSet = HashSet; +type RowOptionHashSet = Option; +type RowTuple = (RowOptionHashSet, RowOptionHashSet); +type RowVec = Vec; + +// Given a vector of hashsets to be set as TableScan filters, a vector of tuples representing the +// tables involved in a join, a vector of tuples representing the columns involved in a join, and +// a hashset of fact tables in the query; return a hashmap where the key is a tuple of the table +// and column names, and the value is the hashset representing the INLIST filter specified in the +// TableScan. +fn combine_sets( + join_values: RowVec, + join_tables: Vec<(String, String)>, + join_fields: Vec<(String, String)>, + fact_tables: HashSet, +) -> HashMap<(String, String), HashSet> { + let mut sets: HashMap<(String, String), HashSet> = HashMap::new(); + for i in 0..join_values.len() { + // Case when we were able to read in both tables involved in the join + if let (Some(set1), Some(set2)) = (&join_values[i].0, &join_values[i].1) { + // The INLIST vector will be the intersection of both hashsets + let set_intersection = set1.intersection(set2); + let mut values = HashSet::new(); + for value in set_intersection { + values.insert(value.clone()); + } + + let current_table = join_tables[i].0.clone(); + // We only create INLIST filters for fact tables + if fact_tables.contains(¤t_table) { + let current_field = join_fields[i].0.clone(); + add_to_existing_set(&mut sets, values.clone(), current_table, current_field); + } + + let current_table = join_tables[i].1.clone(); + // We only create INLIST filters for fact tables + if fact_tables.contains(¤t_table) { + let current_field = join_fields[i].1.clone(); + add_to_existing_set(&mut sets, values.clone(), current_table, current_field); + } + // Case when we were only able to read in the left table of the join + } else if let Some(values) = &join_values[i].0 { + let current_table = join_tables[i].0.clone(); + // We only create INLIST filters for fact tables + if fact_tables.contains(¤t_table) { + let current_field = join_fields[i].0.clone(); + add_to_existing_set(&mut sets, values.clone(), current_table, current_field); + } + + let current_table = join_tables[i].1.clone(); + // We only create INLIST filters for fact tables + if fact_tables.contains(¤t_table) { + let current_field = join_fields[i].1.clone(); + add_to_existing_set(&mut sets, values.clone(), current_table, current_field); + } + // Case when we were only able to read in the right table of the join + } else if let Some(values) = &join_values[i].1 { + let current_table = join_tables[i].0.clone(); + // We only create INLIST filters for fact tables + if fact_tables.contains(¤t_table) { + let current_field = join_fields[i].0.clone(); + add_to_existing_set(&mut sets, values.clone(), current_table, current_field); + } + + let current_table = join_tables[i].1.clone(); + // We only create INLIST filters for fact tables + if fact_tables.contains(¤t_table) { + let current_field = join_fields[i].1.clone(); + add_to_existing_set(&mut sets, values.clone(), current_table, current_field); + } + } + } + sets +} + +// Given a mutable hashmap (the hashmap which will eventually be returned by the `combine_sets` +// function), a hashset of values, a table name, and a column name; insert the hashset of values +// into the hashmap, where the key is a tuple of the table and column names. +fn add_to_existing_set( + sets: &mut HashMap<(String, String), HashSet>, + values: HashSet, + current_table: String, + current_field: String, +) { + let existing_set = sets.get(&(current_table.clone(), current_field.clone())); + match existing_set { + // If the tuple for (current_table, current_field) already exists, then we want to combine + // the existing set with the new hashset being inserted; to do this, we take the + // intersection of both sets. + Some(s) => { + let s = s.clone(); + let v = values.iter().cloned().collect::>(); + let s = s.intersection(&v); + let mut set_intersection = HashSet::new(); + for i in s { + set_intersection.insert(i.clone()); + } + sets.insert((current_table, current_field), set_intersection.clone()); + } + // If the tuple for (current_table, current_field) does not already exist as a key in the + // hashmap, then simply create it and set the hashset as the value + None => { + sets.insert((current_table, current_field), values); + } + } +} + +// Given a LogicalPlan and a hashmap where the key is a tuple containing a table name and column +// and the value is a hashset of unique row values, parse the LogicalPlan and insert INLIST filters +// at the TableScan level. +fn optimize_table_scans( + plan: &LogicalPlan, + filter_values: HashMap<(String, String), HashSet>, +) -> Result> { + // Replaces existing TableScan with a new TableScan which includes + // the new binary expression filter created from reading in the join columns + match plan { + LogicalPlan::TableScan(t) => { + let table_name = t.table_name.to_string(); + let table_filters: HashMap<(String, String), HashSet> = filter_values + .iter() + .filter(|(key, _value)| key.0 == table_name) + .map(|(key, value)| ((key.0.to_owned(), key.1.to_owned()), value.clone())) + .collect(); + let mut updated_filters = t.filters.clone(); + for (key, value) in table_filters.iter() { + let current_expr = + format_inlist_expr(value.clone(), key.0.to_owned(), key.1.to_owned()); + if let Some(e) = current_expr { + updated_filters.push(e); + } + } + let scan = LogicalPlan::TableScan(TableScan { + table_name: t.table_name.clone(), + source: t.source.clone(), + projection: t.projection.clone(), + projected_schema: t.projected_schema.clone(), + filters: updated_filters, + fetch: t.fetch, + }); + Ok(Some(scan)) + } + _ => optimize_children(plan, filter_values), + } +} + +// Given a hashset of values, a table name, and a column name, return a DataFusion INLIST Expr +fn format_inlist_expr( + value_set: HashSet, + join_table: String, + join_field: String, +) -> Option { + let expr = Box::new(Expr::Column(Column::new(Some(join_table), join_field))); + let mut list: Vec = vec![]; + + // Need to correctly format the ScalarValue type + for value in value_set { + if let RowValue::String(s) = value { + if s.is_some() { + let v = Expr::Literal(ScalarValue::Utf8(s)); + list.push(v); + } + } else if let RowValue::Int64(l) = value { + if l.is_some() { + let v = Expr::Literal(ScalarValue::Int64(l)); + list.push(v); + } + } else if let RowValue::Int32(i) = value { + if i.is_some() { + let v = Expr::Literal(ScalarValue::Int32(i)); + list.push(v); + } + } else if let RowValue::Double(Some(f)) = value { + let v = Expr::Literal(ScalarValue::Float64(Some(f.0))); + list.push(v); + } + } + + if list.is_empty() { + None + } else { + Some(Expr::InList { + expr, + list, + negated: false, + }) + } +} + +// Given a LogicalPlan and the same hashmap as the `optimize_table_scans` function, correctly +// iterate through the LogicalPlan nodes. Similar to DataFusion's `optimize_children` function, but +// recurses on the `optimize_table_scans` function instead. +fn optimize_children( + plan: &LogicalPlan, + filter_values: HashMap<(String, String), HashSet>, +) -> Result> { + let new_exprs = plan.expressions(); + let mut new_inputs = Vec::with_capacity(plan.inputs().len()); + let mut plan_is_changed = false; + for input in plan.inputs() { + let new_input = optimize_table_scans(input, filter_values.clone())?; + plan_is_changed = plan_is_changed || new_input.is_some(); + new_inputs.push(new_input.unwrap_or_else(|| input.clone())) + } + if plan_is_changed { + Ok(Some(from_plan(plan, &new_exprs, &new_inputs)?)) + } else { + Ok(None) + } +} diff --git a/dask_planner/src/sql/table.rs b/dask_planner/src/sql/table.rs index f25f891ec..abe71733a 100644 --- a/dask_planner/src/sql/table.rs +++ b/dask_planner/src/sql/table.rs @@ -51,7 +51,6 @@ impl DaskTableSource { } /// Access optional filepath associated with this table source - #[allow(dead_code)] pub fn filepath(&self) -> Option<&String> { self.filepath.as_ref() } diff --git a/dask_sql/context.py b/dask_sql/context.py index 837f7cd1c..0b6f8faf8 100644 --- a/dask_sql/context.py +++ b/dask_sql/context.py @@ -102,6 +102,10 @@ def __init__(self, logging_level=logging.INFO): self.context = DaskSQLContext(self.catalog_name, self.schema_name) self.context.register_schema(self.schema_name, DaskSchema(self.schema_name)) + self.context.apply_dynamic_partition_pruning( + dask_config.get("sql.dynamic_partition_pruning") + ) + # # Register any default plugins, if nothing was registered before. RelConverter.add_plugin_class(logical.DaskAggregatePlugin, replace=False) RelConverter.add_plugin_class(logical.DaskCrossJoinPlugin, replace=False) @@ -795,6 +799,9 @@ def _get_ral(self, sql): """Helper function to turn the sql query into a relational algebra and resulting column names""" logger.debug(f"Entering _get_ral('{sql}')") + self.context.apply_dynamic_partition_pruning( + dask_config.get("sql.dynamic_partition_pruning") + ) # get the schema of what we currently have registered schemas = self._prepare_schemas() diff --git a/dask_sql/sql-schema.yaml b/dask_sql/sql-schema.yaml index 63aad44aa..eaab6936a 100644 --- a/dask_sql/sql-schema.yaml +++ b/dask_sql/sql-schema.yaml @@ -64,6 +64,11 @@ properties: description: | Whether to try pushing down filter predicates into IO (when possible). + dynamic_partition_pruning: + type: boolean + description: | + Whether to apply the dynamic partition pruning optimizer rule. + sort: type: object properties: diff --git a/dask_sql/sql.yaml b/dask_sql/sql.yaml index 786bc2e74..42434d20d 100644 --- a/dask_sql/sql.yaml +++ b/dask_sql/sql.yaml @@ -16,6 +16,8 @@ sql: predicate_pushdown: True + dynamic_partition_pruning: True + sort: topk-nelem-limit: 1000000 From 5421bbf9b363ab15c657432e0c9d367c6f236df7 Mon Sep 17 00:00:00 2001 From: Sarah Yurick <53962159+sarahyurick@users.noreply.github.com> Date: Fri, 23 Jun 2023 13:21:37 -0700 Subject: [PATCH 06/25] Support `DATE` Extraction (#984) * support date extraction * style fix * remove extractdateoperation * use strftime * convert str to datetime * cudf behavior * apply Charles suggestions * revert rust change * Update dialect.rs * add test * style * add check_index * handle scalar input * add RuntimeError * style fix * use xfail --------- Co-authored-by: Ayush Dattagupta Co-authored-by: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> --- dask_planner/src/dialect.rs | 29 ++++++++++++ dask_planner/src/sql.rs | 14 ++++++ dask_sql/_compat.py | 2 + dask_sql/physical/rex/core/call.py | 12 +++++ tests/integration/test_rex.py | 71 +++++++++++++++++++++++++++++- tests/unit/test_call.py | 29 ++++++------ 6 files changed, 142 insertions(+), 15 deletions(-) diff --git a/dask_planner/src/dialect.rs b/dask_planner/src/dialect.rs index 9fe013f3d..24f507dec 100644 --- a/dask_planner/src/dialect.rs +++ b/dask_planner/src/dialect.rs @@ -194,6 +194,35 @@ impl Dialect for DaskDialect { special: false, }))) } + Token::Word(w) if w.value.to_lowercase() == "extract" => { + // EXTRACT(DATE FROM d) + parser.next_token(); // skip extract + parser.expect_token(&Token::LParen)?; + if !parser.parse_keywords(&[Keyword::DATE, Keyword::FROM]) { + // Parse EXTRACT(x FROM d) as normal + parser.prev_token(); + parser.prev_token(); + return Ok(None); + } + let expr = parser.parse_expr()?; + parser.expect_token(&Token::RParen)?; + + // convert to function args + let args = vec![ + FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value( + Value::SingleQuotedString("DATE".to_string()), + ))), + FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)), + ]; + + Ok(Some(Expr::Function(Function { + name: ObjectName(vec![Ident::new("extract_date")]), + args, + over: None, + distinct: false, + special: false, + }))) + } _ => Ok(None), } } diff --git a/dask_planner/src/sql.rs b/dask_planner/src/sql.rs index 941eb9e02..d87bfcc76 100644 --- a/dask_planner/src/sql.rs +++ b/dask_planner/src/sql.rs @@ -310,6 +310,20 @@ impl ContextProvider for DaskSQLContext { let rtf: ReturnTypeFunction = Arc::new(|_| Ok(Arc::new(DataType::Int64))); return Some(Arc::new(ScalarUDF::new(name, &sig, &rtf, &fun))); } + "extract_date" => { + let sig = Signature::one_of( + vec![ + TypeSignature::Exact(vec![DataType::Utf8, DataType::Date64]), + TypeSignature::Exact(vec![ + DataType::Utf8, + DataType::Timestamp(TimeUnit::Nanosecond, None), + ]), + ], + Volatility::Immutable, + ); + let rtf: ReturnTypeFunction = Arc::new(|_| Ok(Arc::new(DataType::Date64))); + return Some(Arc::new(ScalarUDF::new(name, &sig, &rtf, &fun))); + } _ => (), } diff --git a/dask_sql/_compat.py b/dask_sql/_compat.py index 0ed1c8c37..f76982a4c 100644 --- a/dask_sql/_compat.py +++ b/dask_sql/_compat.py @@ -18,3 +18,5 @@ # Parquet predicate-support version checks PQ_NOT_IN_SUPPORT = parseVersion(dask.__version__) > parseVersion("2023.5.1") PQ_IS_SUPPORT = parseVersion(dask.__version__) >= parseVersion("2023.3.1") + +DASK_CUDF_TODATETIME_SUPPORT = _dask_version >= parseVersion("2023.5.1") diff --git a/dask_sql/physical/rex/core/call.py b/dask_sql/physical/rex/core/call.py index ab2ecaeba..db604da3a 100644 --- a/dask_sql/physical/rex/core/call.py +++ b/dask_sql/physical/rex/core/call.py @@ -15,6 +15,7 @@ from dask.utils import random_state_data from dask_planner.rust import SqlTypeName +from dask_sql._compat import DASK_CUDF_TODATETIME_SUPPORT from dask_sql.datacontainer import DataContainer from dask_sql.mappings import ( cast_column_to_type, @@ -929,6 +930,16 @@ def date_part(self, what, df: SeriesOrScalar): return df.week elif what in {"YEAR", "YEARS"}: return df.year + elif what == "DATE": + if isinstance(df, pd.Timestamp): + return df.date() + else: + if is_cudf_type(df) and not DASK_CUDF_TODATETIME_SUPPORT: + raise RuntimeError( + "Dask-cuDF to_datetime support requires Dask version >= 2023.5.1" + ) + else: + return dd.to_datetime(df.strftime("%Y-%m-%d")) else: raise NotImplementedError(f"Extraction of {what} is not (yet) implemented.") @@ -1070,6 +1081,7 @@ class RexCallPlugin(BaseRexPlugin): "coalesce": CoalesceOperation(), "replace": ReplaceOperation(), # date/time operations + "extract_date": ExtractOperation(), "localtime": Operation(lambda *args: pd.Timestamp.now()), "localtimestamp": Operation(lambda *args: pd.Timestamp.now()), "current_time": Operation(lambda *args: pd.Timestamp.now()), diff --git a/tests/integration/test_rex.py b/tests/integration/test_rex.py index 2c761abd0..93d77dca5 100644 --- a/tests/integration/test_rex.py +++ b/tests/integration/test_rex.py @@ -5,6 +5,7 @@ import pandas as pd import pytest +from dask_sql._compat import DASK_CUDF_TODATETIME_SUPPORT from tests.utils import assert_eq @@ -759,10 +760,11 @@ def test_date_functions(c): EXTRACT(SECOND FROM d) AS "second", EXTRACT(WEEK FROM d) AS "week", EXTRACT(YEAR FROM d) AS "year", + EXTRACT(DATE FROM d) AS "date", LAST_DAY(d) as "last_day", - TIMESTAMPADD(YEAR, 2, d) as "plus_1_year", + TIMESTAMPADD(YEAR, 1, d) as "plus_1_year", TIMESTAMPADD(MONTH, 1, d) as "plus_1_month", TIMESTAMPADD(WEEK, 1, d) as "plus_1_week", TIMESTAMPADD(DAY, 1, d) as "plus_1_day", @@ -806,8 +808,9 @@ def test_date_functions(c): "second": [42], "week": [39], "year": [2021], + "date": [datetime(2021, 10, 3)], "last_day": [datetime(2021, 10, 31, 15, 53, 42, 47)], - "plus_1_year": [datetime(2023, 10, 3, 15, 53, 42, 47)], + "plus_1_year": [datetime(2022, 10, 3, 15, 53, 42, 47)], "plus_1_month": [datetime(2021, 11, 3, 15, 53, 42, 47)], "plus_1_week": [datetime(2021, 10, 10, 15, 53, 42, 47)], "plus_1_day": [datetime(2021, 10, 4, 15, 53, 42, 47)], @@ -1054,3 +1057,67 @@ def test_totimestamp(c, gpu): } ) assert_eq(df, expected_df, check_dtype=False) + + +@pytest.mark.parametrize( + "gpu", + [ + False, + pytest.param( + True, + marks=( + pytest.mark.gpu, + pytest.mark.xfail( + not DASK_CUDF_TODATETIME_SUPPORT, + reason="Requires https://github.com/dask/dask/pull/9881", + raises=RuntimeError, + ), + ), + ), + ], +) +def test_extract_date(c, gpu): + df = pd.DataFrame( + { + "a": [1, 2, 3], + "b": [4, 5, 6], + } + ) + df["t"] = [datetime(2021, 1, 1), datetime(2022, 2, 2), datetime(2023, 3, 3)] + c.create_table("df", df, gpu=gpu) + + result = c.sql("SELECT EXTRACT(DATE FROM t) AS e FROM df") + expected_df = pd.DataFrame( + {"e": [datetime(2021, 1, 1), datetime(2022, 2, 2), datetime(2023, 3, 3)]} + ) + assert_eq(result, expected_df) + + result = c.sql("SELECT * FROM df WHERE EXTRACT(DATE FROM t) > '2021-02-01'") + expected_df = pd.DataFrame( + { + "a": [2, 3], + "b": [5, 6], + "t": [datetime(2022, 2, 2), datetime(2023, 3, 3)], + } + ) + assert_eq(result, expected_df, check_index=False) + + result = c.sql( + "SELECT * FROM df WHERE EXTRACT(DATE FROM t) BETWEEN '2020-10-01' AND '2022-10-10'" + ) + expected_df = pd.DataFrame( + {"a": [1, 2], "b": [4, 5], "t": [datetime(2021, 1, 1), datetime(2022, 2, 2)]} + ) + assert_eq(result, expected_df) + + result = c.sql("SELECT TIMESTAMPADD(YEAR, 1, EXTRACT(DATE FROM t)) AS ta FROM df") + expected_df = pd.DataFrame( + {"ta": [datetime(2022, 1, 1), datetime(2023, 2, 2), datetime(2024, 3, 3)]} + ) + assert_eq(result, expected_df) + + result = c.sql("SELECT EXTRACT(DATE FROM t) + INTERVAL '2 days' AS i FROM df") + expected_df = pd.DataFrame( + {"i": [datetime(2021, 1, 3), datetime(2022, 2, 4), datetime(2023, 3, 5)]} + ) + assert_eq(result, expected_df) diff --git a/tests/unit/test_call.py b/tests/unit/test_call.py index 05b116af8..cb3a4b624 100644 --- a/tests/unit/test_call.py +++ b/tests/unit/test_call.py @@ -1,5 +1,5 @@ +import datetime import operator -from datetime import datetime from unittest.mock import MagicMock import dask.dataframe as dd @@ -190,7 +190,7 @@ def test_string_operations(): def test_dates(): op = call.ExtractOperation() - date = datetime(2021, 10, 3, 15, 53, 42, 47) + date = datetime.datetime(2021, 10, 3, 15, 53, 42, 47) assert int(op("CENTURY", date)) == 20 assert op("DAY", date) == 3 assert int(op("DECADE", date)) == 202 @@ -206,18 +206,21 @@ def test_dates(): assert op("SECOND", date) == 42 assert op("WEEK", date) == 39 assert op("YEAR", date) == 2021 + assert op("DATE", date) == datetime.date(2021, 10, 3) ceil_op = call.CeilFloorOperation("ceil") floor_op = call.CeilFloorOperation("floor") - assert ceil_op(date, "DAY") == datetime(2021, 10, 4) - assert ceil_op(date, "HOUR") == datetime(2021, 10, 3, 16) - assert ceil_op(date, "MINUTE") == datetime(2021, 10, 3, 15, 54) - assert ceil_op(date, "SECOND") == datetime(2021, 10, 3, 15, 53, 43) - assert ceil_op(date, "MILLISECOND") == datetime(2021, 10, 3, 15, 53, 42, 1000) - - assert floor_op(date, "DAY") == datetime(2021, 10, 3) - assert floor_op(date, "HOUR") == datetime(2021, 10, 3, 15) - assert floor_op(date, "MINUTE") == datetime(2021, 10, 3, 15, 53) - assert floor_op(date, "SECOND") == datetime(2021, 10, 3, 15, 53, 42) - assert floor_op(date, "MILLISECOND") == datetime(2021, 10, 3, 15, 53, 42) + assert ceil_op(date, "DAY") == datetime.datetime(2021, 10, 4) + assert ceil_op(date, "HOUR") == datetime.datetime(2021, 10, 3, 16) + assert ceil_op(date, "MINUTE") == datetime.datetime(2021, 10, 3, 15, 54) + assert ceil_op(date, "SECOND") == datetime.datetime(2021, 10, 3, 15, 53, 43) + assert ceil_op(date, "MILLISECOND") == datetime.datetime( + 2021, 10, 3, 15, 53, 42, 1000 + ) + + assert floor_op(date, "DAY") == datetime.datetime(2021, 10, 3) + assert floor_op(date, "HOUR") == datetime.datetime(2021, 10, 3, 15) + assert floor_op(date, "MINUTE") == datetime.datetime(2021, 10, 3, 15, 53) + assert floor_op(date, "SECOND") == datetime.datetime(2021, 10, 3, 15, 53, 42) + assert floor_op(date, "MILLISECOND") == datetime.datetime(2021, 10, 3, 15, 53, 42) From 2a0fec37333d93767c4666b42e4499609a459ca9 Mon Sep 17 00:00:00 2001 From: ChrisJar Date: Fri, 30 Jun 2023 13:18:53 -0700 Subject: [PATCH 07/25] Add support for left semi and left anti joins (#1182) * Add beggining of support for left anti joins * Update for gpu * Add leftsemi test * Workaround column mismatch and update tests for gpu * Add cpu implementation of leftanti * Update xfail queries * Fix column renaming * Reverse test changes * Limit select_names in _compute_table_from_rel * Address reviews * Revert type change * Update type annotations Co-authored-by: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> * Update imports in base.py --------- Co-authored-by: Chris Jarrett Co-authored-by: Ayush Dattagupta Co-authored-by: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> --- dask_sql/context.py | 11 +++--- dask_sql/physical/rel/base.py | 17 ++++++--- dask_sql/physical/rel/logical/join.py | 49 +++++++++++++++++++------- tests/integration/test_join.py | 50 +++++++++++++++++++++++++++ tests/unit/test_queries.py | 1 - 5 files changed, 105 insertions(+), 23 deletions(-) diff --git a/dask_sql/context.py b/dask_sql/context.py index 0b6f8faf8..17c6d0055 100644 --- a/dask_sql/context.py +++ b/dask_sql/context.py @@ -845,15 +845,19 @@ def _get_ral(self, sql): def _compute_table_from_rel(self, rel: "LogicalPlan", return_futures: bool = True): dc = RelConverter.convert(rel, context=self) - # Optimization might remove some alias projects. Make sure to keep them here. - select_names = [field for field in rel.getRowType().getFieldList()] - if rel.get_current_node_type() == "Explain": return dc if dc is None: return + # Optimization might remove some alias projects. Make sure to keep them here. + select_names = [field for field in rel.getRowType().getFieldList()] + if select_names: + cc = dc.column_container + + select_names = select_names[: len(cc.columns)] + # Use FQ name if not unique and simple name if it is unique. If a join contains the same column # names the output col is prepended with the fully qualified column name field_counts = Counter([field.getName() for field in select_names]) @@ -864,7 +868,6 @@ def _compute_table_from_rel(self, rel: "LogicalPlan", return_futures: bool = Tru for field in select_names ] - cc = dc.column_container cc = cc.rename( { df_col: select_name diff --git a/dask_sql/physical/rel/base.py b/dask_sql/physical/rel/base.py index 520f14e6d..a1f378197 100644 --- a/dask_sql/physical/rel/base.py +++ b/dask_sql/physical/rel/base.py @@ -1,5 +1,5 @@ import logging -from typing import TYPE_CHECKING, List +from typing import TYPE_CHECKING, List, Optional import dask.dataframe as dd @@ -30,7 +30,7 @@ def convert(self, rel: "LogicalPlan", context: "dask_sql.Context") -> dd.DataFra @staticmethod def fix_column_to_row_type( - cc: ColumnContainer, row_type: "RelDataType" + cc: ColumnContainer, row_type: "RelDataType", join_type: Optional[str] = None ) -> ColumnContainer: """ Make sure that the given column container @@ -39,6 +39,8 @@ def fix_column_to_row_type( and will just "blindly" rename the columns. """ field_names = [str(x) for x in row_type.getFieldNames()] + if join_type in ("leftsemi", "leftanti"): + field_names = field_names[: len(cc.columns)] logger.debug(f"Renaming {cc.columns} to {field_names}") cc = cc.rename_handle_duplicates( @@ -84,7 +86,9 @@ def assert_inputs( return [RelConverter.convert(input_rel, context) for input_rel in input_rels] @staticmethod - def fix_dtype_to_row_type(dc: DataContainer, row_type: "RelDataType"): + def fix_dtype_to_row_type( + dc: DataContainer, row_type: "RelDataType", join_type: Optional[str] = None + ): """ Fix the dtype of the given data container (or: the df within it) to the data type given as argument. @@ -98,9 +102,12 @@ def fix_dtype_to_row_type(dc: DataContainer, row_type: "RelDataType"): df = dc.df cc = dc.column_container + field_list = row_type.getFieldList() + if join_type in ("leftsemi", "leftanti"): + field_list = field_list[: len(cc.columns)] + field_types = { - str(field.getQualifiedName()): field.getType() - for field in row_type.getFieldList() + str(field.getQualifiedName()): field.getType() for field in field_list } for field_name, field_type in field_types.items(): diff --git a/dask_sql/physical/rel/logical/join.py b/dask_sql/physical/rel/logical/join.py index 3aa3774d2..c1c904af6 100644 --- a/dask_sql/physical/rel/logical/join.py +++ b/dask_sql/physical/rel/logical/join.py @@ -14,6 +14,7 @@ from dask_sql.physical.rel.base import BaseRelPlugin from dask_sql.physical.rel.logical.filter import filter_or_scalar from dask_sql.physical.rex import RexConverter +from dask_sql.utils import is_cudf_type if TYPE_CHECKING: import dask_sql @@ -45,7 +46,8 @@ class DaskJoinPlugin(BaseRelPlugin): "LEFT": "left", "RIGHT": "right", "FULL": "outer", - "LEFTSEMI": "inner", # TODO: Need research here! This is likely not a true inner join + "LEFTSEMI": "leftsemi", + "LEFTANTI": "leftanti", } def convert(self, rel: "LogicalPlan", context: "dask_sql.Context") -> DataContainer: @@ -74,6 +76,10 @@ def convert(self, rel: "LogicalPlan", context: "dask_sql.Context") -> DataContai join_type = join.getJoinType() join_type = self.JOIN_TYPE_MAPPING[str(join_type)] + # TODO: update with correct implementation of leftsemi for CPU + # https://github.com/dask-contrib/dask-sql/issues/1190 + if join_type == "leftsemi" and not is_cudf_type(df_lhs_renamed): + join_type = "inner" # 3. The join condition can have two forms, that we can understand # (a) a = b @@ -170,14 +176,19 @@ def merge_single_partitions(lhs_partition, rhs_partition): # 6. So the next step is to make sure # we have the correct column order (and to remove the temporary join columns) - correct_column_order = list(df_lhs_renamed.columns) + list( - df_rhs_renamed.columns - ) + if join_type in ("leftsemi", "leftanti"): + correct_column_order = list(df_lhs_renamed.columns) + else: + correct_column_order = list(df_lhs_renamed.columns) + list( + df_rhs_renamed.columns + ) cc = ColumnContainer(df.columns).limit_to(correct_column_order) # and to rename them like the rel specifies row_type = rel.getRowType() field_specifications = [str(f) for f in row_type.getFieldNames()] + if join_type in ("leftsemi", "leftanti"): + field_specifications = field_specifications[: len(cc.columns)] cc = cc.rename( { @@ -185,7 +196,7 @@ def merge_single_partitions(lhs_partition, rhs_partition): for from_col, to_col in zip(cc.columns, field_specifications) } ) - cc = self.fix_column_to_row_type(cc, row_type) + cc = self.fix_column_to_row_type(cc, row_type, join_type) dc = DataContainer(df, cc) # 7. Last but not least we apply any filters by and-chaining together the filters @@ -202,7 +213,7 @@ def merge_single_partitions(lhs_partition, rhs_partition): df = filter_or_scalar(df, filter_condition) dc = DataContainer(df, cc) - dc = self.fix_dtype_to_row_type(dc, rel.getRowType()) + dc = self.fix_dtype_to_row_type(dc, rel.getRowType(), join_type) # # Rename underlying DataFrame column names back to their original values before returning # df = dc.assign() # dc = DataContainer(df, ColumnContainer(cc.columns)) @@ -227,7 +238,7 @@ def _join_on_columns( [~df_lhs_renamed.iloc[:, index].isna() for index in lhs_on], ) df_lhs_renamed = df_lhs_renamed[df_lhs_filter] - if join_type in ["inner", "left"]: + if join_type in ["inner", "left", "leftanti", "leftsemi"]: df_rhs_filter = reduce( operator.and_, [~df_rhs_renamed.iloc[:, index].isna() for index in rhs_on], @@ -256,12 +267,24 @@ def _join_on_columns( "For more information refer to https://github.com/dask/dask/issues/9851" " and https://github.com/dask/dask/issues/9870" ) - df = df_lhs_with_tmp.merge( - df_rhs_with_tmp, - on=added_columns, - how=join_type, - broadcast=broadcast, - ).drop(columns=added_columns) + if join_type == "leftanti" and not is_cudf_type(df_lhs_with_tmp): + df = df_lhs_with_tmp.merge( + df_rhs_with_tmp, + on=added_columns, + how="left", + broadcast=broadcast, + indicator=True, + ).drop(columns=added_columns) + df = df[df["_merge"] == "left_only"].drop( + columns=["_merge"] + list(df_rhs_with_tmp.columns), errors="ignore" + ) + else: + df = df_lhs_with_tmp.merge( + df_rhs_with_tmp, + on=added_columns, + how=join_type, + broadcast=broadcast, + ).drop(columns=added_columns) return df diff --git a/tests/integration/test_join.py b/tests/integration/test_join.py index 3b131541c..1169bc947 100644 --- a/tests/integration/test_join.py +++ b/tests/integration/test_join.py @@ -86,6 +86,56 @@ def test_join_left(c): assert_eq(return_df, expected_df, check_index=False) +@pytest.mark.parametrize("gpu", [False, pytest.param(True, marks=pytest.mark.gpu)]) +def test_join_left_anti(c, gpu): + df1 = pd.DataFrame({"id": [1, 1, 2, 4], "a": ["a", "b", "c", "d"]}) + df2 = pd.DataFrame({"id": [2, 1, 2, 3], "b": ["c", "c", "a", "c"]}) + c.create_table("df_1", df1, gpu=gpu) + c.create_table("df_2", df2, gpu=gpu) + + return_df = c.sql( + """ + SELECT lhs.id, lhs.a + FROM df_1 AS lhs + LEFT ANTI JOIN df_2 AS rhs + ON lhs.id = rhs.id + """ + ) + expected_df = pd.DataFrame( + { + "id": [4], + "a": ["d"], + } + ) + + assert_eq(return_df, expected_df, check_index=False) + + +@pytest.mark.gpu +def test_join_left_semi(c): + df1 = pd.DataFrame({"id": [1, 1, 2, 4], "a": ["a", "b", "c", "d"]}) + df2 = pd.DataFrame({"id": [2, 1, 2, 3], "b": ["c", "c", "a", "c"]}) + c.create_table("df_1", df1, gpu=True) + c.create_table("df_2", df2, gpu=True) + + return_df = c.sql( + """ + SELECT lhs.id, lhs.a + FROM df_1 AS lhs + LEFT SEMI JOIN df_2 AS rhs + ON lhs.id = rhs.id + """ + ) + expected_df = pd.DataFrame( + { + "id": [1, 1, 2], + "a": ["a", "b", "c"], + } + ) + + assert_eq(return_df, expected_df, check_index=False) + + def test_join_right(c): return_df = c.sql( """ diff --git a/tests/unit/test_queries.py b/tests/unit/test_queries.py index b32e9530f..67120df82 100644 --- a/tests/unit/test_queries.py +++ b/tests/unit/test_queries.py @@ -36,7 +36,6 @@ 77, 80, 86, - 87, 88, 89, 92, From 371315c30963ffabf89fbb4e58d5e05c2f44cb79 Mon Sep 17 00:00:00 2001 From: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Date: Fri, 30 Jun 2023 17:25:14 -0400 Subject: [PATCH 08/25] Add compatibility for pandas 2 (#1184) * First pass at unblocking pytest errors * Fix some datetime relateed failures * Copy datetime table fixture to avoid dropping timezones * Unpin pandas dependency * Resolve append deprecations in analyze table * Resolve append deprecations in JDBC * Fix deprecated drop call in test_join_cross * specify mixed datetime format for test_select_different_types * Week number now accessible through isocalendar * xfail test_filter_cast_timestamp * Temp fix for cuDF timezone delocalization * Add some compat code for pandas<2 * Use timezone-aware datetimes on GPU * Don't hardcode timezone fixture * Link to timezone scalar issue --- .../environment-3.10-dev.yaml | 2 +- .../environment-3.9-dev.yaml | 2 +- .../gpuci/environment-3.10.yaml | 2 +- .../gpuci/environment-3.9.yaml | 2 +- continuous_integration/recipe/meta.yaml | 2 +- dask_sql/_compat.py | 1 + dask_sql/mappings.py | 14 ++++++-- dask_sql/physical/rel/custom/analyze_table.py | 36 +++++++++---------- dask_sql/physical/rex/core/call.py | 4 +-- dask_sql/server/presto_jdbc.py | 6 ++-- docker/conda.txt | 2 +- docker/main.dockerfile | 2 +- docs/environment.yml | 2 +- docs/requirements-docs.txt | 2 +- setup.py | 2 +- tests/integration/fixtures.py | 21 +++++++---- tests/integration/test_analyze.py | 24 ++++++------- tests/integration/test_filter.py | 6 ++-- tests/integration/test_jdbc.py | 3 +- tests/integration/test_join.py | 2 +- tests/integration/test_select.py | 15 +++++--- tests/unit/test_mapping.py | 2 +- 22 files changed, 88 insertions(+), 66 deletions(-) diff --git a/continuous_integration/environment-3.10-dev.yaml b/continuous_integration/environment-3.10-dev.yaml index 6a3a37f0b..a867996d1 100644 --- a/continuous_integration/environment-3.10-dev.yaml +++ b/continuous_integration/environment-3.10-dev.yaml @@ -15,7 +15,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0,<2.0.0 +- pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/environment-3.9-dev.yaml b/continuous_integration/environment-3.9-dev.yaml index d7b4700f8..7424529d6 100644 --- a/continuous_integration/environment-3.9-dev.yaml +++ b/continuous_integration/environment-3.9-dev.yaml @@ -15,7 +15,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0,<2.0.0 +- pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index f1b76271a..2467e144a 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -18,7 +18,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0,<2.0.0 +- pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index 2ee59f6cb..917892f24 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -18,7 +18,7 @@ dependencies: - mlflow - mock - numpy>=1.21.6 -- pandas>=1.4.0,<2.0.0 +- pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index f2ad46249..5152cfc4e 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -35,7 +35,7 @@ requirements: run: - python - dask >=2022.3.0 - - pandas >=1.4.0,<2.0.0 + - pandas >=1.4.0 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi >=0.69.0,<0.87.0 - uvicorn >=0.13.4 diff --git a/dask_sql/_compat.py b/dask_sql/_compat.py index f76982a4c..be8cfbae5 100644 --- a/dask_sql/_compat.py +++ b/dask_sql/_compat.py @@ -8,6 +8,7 @@ _dask_version = parseVersion(dask.__version__) INDEXER_WINDOW_STEP_IMPLEMENTED = _pandas_version >= parseVersion("1.5.0") +PANDAS_GT_200 = _pandas_version >= parseVersion("2.0.0") # TODO: remove if prompt-toolkit min version gets bumped PIPE_INPUT_CONTEXT_MANAGER = _prompt_toolkit_version >= parseVersion("3.0.29") diff --git a/dask_sql/mappings.py b/dask_sql/mappings.py index 2b66c0504..9ba22f797 100644 --- a/dask_sql/mappings.py +++ b/dask_sql/mappings.py @@ -331,13 +331,19 @@ def cast_column_type( def cast_column_to_type(col: dd.Series, expected_type: str): """Cast the given column to the expected type""" + pdt = pd.api.types + + is_dt_ns = pdt.is_datetime64_ns_dtype + is_dt_tz = lambda t: is_dt_ns(t) and pdt.is_datetime64tz_dtype(t) + is_dt_ntz = lambda t: is_dt_ns(t) and not pdt.is_datetime64tz_dtype(t) + current_type = col.dtype if similar_type(current_type, expected_type): logger.debug("...not converting.") return None - if pd.api.types.is_integer_dtype(expected_type): + if pdt.is_integer_dtype(expected_type): if pd.api.types.is_float_dtype(current_type): logger.debug("...truncating...") # Currently "trunc" can not be applied to NA (the pandas missing value type), @@ -345,10 +351,14 @@ def cast_column_to_type(col: dd.Series, expected_type: str): # For our use case, that does not matter, as the conversion to integer later # will convert both NA and np.NaN to NA. col = da.trunc(col.fillna(value=np.NaN)) - elif pd.api.types.is_timedelta64_dtype(current_type): + elif pdt.is_timedelta64_dtype(current_type): logger.debug(f"Explicitly casting from {current_type} to np.int64") return col.astype(np.int64) + if is_dt_tz(current_type) and is_dt_ntz(expected_type): + # casting from timezone-aware to timezone-naive datatypes with astype is deprecated in pandas 2 + return col.dt.tz_localize(None) + logger.debug(f"Need to cast from {current_type} to {expected_type}") return col.astype(expected_type) diff --git a/dask_sql/physical/rel/custom/analyze_table.py b/dask_sql/physical/rel/custom/analyze_table.py index 14011ccef..69f734a54 100644 --- a/dask_sql/physical/rel/custom/analyze_table.py +++ b/dask_sql/physical/rel/custom/analyze_table.py @@ -47,26 +47,22 @@ def convert(self, rel: "LogicalPlan", context: "dask_sql.Context") -> DataContai df = dc.df # Calculate statistics - statistics = dd.from_pandas( - pd.DataFrame({col: [] for col in columns}), npartitions=1 - ) - statistics = statistics.append(df[[mapping(col) for col in columns]].describe()) - - # Add additional information - statistics = statistics.append( - pd.Series( - { - col: str(python_to_sql_type(df[mapping(col)].dtype)).lower() - for col in columns - }, - name="data_type", - ) - ) - statistics = statistics.append( - pd.Series( - {col: col for col in columns}, - name="col_name", - ) + statistics = dd.concat( + [ + df[[mapping(col) for col in columns]].describe(), + pd.DataFrame( + { + mapping(col): str( + python_to_sql_type(df[mapping(col)].dtype) + ).lower() + for col in columns + }, + index=["data_type"], + ), + pd.DataFrame( + {mapping(col): col for col in columns}, index=["col_name"] + ), + ] ) cc = ColumnContainer(statistics.columns) diff --git a/dask_sql/physical/rex/core/call.py b/dask_sql/physical/rex/core/call.py index db604da3a..712173704 100644 --- a/dask_sql/physical/rex/core/call.py +++ b/dask_sql/physical/rex/core/call.py @@ -15,7 +15,7 @@ from dask.utils import random_state_data from dask_planner.rust import SqlTypeName -from dask_sql._compat import DASK_CUDF_TODATETIME_SUPPORT +from dask_sql._compat import DASK_CUDF_TODATETIME_SUPPORT, PANDAS_GT_200 from dask_sql.datacontainer import DataContainer from dask_sql.mappings import ( cast_column_to_type, @@ -927,7 +927,7 @@ def date_part(self, what, df: SeriesOrScalar): elif what in {"SECOND", "SECONDS"}: return df.second elif what in {"WEEK", "WEEKS"}: - return df.week + return df.isocalendar().week if PANDAS_GT_200 else df.week elif what in {"YEAR", "YEARS"}: return df.year elif what == "DATE": diff --git a/dask_sql/server/presto_jdbc.py b/dask_sql/server/presto_jdbc.py index d3c3880cb..02f77a1b4 100644 --- a/dask_sql/server/presto_jdbc.py +++ b/dask_sql/server/presto_jdbc.py @@ -37,15 +37,15 @@ def create_meta_data(c: Context): # catalogs = pd.DataFrame().append(create_catalog_row(catalog), ignore_index=True) # c.create_table("catalogs", catalogs, schema_name=system_schema) - schemas = pd.DataFrame().append(create_schema_row(), ignore_index=True) + schemas = pd.DataFrame(create_schema_row(), index=[0]) c.create_table("schemas", schemas, schema_name=system_schema) schema_rows = [] - tables = pd.DataFrame().append(create_table_row(), ignore_index=True) + tables = pd.DataFrame(create_table_row(), index=[0]) c.create_table("tables", tables, schema_name=system_schema) table_rows = [] - columns = pd.DataFrame().append(create_column_row(), ignore_index=True) + columns = pd.DataFrame(create_column_row(), index=[0]) c.create_table("columns", columns, schema_name=system_schema) column_rows = [] diff --git a/docker/conda.txt b/docker/conda.txt index 0c57cf45d..d24d217aa 100644 --- a/docker/conda.txt +++ b/docker/conda.txt @@ -1,6 +1,6 @@ python>=3.8 dask>=2022.3.0 -pandas>=1.4.0,<2.0.0 +pandas>=1.4.0 jpype1>=1.0.2 openjdk>=8 maven>=3.6.0 diff --git a/docker/main.dockerfile b/docker/main.dockerfile index 09d07834f..da965a53c 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -17,7 +17,7 @@ RUN mamba install -y \ "setuptools-rust>=1.5.2" \ # core dependencies "dask>=2022.3.0" \ - "pandas>=1.4.0,<2.0.0" \ + "pandas>=1.4.0" \ # FIXME: handling is needed for httpx-based fastapi>=0.87.0 "fastapi>=0.69.0,<0.87.0" \ "uvicorn>=0.13.4" \ diff --git a/docs/environment.yml b/docs/environment.yml index ae25c9440..96a727465 100644 --- a/docs/environment.yml +++ b/docs/environment.yml @@ -8,7 +8,7 @@ dependencies: - sphinx-tabs - dask-sphinx-theme>=2.0.3 - dask>=2022.3.0 - - pandas>=1.4.0,<2.0.0 + - pandas>=1.4.0 - fugue>=0.7.3 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - fastapi>=0.69.0,<0.87.0 diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index 374528d89..c9d8c6b0e 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -2,7 +2,7 @@ sphinx>=4.0.0 sphinx-tabs dask-sphinx-theme>=3.0.0 dask>=2022.3.0 -pandas>=1.4.0,<2.0.0 +pandas>=1.4.0 fugue>=0.7.3 # FIXME: handling is needed for httpx-based fastapi>=0.87.0 fastapi>=0.69.0,<0.87.0 diff --git a/setup.py b/setup.py index 085d362fe..d149ac5f0 100644 --- a/setup.py +++ b/setup.py @@ -44,7 +44,7 @@ install_requires=[ "dask[dataframe]>=2022.3.0", "distributed>=2022.3.0", - "pandas>=1.4.0,<2.0.0", + "pandas>=1.4.0", # FIXME: handling is needed for httpx-based fastapi>=0.87.0 "fastapi>=0.69.0,<0.87.0", "uvicorn>=0.13.4", diff --git a/tests/integration/fixtures.py b/tests/integration/fixtures.py index 65fc3b156..90b6f3828 100644 --- a/tests/integration/fixtures.py +++ b/tests/integration/fixtures.py @@ -169,12 +169,21 @@ def gpu_string_table(string_table): @pytest.fixture() def gpu_datetime_table(datetime_table): - # cudf doesn't have support for timezoned datetime data - datetime_table["timezone"] = datetime_table["timezone"].astype("datetime64[ns]") - datetime_table["utc_timezone"] = datetime_table["utc_timezone"].astype( - "datetime64[ns]" - ) - return cudf.from_pandas(datetime_table) if cudf else None + if cudf: + # TODO: remove once `from_pandas` has support for timezone-aware data + # https://github.com/rapidsai/cudf/issues/13611 + df = datetime_table.copy() + df["timezone"] = df["timezone"].dt.tz_localize(None) + df["utc_timezone"] = df["utc_timezone"].dt.tz_localize(None) + gdf = cudf.from_pandas(df) + gdf["timezone"] = gdf["timezone"].dt.tz_localize( + str(datetime_table["timezone"].dt.tz) + ) + gdf["utc_timezone"] = gdf["utc_timezone"].dt.tz_localize( + str(datetime_table["utc_timezone"].dt.tz) + ) + return gdf + return None @pytest.fixture() diff --git a/tests/integration/test_analyze.py b/tests/integration/test_analyze.py index 8371476c1..a7ccf65b6 100644 --- a/tests/integration/test_analyze.py +++ b/tests/integration/test_analyze.py @@ -1,3 +1,4 @@ +import dask.dataframe as dd import pandas as pd from dask_sql.mappings import python_to_sql_type @@ -8,24 +9,21 @@ def test_analyze(c, df): result_df = c.sql("ANALYZE TABLE df COMPUTE STATISTICS FOR ALL COLUMNS") # extract table and compute stats with Dask manually - expected_df = ( - c.sql("SELECT * FROM df") - .describe() - .append( - pd.Series( + expected_df = dd.concat( + [ + c.sql("SELECT * FROM df").describe(), + pd.DataFrame( { col: str(python_to_sql_type(df[col].dtype)).lower() for col in df.columns }, - name="data_type", - ) - ) - .append( - pd.Series( + index=["data_type"], + ), + pd.DataFrame( {col: col for col in df.columns}, - name="col_name", - ) - ) + index=["col_name"], + ), + ] ) assert_eq(result_df, expected_df) diff --git a/tests/integration/test_filter.py b/tests/integration/test_filter.py index 9de072d5e..cede43185 100644 --- a/tests/integration/test_filter.py +++ b/tests/integration/test_filter.py @@ -92,9 +92,8 @@ def test_filter_cast_date(c, input_table, request): CAST(timezone AS DATE) > DATE '2014-08-01' """ ) - expected_df = datetime_table[ - datetime_table["timezone"].astype(" pd.Timestamp("2014-08-01") ] assert_eq(return_df, expected_df) @@ -110,6 +109,9 @@ def test_filter_cast_date(c, input_table, request): ), ], ) +@pytest.mark.xfail( + reason="Need support for non-UTC timezoned literals, see https://github.com/dask-contrib/dask-sql/issues/1193" +) def test_filter_cast_timestamp(c, input_table, request): datetime_table = request.getfixturevalue(input_table) return_df = c.sql( diff --git a/tests/integration/test_jdbc.py b/tests/integration/test_jdbc.py index c4634311f..aa39737ad 100644 --- a/tests/integration/test_jdbc.py +++ b/tests/integration/test_jdbc.py @@ -19,8 +19,7 @@ def c(): c = Context() c.create_schema(schema) - row = create_table_row() - tables = pd.DataFrame().append(row, ignore_index=True) + tables = pd.DataFrame(create_table_row(), index=[0]) tables = tables.astype({"AN_INT": "int64"}) c.create_table(table, tables, schema_name=schema) diff --git a/tests/integration/test_join.py b/tests/integration/test_join.py index 1169bc947..c46cec101 100644 --- a/tests/integration/test_join.py +++ b/tests/integration/test_join.py @@ -169,7 +169,7 @@ def test_join_cross(c, user_table_1, department_table): user_table_1["key"] = 1 department_table["key"] = 1 - expected_df = dd.merge(user_table_1, department_table, on="key").drop("key", 1) + expected_df = dd.merge(user_table_1, department_table, on="key").drop(columns="key") assert_eq(return_df, expected_df, check_index=False) diff --git a/tests/integration/test_select.py b/tests/integration/test_select.py index 92ca6b53d..9c4331d77 100644 --- a/tests/integration/test_select.py +++ b/tests/integration/test_select.py @@ -4,6 +4,7 @@ from dask.dataframe.optimize import optimize_dataframe_getitem from dask.utils_test import hlg_layer +from dask_sql._compat import PANDAS_GT_200 from dask_sql.utils import ParsingException from tests.utils import assert_eq @@ -33,7 +34,10 @@ def test_select_column(c, df): def test_select_different_types(c): expected_df = pd.DataFrame( { - "date": pd.to_datetime(["2022-01-21 17:34", "2022-01-21", "17:34", pd.NaT]), + "date": pd.to_datetime( + ["2022-01-21 17:34", "2022-01-21", "17:34", pd.NaT], + format="mixed" if PANDAS_GT_200 else None, + ), "string": ["this is a test", "another test", "äölüć", ""], "integer": [1, 2, -4, 5], "float": [-1.1, np.NaN, pd.NA, np.sqrt(2)], @@ -163,13 +167,13 @@ def test_date_casting(c, input_table, request): expected_df = datetime_table expected_df["timezone"] = ( - expected_df["timezone"].astype(" Date: Fri, 30 Jun 2023 19:53:23 -0500 Subject: [PATCH 09/25] Use `scan_table` to apply custom filters (#1179) * q3 functionality * style and minor functionality changes * some cleanup * save progress * use inlist instead of binaryexpr * fix cargo test * fix some queries * use with_max_passes=1 and remove todos * add warning * only run dpp once * null handling and double dtype * minor style fixes * clippy * use adp imports * add jeremy suggestions and better type logic * style fix * MORE int/float logic * style fix * fix some bugs * add dask_config * check for duplicate tablescans * fix row iterator * clippy * clippy again * add support for custom filters to attempt_predicate_pushdown * remove comments * fix preserve_filters=False bug * copy changes from 1040 * fix kwarg bug * avoid using list within predicate values * roll back accidental change * Re-add all filters after conjunctive_dnf_filters * Planner: Update table_scan to return the pyexpr in addition to dnf tuple * update table_scan logic to use the new filtered_dnf tuple format * improve caching a bit --------- Co-authored-by: Sarah Yurick Co-authored-by: Sarah Yurick <53962159+sarahyurick@users.noreply.github.com> Co-authored-by: Jeremy Dyer Co-authored-by: Ayush Dattagupta --- dask_planner/src/sql/logical/table_scan.rs | 47 ++++++++++++++++----- dask_sql/physical/rel/logical/filter.py | 10 +++-- dask_sql/physical/rel/logical/table_scan.py | 32 ++++++++++++-- dask_sql/physical/utils/filter.py | 31 +++++++++++--- 4 files changed, 97 insertions(+), 23 deletions(-) diff --git a/dask_planner/src/sql/logical/table_scan.rs b/dask_planner/src/sql/logical/table_scan.rs index 679d24c49..3b7a89e6e 100644 --- a/dask_planner/src/sql/logical/table_scan.rs +++ b/dask_planner/src/sql/logical/table_scan.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::{sync::Arc, vec}; use datafusion_python::{ datafusion_common::{DFSchema, ScalarValue}, @@ -19,6 +19,7 @@ pub struct PyTableScan { input: Arc, } +type FilterTuple = (String, String, Option>); #[pyclass(name = "FilteredResult", module = "dask_planner", subclass)] #[derive(Debug, Clone)] pub struct PyFilteredResult { @@ -31,7 +32,7 @@ pub struct PyFilteredResult { // Expr(s) that can have their filtering logic performed in the pyarrow IO logic // are stored here in a DNF format that is expected by pyarrow. #[pyo3(get)] - pub filtered_exprs: Vec<(String, String, Vec)>, + pub filtered_exprs: Vec<(PyExpr, FilterTuple)>, } impl PyTableScan { @@ -45,9 +46,10 @@ impl PyTableScan { /// it as well if needed. pub fn _expand_dnf_filter( filter: &Expr, + input: &Arc, py: Python, - ) -> Result)>, DaskPlannerError> { - let mut filter_tuple: Vec<(String, String, Vec)> = Vec::new(); + ) -> Result, DaskPlannerError> { + let mut filter_tuple: Vec<(PyExpr, FilterTuple)> = Vec::new(); match filter { Expr::InList { @@ -100,9 +102,12 @@ impl PyTableScan { .collect(); filter_tuple.push(( - ident.unwrap_or(expr.canonical_name()), - op.to_string(), - il?, + PyExpr::from(filter.clone(), Some(vec![input.clone()])), + ( + ident.unwrap_or(expr.canonical_name()), + op.to_string(), + Some(il?), + ), )); Ok(filter_tuple) } else { @@ -110,15 +115,35 @@ impl PyTableScan { "Invalid identifying column Expr instance `{}`. using in Dask instead", filter )); - Err::)>, DaskPlannerError>(er) + Err::, DaskPlannerError>(er) } } + Expr::IsNotNull(expr) => { + // Only handle simple Expr(s) for IsNotNull operations for now + let ident = match *expr.clone() { + Expr::Column(col) => Ok(col.name), + _ => Err(DaskPlannerError::InvalidIOFilter(format!( + "Invalid IsNotNull Expr type `{}`. using in Dask instead", + filter + ))), + }; + + filter_tuple.push(( + PyExpr::from(filter.clone(), Some(vec![input.clone()])), + ( + ident.unwrap_or(expr.canonical_name()), + "is not".to_string(), + None, + ), + )); + Ok(filter_tuple) + } _ => { let er = DaskPlannerError::InvalidIOFilter(format!( "Unable to apply filter: `{}` to IO reader, using in Dask instead", filter )); - Err::)>, DaskPlannerError>(er) + Err::, DaskPlannerError>(er) } } } @@ -132,12 +157,12 @@ impl PyTableScan { filters: &[Expr], py: Python, ) -> PyFilteredResult { - let mut filtered_exprs: Vec<(String, String, Vec)> = Vec::new(); + let mut filtered_exprs: Vec<(PyExpr, FilterTuple)> = Vec::new(); let mut unfiltered_exprs: Vec = Vec::new(); filters .iter() - .for_each(|f| match PyTableScan::_expand_dnf_filter(f, py) { + .for_each(|f| match PyTableScan::_expand_dnf_filter(f, input, py) { Ok(mut expanded_dnf_filter) => filtered_exprs.append(&mut expanded_dnf_filter), Err(_e) => { unfiltered_exprs.push(PyExpr::from(f.clone(), Some(vec![input.clone()]))) diff --git a/dask_sql/physical/rel/logical/filter.py b/dask_sql/physical/rel/logical/filter.py index 178121fef..d3c3f5fd3 100644 --- a/dask_sql/physical/rel/logical/filter.py +++ b/dask_sql/physical/rel/logical/filter.py @@ -1,5 +1,5 @@ import logging -from typing import TYPE_CHECKING, Union +from typing import TYPE_CHECKING, List, Union import dask.config as dask_config import dask.dataframe as dd @@ -17,7 +17,11 @@ logger = logging.getLogger(__name__) -def filter_or_scalar(df: dd.DataFrame, filter_condition: Union[np.bool_, dd.Series]): +def filter_or_scalar( + df: dd.DataFrame, + filter_condition: Union[np.bool_, dd.Series], + add_filters: List = None, +): """ Some (complex) SQL queries can lead to a strange condition which is always true or false. We do not need to filter in this case. @@ -35,7 +39,7 @@ def filter_or_scalar(df: dd.DataFrame, filter_condition: Union[np.bool_, dd.Seri filter_condition = filter_condition.fillna(False) out = df[filter_condition] if dask_config.get("sql.predicate_pushdown"): - return attempt_predicate_pushdown(out) + return attempt_predicate_pushdown(out, add_filters=add_filters) else: return out diff --git a/dask_sql/physical/rel/logical/table_scan.py b/dask_sql/physical/rel/logical/table_scan.py index 5c1718f62..b4025ec97 100644 --- a/dask_sql/physical/rel/logical/table_scan.py +++ b/dask_sql/physical/rel/logical/table_scan.py @@ -3,6 +3,8 @@ from functools import reduce from typing import TYPE_CHECKING +from dask.utils_test import hlg_layer + from dask_sql.datacontainer import DataContainer from dask_sql.physical.rel.base import BaseRelPlugin from dask_sql.physical.rel.logical.filter import filter_or_scalar @@ -77,16 +79,38 @@ def _apply_projections(self, table_scan, dask_table, dc): def _apply_filters(self, table_scan, rel, dc, context): df = dc.df cc = dc.column_container - filters = table_scan.getFilters() - # All partial filters here are applied in conjunction (&) - if filters: + all_filters = table_scan.getFilters() + conjunctive_dnf_filters = table_scan.getDNFFilters().filtered_exprs + non_dnf_filters = table_scan.getDNFFilters().io_unfilterable_exprs + + if conjunctive_dnf_filters: + # Extract the PyExprs from the conjunctive DNF filters + filter_exprs = [f[0] for f in conjunctive_dnf_filters] + if non_dnf_filters: + filter_exprs.extend(non_dnf_filters) + + df_condition = reduce( + operator.and_, + [ + RexConverter.convert(rel, rex, dc, context=context) + for rex in filter_exprs + ], + ) + df = filter_or_scalar( + df, df_condition, add_filters=[f[1] for f in conjunctive_dnf_filters] + ) + elif all_filters: df_condition = reduce( operator.and_, [ RexConverter.convert(rel, rex, dc, context=context) - for rex in filters + for rex in all_filters ], ) df = filter_or_scalar(df, df_condition) + try: + logger.debug(hlg_layer(df.dask, "read-parquet").creation_info) + except KeyError: + pass return DataContainer(df, cc) diff --git a/dask_sql/physical/utils/filter.py b/dask_sql/physical/utils/filter.py index 0b4e0f40b..f99934c07 100644 --- a/dask_sql/physical/utils/filter.py +++ b/dask_sql/physical/utils/filter.py @@ -129,10 +129,12 @@ def attempt_predicate_pushdown( # Regenerate collection with filtered IO layer try: + _regen_cache = {} return dsk.layers[name]._regenerate_collection( dsk, # TODO: shouldn't need to specify index=False after dask#9661 is merged new_kwargs={io_layer: {"filters": filters, "index": False}}, + _regen_cache=_regen_cache, ) except ValueError as err: # Most-likely failed to apply filters in read_parquet. @@ -195,15 +197,33 @@ def __bool__(self) -> bool: @classmethod def normalize(cls, filters: _And | _Or | list | tuple | None): """Convert raw filters to the `_Or(_And)` DNF representation""" + + def _valid_tuple(predicate: tuple): + col, op, val = predicate + if isinstance(col, tuple): + raise TypeError("filters must be List[Tuple] or List[List[Tuple]]") + if op in ("in", "not in"): + return (col, op, tuple(val)) + else: + return predicate + + def _valid_list(conjunction: list): + valid = [] + for predicate in conjunction: + if not isinstance(predicate, tuple): + raise TypeError(f"Predicate must be a tuple, got {predicate}") + valid.append(_valid_tuple(predicate)) + return valid + if not filters: result = None elif isinstance(filters, list): conjunctions = filters if isinstance(filters[0], list) else [filters] - result = cls._Or([cls._And(conjunction) for conjunction in conjunctions]) + result = cls._Or( + [cls._And(_valid_list(conjunction)) for conjunction in conjunctions] + ) elif isinstance(filters, tuple): - if isinstance(filters[0], tuple): - raise TypeError("filters must be List[Tuple] or List[List[Tuple]]") - result = cls._Or((cls._And((filters,)),)) + result = cls._Or((cls._And((_valid_tuple(filters),)),)) elif isinstance(filters, cls._Or): result = cls._Or(se for e in filters for se in cls.normalize(e)) elif isinstance(filters, cls._And): @@ -332,7 +352,8 @@ def _regenerate_collection( # Return regenerated layer if the work was # already done - _regen_cache = _regen_cache or {} + if _regen_cache is None: + _regen_cache = {} if self.layer.output in _regen_cache: return _regen_cache[self.layer.output] From eab95ce898dfa155e41c271040735c7e036d40a0 Mon Sep 17 00:00:00 2001 From: Sarah Yurick <53962159+sarahyurick@users.noreply.github.com> Date: Thu, 6 Jul 2023 13:44:01 -0700 Subject: [PATCH 10/25] Improve scalar logic for timestamps (#1025) * default to seconds * save progress * fix most tests * fix gpu test * check_dtype False * push new updates * check_dtype=False * timedelta check * check is_cudf_type * add DASK_CUDF_TODATETIME_SUPPORT * style * edit test * remove gpu xfail * remove is_timestamp_nano * style * remove ReduceOp check --------- Co-authored-by: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Co-authored-by: Ayush Dattagupta --- dask_planner/src/sql.rs | 25 ++++- dask_sql/physical/rex/core/call.py | 32 ++++--- tests/integration/test_rex.py | 147 ++++++++++++++++++++++++++--- 3 files changed, 174 insertions(+), 30 deletions(-) diff --git a/dask_planner/src/sql.rs b/dask_planner/src/sql.rs index d87bfcc76..a0e238727 100644 --- a/dask_planner/src/sql.rs +++ b/dask_planner/src/sql.rs @@ -244,6 +244,11 @@ impl ContextProvider for DaskSQLContext { DataType::Int64, DataType::Timestamp(TimeUnit::Nanosecond, None), ]), + TypeSignature::Exact(vec![ + DataType::Utf8, + DataType::Int64, + DataType::Int64, + ]), ], Volatility::Immutable, ); @@ -251,11 +256,23 @@ impl ContextProvider for DaskSQLContext { return Some(Arc::new(ScalarUDF::new(name, &sig, &rtf, &fun))); } "timestampdiff" => { - let sig = Signature::exact( + let sig = Signature::one_of( vec![ - DataType::Utf8, - DataType::Timestamp(TimeUnit::Nanosecond, None), - DataType::Timestamp(TimeUnit::Nanosecond, None), + TypeSignature::Exact(vec![ + DataType::Utf8, + DataType::Timestamp(TimeUnit::Nanosecond, None), + DataType::Timestamp(TimeUnit::Nanosecond, None), + ]), + TypeSignature::Exact(vec![ + DataType::Utf8, + DataType::Date64, + DataType::Date64, + ]), + TypeSignature::Exact(vec![ + DataType::Utf8, + DataType::Int64, + DataType::Int64, + ]), ], Volatility::Immutable, ); diff --git a/dask_sql/physical/rex/core/call.py b/dask_sql/physical/rex/core/call.py index 712173704..85d083d78 100644 --- a/dask_sql/physical/rex/core/call.py +++ b/dask_sql/physical/rex/core/call.py @@ -251,6 +251,9 @@ def cast(self, operand, rex=None) -> SeriesOrScalar: if output_type == "DECIMAL": sql_type_args = rex.getPrecisionScale() + if output_type == "TIMESTAMP" and pd.api.types.is_integer_dtype(operand): + operand = operand * 10**9 + if not is_frame(operand): # pragma: no cover return sql_to_python_value(sql_type, operand) @@ -613,17 +616,8 @@ def to_timestamp(self, df, format): format = format.replace('"', "") format = format.replace("'", "") - # TODO: format timestamps for GPU tests - if is_cudf_type(df): - if format != default_format: - raise RuntimeError("Non-default timestamp formats not supported on GPU") - if df.dtype == "object": - return df - else: - nanoseconds_to_seconds = 10**9 - return df * nanoseconds_to_seconds # String cases - elif type(df) == str: + if type(df) == str: return np.datetime64(datetime.strptime(df, format)) elif df.dtype == "object": return dd.to_datetime(df, format=format) @@ -656,7 +650,11 @@ def timestampadd(self, unit, interval, df: SeriesOrScalar): interval = int(interval) if interval < 0: raise RuntimeError(f"Negative time interval {interval} is not supported.") - df = df.astype("datetime64[ns]") + df = ( + df.astype("datetime64[s]") + if pd.api.types.is_integer_dtype(df) + else df.astype("datetime64[ns]") + ) if is_cudf_type(df): from cudf import DateOffset @@ -700,11 +698,23 @@ def __init__(self): super().__init__(self.datetime_sub) def datetime_sub(self, unit, df1, df2): + if pd.api.types.is_integer_dtype(df1): + df1 = df1 * 10**9 + if pd.api.types.is_integer_dtype(df2): + df2 = df2 * 10**9 + if "datetime64[s]" == str(getattr(df1, "dtype", "")): + df1 = df1.astype("datetime64[ns]") + if "datetime64[s]" == str(getattr(df2, "dtype", "")): + df2 = df2.astype("datetime64[ns]") + subtraction_op = ReduceOperation( operation=operator.sub, unary_operation=lambda x: -x ) result = subtraction_op(df2, df1) + if is_cudf_type(df1): + result = result.astype("int") + if unit in {"NANOSECOND", "NANOSECONDS"}: return result elif unit in {"MICROSECOND", "MICROSECONDS"}: diff --git a/tests/integration/test_rex.py b/tests/integration/test_rex.py index 93d77dca5..b49a687d2 100644 --- a/tests/integration/test_rex.py +++ b/tests/integration/test_rex.py @@ -940,21 +940,7 @@ def test_timestampdiff(c): assert_eq(ddf, expected_df, check_dtype=False) -@pytest.mark.parametrize( - "gpu", - [ - False, - pytest.param( - True, - marks=( - pytest.mark.gpu, - pytest.mark.xfail( - reason="Failing due to dask-cudf bug https://github.com/rapidsai/cudf/issues/12062" - ), - ), - ), - ], -) +@pytest.mark.parametrize("gpu", [False, pytest.param(True, marks=pytest.mark.gpu)]) def test_totimestamp(c, gpu): df = pd.DataFrame( { @@ -1121,3 +1107,134 @@ def test_extract_date(c, gpu): {"i": [datetime(2021, 1, 3), datetime(2022, 2, 4), datetime(2023, 3, 5)]} ) assert_eq(result, expected_df) + + +@pytest.mark.parametrize( + "gpu", + [ + False, + pytest.param( + True, + marks=( + pytest.mark.gpu, + pytest.mark.xfail( + not DASK_CUDF_TODATETIME_SUPPORT, + reason="Requires https://github.com/dask/dask/pull/9881", + raises=RuntimeError, + ), + ), + ), + ], +) +def test_scalar_timestamps(c, gpu): + df = pd.DataFrame({"d": [1203073300, 1503073700]}) + c.create_table("df", df, gpu=gpu) + + expected_df = pd.DataFrame( + { + "dt": [datetime(2008, 2, 20, 11, 1, 40), datetime(2017, 8, 23, 16, 28, 20)], + } + ) + + df1 = c.sql("SELECT to_timestamp(d) + INTERVAL '5 days' AS dt FROM df") + assert_eq(df1, expected_df) + df2 = c.sql("SELECT CAST(d AS TIMESTAMP) + INTERVAL '5 days' AS dt FROM df") + assert_eq(df2, expected_df) + + df1 = c.sql("SELECT TIMESTAMPADD(DAY, 5, to_timestamp(d)) AS dt FROM df") + assert_eq(df1, expected_df) + df2 = c.sql("SELECT TIMESTAMPADD(DAY, 5, d) AS dt FROM df") + assert_eq(df2, expected_df) + df3 = c.sql("SELECT TIMESTAMPADD(DAY, 5, CAST(d AS TIMESTAMP)) AS dt FROM df") + assert_eq(df3, expected_df) + + expected_df = pd.DataFrame({"day": [15, 18]}) + df1 = c.sql("SELECT EXTRACT(DAY FROM to_timestamp(d)) AS day FROM df") + assert_eq(df1, expected_df, check_dtype=False) + df2 = c.sql("SELECT EXTRACT(DAY FROM CAST(d AS TIMESTAMP)) AS day FROM df") + assert_eq(df2, expected_df, check_dtype=False) + + expected_df = pd.DataFrame( + { + "ceil_to_day": [datetime(2008, 2, 16), datetime(2017, 8, 19)], + } + ) + df1 = c.sql("SELECT CEIL(to_timestamp(d) TO DAY) AS ceil_to_day FROM df") + assert_eq(df1, expected_df) + df2 = c.sql("SELECT CEIL(CAST(d AS TIMESTAMP) TO DAY) AS ceil_to_day FROM df") + assert_eq(df2, expected_df) + + expected_df = pd.DataFrame( + { + "floor_to_day": [datetime(2008, 2, 15), datetime(2017, 8, 18)], + } + ) + df1 = c.sql("SELECT FLOOR(to_timestamp(d) TO DAY) AS floor_to_day FROM df") + assert_eq(df1, expected_df) + df2 = c.sql("SELECT FLOOR(CAST(d AS TIMESTAMP) TO DAY) AS floor_to_day FROM df") + assert_eq(df2, expected_df) + + df = pd.DataFrame({"d1": [1203073300], "d2": [1503073700]}) + c.create_table("df", df, gpu=gpu) + expected_df = pd.DataFrame({"dt": [3472]}) + df1 = c.sql( + "SELECT TIMESTAMPDIFF(DAY, to_timestamp(d1), to_timestamp(d2)) AS dt FROM df" + ) + # TODO: The GPU case returns an incorrect value here + if not gpu: + assert_eq(df1, expected_df) + df2 = c.sql("SELECT TIMESTAMPDIFF(DAY, d1, d2) AS dt FROM df") + assert_eq(df2, expected_df, check_dtype=False) + df3 = c.sql( + "SELECT TIMESTAMPDIFF(DAY, CAST(d1 AS TIMESTAMP), CAST(d2 AS TIMESTAMP)) AS dt FROM df" + ) + assert_eq(df3, expected_df) + + scalar1 = 1203073300 + scalar2 = 1503073700 + + expected_df = pd.DataFrame({"dt": [datetime(2008, 2, 20, 11, 1, 40)]}) + + df1 = c.sql(f"SELECT to_timestamp({scalar1}) + INTERVAL '5 days' AS dt") + assert_eq(df1, expected_df) + # TODO: Fix seconds/nanoseconds conversion + # df2 = c.sql(f"SELECT CAST({scalar1} AS TIMESTAMP) + INTERVAL '5 days' AS dt") + # assert_eq(df2, expected_df) + + df1 = c.sql(f"SELECT TIMESTAMPADD(DAY, 5, to_timestamp({scalar1})) AS dt") + assert_eq(df1, expected_df) + df2 = c.sql(f"SELECT TIMESTAMPADD(DAY, 5, {scalar1}) AS dt") + assert_eq(df2, expected_df) + df3 = c.sql(f"SELECT TIMESTAMPADD(DAY, 5, CAST({scalar1} AS TIMESTAMP)) AS dt") + assert_eq(df3, expected_df) + + expected_df = pd.DataFrame({"day": [15]}) + df1 = c.sql(f"SELECT EXTRACT(DAY FROM to_timestamp({scalar1})) AS day") + assert_eq(df1, expected_df, check_dtype=False) + # TODO: Fix seconds/nanoseconds conversion + # df2 = c.sql(f"SELECT EXTRACT(DAY FROM CAST({scalar1} AS TIMESTAMP)) AS day") + # assert_eq(df2, expected_df, check_dtype=False) + + expected_df = pd.DataFrame({"ceil_to_day": [datetime(2008, 2, 16)]}) + df1 = c.sql(f"SELECT CEIL(to_timestamp({scalar1}) TO DAY) AS ceil_to_day") + assert_eq(df1, expected_df) + df2 = c.sql(f"SELECT CEIL(CAST({scalar1} AS TIMESTAMP) TO DAY) AS ceil_to_day") + assert_eq(df2, expected_df) + + expected_df = pd.DataFrame({"floor_to_day": [datetime(2008, 2, 15)]}) + df1 = c.sql(f"SELECT FLOOR(to_timestamp({scalar1}) TO DAY) AS floor_to_day") + assert_eq(df1, expected_df) + df2 = c.sql(f"SELECT FLOOR(CAST({scalar1} AS TIMESTAMP) TO DAY) AS floor_to_day") + assert_eq(df2, expected_df) + + expected_df = pd.DataFrame({"dt": [3472]}) + df1 = c.sql( + f"SELECT TIMESTAMPDIFF(DAY, to_timestamp({scalar1}), to_timestamp({scalar2})) AS dt" + ) + assert_eq(df1, expected_df) + df2 = c.sql(f"SELECT TIMESTAMPDIFF(DAY, {scalar1}, {scalar2}) AS dt") + assert_eq(df2, expected_df, check_dtype=False) + df3 = c.sql( + f"SELECT TIMESTAMPDIFF(DAY, CAST({scalar1} AS TIMESTAMP), CAST({scalar2} AS TIMESTAMP)) AS dt" + ) + assert_eq(df3, expected_df) From 144aac0d57571ec70565a88053cdd323c0e5813d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Jul 2023 10:53:08 -0700 Subject: [PATCH 11/25] Bump async-trait from 0.1.68 to 0.1.71 in /dask_planner (#1198) Bumps [async-trait](https://github.com/dtolnay/async-trait) from 0.1.68 to 0.1.71. - [Release notes](https://github.com/dtolnay/async-trait/releases) - [Commits](https://github.com/dtolnay/async-trait/compare/0.1.68...0.1.71) --- updated-dependencies: - dependency-name: async-trait dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ayush Dattagupta --- dask_planner/Cargo.lock | 40 ++++++++++++++++++++-------------------- dask_planner/Cargo.toml | 2 +- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/dask_planner/Cargo.lock b/dask_planner/Cargo.lock index 3f501e47d..21d448e09 100644 --- a/dask_planner/Cargo.lock +++ b/dask_planner/Cargo.lock @@ -350,18 +350,18 @@ checksum = "0e97ce7de6cf12de5d7226c73f5ba9811622f4db3a5b91b55c53e987e5f91cba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] name = "async-trait" -version = "0.1.68" +version = "0.1.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "a564d521dd56509c4c47480d00b80ee55f7e385ae48db5744c67ad50c92d2ebf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -694,7 +694,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -711,7 +711,7 @@ checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -907,7 +907,7 @@ dependencies = [ "pyo3-build-config 0.18.3", "rand", "regex-syntax 0.6.29", - "syn 2.0.15", + "syn 2.0.23", "tokio", "url", "uuid", @@ -1171,7 +1171,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -2647,7 +2647,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ceca8aaf45b5c46ec7ed39fff75f57290368c1846d33d24a122ca81416ab058" dependencies = [ "proc-macro2", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -2658,9 +2658,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" [[package]] name = "proc-macro2" -version = "1.0.56" +version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" +checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" dependencies = [ "unicode-ident", ] @@ -2822,9 +2822,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.26" +version = "1.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105" dependencies = [ "proc-macro2", ] @@ -3129,7 +3129,7 @@ checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -3354,7 +3354,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml", - "syn 2.0.15", + "syn 2.0.23", "typify", "walkdir", ] @@ -3378,9 +3378,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.15" +version = "2.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822" +checksum = "59fb7d6d8281a51045d62b8eb3a7d1ce347b76f312af50cd3dc0af39c87c1737" dependencies = [ "proc-macro2", "quote", @@ -3432,7 +3432,7 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -3536,7 +3536,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] @@ -3601,7 +3601,7 @@ checksum = "0f57e3ca2a01450b1a921183a9c9cbfda207fd822cef4ccb00a65402cbba7a74" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.23", ] [[package]] diff --git a/dask_planner/Cargo.toml b/dask_planner/Cargo.toml index eb12bff27..dd9f66f81 100644 --- a/dask_planner/Cargo.toml +++ b/dask_planner/Cargo.toml @@ -9,7 +9,7 @@ edition = "2021" rust-version = "1.65" [dependencies] -async-trait = "0.1.68" +async-trait = "0.1.71" datafusion-python = { git = "https://github.com/apache/arrow-datafusion-python.git", rev = "9493638" } env_logger = "0.10" log = "^0.4" From c6b2ce1b59aa538d8da92a1e5e0b3e0556548231 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Jul 2023 17:40:24 -0700 Subject: [PATCH 12/25] Bump pyo3-build-config from 0.19.0 to 0.19.1 in /dask_planner (#1196) Bumps [pyo3-build-config](https://github.com/pyo3/pyo3) from 0.19.0 to 0.19.1. - [Release notes](https://github.com/pyo3/pyo3/releases) - [Changelog](https://github.com/PyO3/pyo3/blob/main/CHANGELOG.md) - [Commits](https://github.com/pyo3/pyo3/compare/v0.19.0...v0.19.1) --- updated-dependencies: - dependency-name: pyo3-build-config dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ayush Dattagupta --- dask_planner/Cargo.lock | 6 +++--- dask_planner/Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dask_planner/Cargo.lock b/dask_planner/Cargo.lock index 21d448e09..bfa4e2c89 100644 --- a/dask_planner/Cargo.lock +++ b/dask_planner/Cargo.lock @@ -736,7 +736,7 @@ dependencies = [ "env_logger", "log", "pyo3", - "pyo3-build-config 0.19.0", + "pyo3-build-config 0.19.1", "pyo3-log", ] @@ -2752,9 +2752,9 @@ dependencies = [ [[package]] name = "pyo3-build-config" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713eccf888fb05f1a96eb78c0dbc51907fee42b3377272dc902eb38985f418d5" +checksum = "554db24f0b3c180a9c0b1268f91287ab3f17c162e15b54caaae5a6b3773396b0" dependencies = [ "once_cell", "target-lexicon", diff --git a/dask_planner/Cargo.toml b/dask_planner/Cargo.toml index dd9f66f81..8beffe3aa 100644 --- a/dask_planner/Cargo.toml +++ b/dask_planner/Cargo.toml @@ -17,7 +17,7 @@ pyo3 = { version = "0.18.3", features = ["extension-module", "abi3", "abi3-py38" pyo3-log = "0.8.2" [build-dependencies] -pyo3-build-config = "0.19.0" +pyo3-build-config = "0.19.1" [lib] crate-type = ["cdylib"] From baad3382de175becb410eb975d2aee851e33dadc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 19 Jul 2023 06:05:18 -0400 Subject: [PATCH 13/25] Bump pyo3-log from 0.8.2 to 0.8.3 in /dask_planner (#1200) Bumps [pyo3-log](https://github.com/vorner/pyo3-log) from 0.8.2 to 0.8.3. - [Changelog](https://github.com/vorner/pyo3-log/blob/main/CHANGELOG.md) - [Commits](https://github.com/vorner/pyo3-log/compare/v0.8.2...v0.8.3) --- updated-dependencies: - dependency-name: pyo3-log dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- dask_planner/Cargo.lock | 4 ++-- dask_planner/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dask_planner/Cargo.lock b/dask_planner/Cargo.lock index bfa4e2c89..ee67cfb89 100644 --- a/dask_planner/Cargo.lock +++ b/dask_planner/Cargo.lock @@ -2772,9 +2772,9 @@ dependencies = [ [[package]] name = "pyo3-log" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c94ff6535a6bae58d7d0b85e60d4c53f7f84d0d0aa35d6a28c3f3e70bfe51444" +checksum = "f47b0777feb17f61eea78667d61103758b243a871edc09a7786500a50467b605" dependencies = [ "arc-swap", "log", diff --git a/dask_planner/Cargo.toml b/dask_planner/Cargo.toml index 8beffe3aa..a3dce7aff 100644 --- a/dask_planner/Cargo.toml +++ b/dask_planner/Cargo.toml @@ -14,7 +14,7 @@ datafusion-python = { git = "https://github.com/apache/arrow-datafusion-python.g env_logger = "0.10" log = "^0.4" pyo3 = { version = "0.18.3", features = ["extension-module", "abi3", "abi3-py38"] } -pyo3-log = "0.8.2" +pyo3-log = "0.8.3" [build-dependencies] pyo3-build-config = "0.19.1" From 2c5a4929050a6921c34b5c7ae2f5fc985c46b202 Mon Sep 17 00:00:00 2001 From: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Date: Wed, 19 Jul 2023 10:08:05 -0400 Subject: [PATCH 14/25] Remove `glibc` constraint from aarch64 packages (#1201) * Remove glibc constraint from aarch64 packages * Modify FIXME comment --- .github/workflows/release.yml | 12 ------------ continuous_integration/recipe/meta.yaml | 6 ------ dask_sql/__init__.py | 4 ++++ 3 files changed, 4 insertions(+), 18 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1ee1e6397..3795b4823 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,18 +82,6 @@ jobs: use-mamba: true python-version: "3.8" channel-priority: strict - # FIXME: aarch64 builds require glibc>=2.32 to prevent TLS allocation error when importing; - # is there any way we could modify the TLS model of its shared object to avoid this? - # https://bugzilla.redhat.com/show_bug.cgi?id=1722181 - # xref: https://github.com/dask-contrib/dask-sql/issues/1169 - - name: Update platform tag for aarch64 wheel - if: matrix.os == 'ubuntu-latest' - run: | - mamba install wheel - - wheel tags --platform-tag=manylinux_2_32_aarch64 \ - --remove \ - dist/*_aarch64.whl - name: Check dist files run: | mamba install twine diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index 5152cfc4e..c90ba3bd2 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -43,12 +43,6 @@ requirements: - prompt-toolkit >=3.0.8 - pygments >=2.7.1 - tabulate - run_constrained: - # FIXME: aarch64 builds require glibc>=2.32 to prevent TLS allocation error when importing; - # is there any way we could modify the TLS model of its shared object to avoid this? - # https://bugzilla.redhat.com/show_bug.cgi?id=1722181 - # xref: https://github.com/dask-contrib/dask-sql/issues/1169 - - __glibc >=2.32 # [aarch64] test: imports: diff --git a/dask_sql/__init__.py b/dask_sql/__init__.py index 756486b74..d923876b8 100644 --- a/dask_sql/__init__.py +++ b/dask_sql/__init__.py @@ -1,3 +1,7 @@ +# FIXME: can we modify TLS model of Rust object to avoid aarch64 glibc bug? +# https://github.com/dask-contrib/dask-sql/issues/1169 +import dask_planner.rust + from . import _version, config from .cmd import cmd_loop from .context import Context From 662359785acdbd37a6e09c538a5f02790e561cb5 Mon Sep 17 00:00:00 2001 From: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Date: Fri, 28 Jul 2023 14:50:06 -0400 Subject: [PATCH 15/25] Add `xz` to conda `host` dependencies (#1202) * Add xz to host requirements for linux-64 * Add --error-overlinking flag to builds * Fix linux64 selector --------- Co-authored-by: Ayush Dattagupta --- .github/workflows/conda.yml | 1 + continuous_integration/recipe/meta.yaml | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/conda.yml b/.github/workflows/conda.yml index 78253db6b..20294124a 100644 --- a/.github/workflows/conda.yml +++ b/.github/workflows/conda.yml @@ -61,6 +61,7 @@ jobs: conda mambabuild continuous_integration/recipe \ --python ${{ matrix.python }} \ --variants "{target_platform: [${{ matrix.arch }}]}" \ + --error-overlinking \ --no-test \ --no-anaconda-upload \ --output-folder packages diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index c90ba3bd2..5f42f10d9 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -32,6 +32,7 @@ requirements: - python - setuptools-rust - libprotobuf + - xz # [linux64] run: - python - dask >=2022.3.0 From af180620216793b7c6125b7db8f98dd0bba038de Mon Sep 17 00:00:00 2001 From: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Date: Fri, 28 Jul 2023 16:48:49 -0400 Subject: [PATCH 16/25] Add python->SQL handling for pyarrow strings, test python 3.9 in upstream import testing (#1206) * Resolve upstream Dask failures * Fix typo * Override pyarrow string default in sql.yaml * Move pyarrow string override to conftest.py --------- Co-authored-by: Ayush Dattagupta --- .github/workflows/test-upstream.yml | 4 +++- .github/workflows/test.yml | 4 +++- conftest.py | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-upstream.yml b/.github/workflows/test-upstream.yml index ff0296b15..0305a3ab4 100644 --- a/.github/workflows/test-upstream.yml +++ b/.github/workflows/test-upstream.yml @@ -110,7 +110,9 @@ jobs: with: miniforge-variant: Mambaforge use-mamba: true - python-version: "3.8" + # TODO: drop support for python 3.8, add support for python 3.11 + # https://github.com/dask-contrib/dask-sql/pull/1143 + python-version: "3.9" channel-priority: strict - name: Install Protoc uses: arduino/setup-protoc@v1 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index be2d98126..e9080cf2f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -107,7 +107,9 @@ jobs: with: miniforge-variant: Mambaforge use-mamba: true - python-version: "3.8" + # TODO: drop support for python 3.8, add support for python 3.11 + # https://github.com/dask-contrib/dask-sql/pull/1143 + python-version: ${{ needs.detect-ci-trigger.outputs.triggered == 'true' && '3.9' || '3.8' }} channel-priority: strict - name: Install Protoc uses: arduino/setup-protoc@v1 diff --git a/conftest.py b/conftest.py index 0042c9ca7..172fa3028 100644 --- a/conftest.py +++ b/conftest.py @@ -12,6 +12,8 @@ def pytest_addoption(parser): def pytest_runtest_setup(item): + # TODO: explore adding support for pyarrow string columns + dask.config.set({"dataframe.convert-string": False}) if "gpu" in item.keywords: if not item.config.getoption("--rungpu"): pytest.skip("need --rungpu option to run") From 0c63447f2812541fb9d6636edfd0a54bff553511 Mon Sep 17 00:00:00 2001 From: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Date: Fri, 28 Jul 2023 20:06:06 -0400 Subject: [PATCH 17/25] Bump `fastapi` dependency to `>=0.92.0` (#1205) * Bump fastapi min version to 0.92.0 * Add httpx to deps * Establish lower bound for httpx * Remove data kwarg from test_routes * Fix Python 3.8 `fastapi` version constraint * Revert "Fix Python 3.8 `fastapi` version constraint" This reverts commit cebfb900bf27a12c5759418ddc5b81a593bcc69d. --------- Co-authored-by: Ayush Dattagupta Co-authored-by: jakirkham --- continuous_integration/environment-3.10-dev.yaml | 4 ++-- continuous_integration/environment-3.8-dev.yaml | 3 ++- continuous_integration/environment-3.9-dev.yaml | 4 ++-- continuous_integration/gpuci/environment-3.10.yaml | 4 ++-- continuous_integration/gpuci/environment-3.9.yaml | 4 ++-- continuous_integration/recipe/meta.yaml | 4 ++-- docker/conda.txt | 4 ++-- docker/main.dockerfile | 4 ++-- docs/environment.yml | 4 ++-- docs/requirements-docs.txt | 4 ++-- setup.py | 4 ++-- tests/integration/test_server.py | 2 +- 12 files changed, 23 insertions(+), 22 deletions(-) diff --git a/continuous_integration/environment-3.10-dev.yaml b/continuous_integration/environment-3.10-dev.yaml index a867996d1..08af189eb 100644 --- a/continuous_integration/environment-3.10-dev.yaml +++ b/continuous_integration/environment-3.10-dev.yaml @@ -5,9 +5,9 @@ channels: dependencies: - c-compiler - dask>=2022.3.0 -# FIXME: handling is needed for httpx-based fastapi>=0.87.0 -- fastapi>=0.69.0,<0.87.0 +- fastapi>=0.92.0 - fugue>=0.7.3 +- httpx>=0.24.1 - intake>=0.6.0 - jsonschema - lightgbm diff --git a/continuous_integration/environment-3.8-dev.yaml b/continuous_integration/environment-3.8-dev.yaml index 18b478472..15abe79b5 100644 --- a/continuous_integration/environment-3.8-dev.yaml +++ b/continuous_integration/environment-3.8-dev.yaml @@ -5,8 +5,9 @@ channels: dependencies: - c-compiler - dask=2022.3.0 -- fastapi=0.69.0 +- fastapi=0.92.0 - fugue=0.7.3 +- httpx=0.24.1 - intake=0.6.0 - jsonschema - lightgbm diff --git a/continuous_integration/environment-3.9-dev.yaml b/continuous_integration/environment-3.9-dev.yaml index 7424529d6..47e64e8fc 100644 --- a/continuous_integration/environment-3.9-dev.yaml +++ b/continuous_integration/environment-3.9-dev.yaml @@ -5,9 +5,9 @@ channels: dependencies: - c-compiler - dask>=2022.3.0 -# FIXME: handling is needed for httpx-based fastapi>=0.87.0 -- fastapi>=0.69.0,<0.87.0 +- fastapi>=0.92.0 - fugue>=0.7.3 +- httpx>=0.24.1 - intake>=0.6.0 - jsonschema - lightgbm diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index 2467e144a..d312844d3 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -8,9 +8,9 @@ channels: dependencies: - c-compiler - dask>=2022.3.0 -# FIXME: handling is needed for httpx-based fastapi>=0.87.0 -- fastapi>=0.69.0,<0.87.0 +- fastapi>=0.92.0 - fugue>=0.7.3 +- httpx>=0.24.1 - intake>=0.6.0 - jsonschema - lightgbm diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index 917892f24..565869411 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -8,9 +8,9 @@ channels: dependencies: - c-compiler - dask>=2022.3.0 -# FIXME: handling is needed for httpx-based fastapi>=0.87.0 -- fastapi>=0.69.0,<0.87.0 +- fastapi>=0.92.0 - fugue>=0.7.3 +- httpx>=0.24.1 - intake>=0.6.0 - jsonschema - lightgbm diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index 5f42f10d9..f6c34cbee 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -37,8 +37,8 @@ requirements: - python - dask >=2022.3.0 - pandas >=1.4.0 - # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - - fastapi >=0.69.0,<0.87.0 + - fastapi >=0.92.0 + - httpx>=0.24.1 - uvicorn >=0.13.4 - tzlocal >=2.1 - prompt-toolkit >=3.0.8 diff --git a/docker/conda.txt b/docker/conda.txt index d24d217aa..83b176843 100644 --- a/docker/conda.txt +++ b/docker/conda.txt @@ -10,8 +10,8 @@ pytest-xdist mock>=4.0.3 sphinx>=3.2.1 tzlocal>=2.1 -# FIXME: handling is needed for httpx-based fastapi>=0.87.0 -fastapi>=0.69.0,<0.87.0 +fastapi>=0.92.0 +httpx>=0.24.1 uvicorn>=0.13.4 pyarrow>=6.0.1 prompt_toolkit>=3.0.8 diff --git a/docker/main.dockerfile b/docker/main.dockerfile index da965a53c..c3dbbf8d2 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -18,8 +18,8 @@ RUN mamba install -y \ # core dependencies "dask>=2022.3.0" \ "pandas>=1.4.0" \ - # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - "fastapi>=0.69.0,<0.87.0" \ + "fastapi>=0.92.0" \ + "httpx>=0.24.1" \ "uvicorn>=0.13.4" \ "tzlocal>=2.1" \ "prompt_toolkit>=3.0.8" \ diff --git a/docs/environment.yml b/docs/environment.yml index 96a727465..e9366eaa4 100644 --- a/docs/environment.yml +++ b/docs/environment.yml @@ -10,8 +10,8 @@ dependencies: - dask>=2022.3.0 - pandas>=1.4.0 - fugue>=0.7.3 - # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - - fastapi>=0.69.0,<0.87.0 + - fastapi>=0.92.0 + - httpx>=0.24.1 - uvicorn>=0.13.4 - tzlocal>=2.1 - prompt_toolkit>=3.0.8 diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index c9d8c6b0e..c039df54a 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -4,8 +4,8 @@ dask-sphinx-theme>=3.0.0 dask>=2022.3.0 pandas>=1.4.0 fugue>=0.7.3 -# FIXME: handling is needed for httpx-based fastapi>=0.87.0 -fastapi>=0.69.0,<0.87.0 +fastapi>=0.92.0 +httpx>=0.24.1 uvicorn>=0.13.4 tzlocal>=2.1 prompt_toolkit>=3.0.8 diff --git a/setup.py b/setup.py index d149ac5f0..387c93125 100644 --- a/setup.py +++ b/setup.py @@ -45,8 +45,8 @@ "dask[dataframe]>=2022.3.0", "distributed>=2022.3.0", "pandas>=1.4.0", - # FIXME: handling is needed for httpx-based fastapi>=0.87.0 - "fastapi>=0.69.0,<0.87.0", + "fastapi>=0.92.0", + "httpx>=0.24.1", "uvicorn>=0.13.4", "tzlocal>=2.1", "prompt_toolkit>=3.0.8", diff --git a/tests/integration/test_server.py b/tests/integration/test_server.py index 655f91881..75cb7ca81 100644 --- a/tests/integration/test_server.py +++ b/tests/integration/test_server.py @@ -58,7 +58,7 @@ def get_result_or_error(app_client, response): def test_routes(app_client): assert app_client.post("/v1/statement", data="SELECT 1 + 1").status_code == 200 - assert app_client.get("/v1/statement", data="SELECT 1 + 1").status_code == 405 + assert app_client.get("/v1/statement").status_code == 405 assert app_client.get("/v1/empty").status_code == 200 assert app_client.get("/v1/status/some-wrong-uuid").status_code == 404 assert app_client.delete("/v1/cancel/some-wrong-uuid").status_code == 404 From 53e8777c0222028ef3f5069621c65437d5c7965c Mon Sep 17 00:00:00 2001 From: Ayush Dattagupta Date: Thu, 3 Aug 2023 11:16:36 -0700 Subject: [PATCH 18/25] Pin dask/distributed to 2023.7.1 for release (#1209) --- continuous_integration/environment-3.10-dev.yaml | 2 +- continuous_integration/environment-3.9-dev.yaml | 2 +- continuous_integration/gpuci/environment-3.10.yaml | 2 +- continuous_integration/gpuci/environment-3.9.yaml | 2 +- continuous_integration/recipe/meta.yaml | 2 +- docker/conda.txt | 2 +- docker/main.dockerfile | 2 +- docs/environment.yml | 2 +- docs/requirements-docs.txt | 2 +- setup.py | 4 ++-- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/continuous_integration/environment-3.10-dev.yaml b/continuous_integration/environment-3.10-dev.yaml index 08af189eb..653e8fb11 100644 --- a/continuous_integration/environment-3.10-dev.yaml +++ b/continuous_integration/environment-3.10-dev.yaml @@ -4,7 +4,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0 +- dask>=2022.3.0,<=2023.7.1 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/environment-3.9-dev.yaml b/continuous_integration/environment-3.9-dev.yaml index 47e64e8fc..640569136 100644 --- a/continuous_integration/environment-3.9-dev.yaml +++ b/continuous_integration/environment-3.9-dev.yaml @@ -4,7 +4,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0 +- dask>=2022.3.0,<=2023.7.1 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index d312844d3..8703b8618 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -7,7 +7,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0 +- dask>=2022.3.0,<=2023.7.1 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index 565869411..cd0043a5a 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -7,7 +7,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0 +- dask>=2022.3.0,<=2023.7.1 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index f6c34cbee..e10000e39 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -35,7 +35,7 @@ requirements: - xz # [linux64] run: - python - - dask >=2022.3.0 + - dask >=2022.3.0,<=2023.7.1 - pandas >=1.4.0 - fastapi >=0.92.0 - httpx>=0.24.1 diff --git a/docker/conda.txt b/docker/conda.txt index 83b176843..3c37fa08e 100644 --- a/docker/conda.txt +++ b/docker/conda.txt @@ -1,5 +1,5 @@ python>=3.8 -dask>=2022.3.0 +dask>=2022.3.0,<=2023.7.1 pandas>=1.4.0 jpype1>=1.0.2 openjdk>=8 diff --git a/docker/main.dockerfile b/docker/main.dockerfile index c3dbbf8d2..eba3b5309 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -16,7 +16,7 @@ RUN mamba install -y \ # build requirements "setuptools-rust>=1.5.2" \ # core dependencies - "dask>=2022.3.0" \ + "dask>=2022.3.0,<=2023.7.1" \ "pandas>=1.4.0" \ "fastapi>=0.92.0" \ "httpx>=0.24.1" \ diff --git a/docs/environment.yml b/docs/environment.yml index e9366eaa4..bf840400b 100644 --- a/docs/environment.yml +++ b/docs/environment.yml @@ -7,7 +7,7 @@ dependencies: - sphinx>=4.0.0 - sphinx-tabs - dask-sphinx-theme>=2.0.3 - - dask>=2022.3.0 + - dask>=2022.3.0,<=2023.7.1 - pandas>=1.4.0 - fugue>=0.7.3 - fastapi>=0.92.0 diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index c039df54a..66800718d 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -1,7 +1,7 @@ sphinx>=4.0.0 sphinx-tabs dask-sphinx-theme>=3.0.0 -dask>=2022.3.0 +dask>=2022.3.0,<=2023.7.1 pandas>=1.4.0 fugue>=0.7.3 fastapi>=0.92.0 diff --git a/setup.py b/setup.py index 387c93125..5a8280cbc 100644 --- a/setup.py +++ b/setup.py @@ -42,8 +42,8 @@ python_requires=">=3.8", setup_requires=sphinx_requirements, install_requires=[ - "dask[dataframe]>=2022.3.0", - "distributed>=2022.3.0", + "dask[dataframe]>=2022.3.0,<=2023.7.1", + "distributed>=2022.3.0,<=2023.7.1", "pandas>=1.4.0", "fastapi>=0.92.0", "httpx>=0.24.1", From 030c8fd7a484829fed94203446857df71389468f Mon Sep 17 00:00:00 2001 From: jakirkham Date: Thu, 3 Aug 2023 13:13:03 -0700 Subject: [PATCH 19/25] Add missing space in `httpx` requirement (#1210) --- continuous_integration/recipe/meta.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index e10000e39..42a7cbba0 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -38,7 +38,7 @@ requirements: - dask >=2022.3.0,<=2023.7.1 - pandas >=1.4.0 - fastapi >=0.92.0 - - httpx>=0.24.1 + - httpx >=0.24.1 - uvicorn >=0.13.4 - tzlocal >=2.1 - prompt-toolkit >=3.0.8 From a837d7da6758b50ed9004ffa3efcfcd870081316 Mon Sep 17 00:00:00 2001 From: Ayush Dattagupta Date: Mon, 7 Aug 2023 10:27:19 -0700 Subject: [PATCH 20/25] unpin dask/distributed for development (#1211) --- continuous_integration/environment-3.10-dev.yaml | 2 +- continuous_integration/environment-3.9-dev.yaml | 2 +- continuous_integration/gpuci/environment-3.10.yaml | 2 +- continuous_integration/gpuci/environment-3.9.yaml | 2 +- continuous_integration/recipe/meta.yaml | 2 +- docker/conda.txt | 2 +- docker/main.dockerfile | 2 +- docs/environment.yml | 2 +- docs/requirements-docs.txt | 2 +- setup.py | 4 ++-- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/continuous_integration/environment-3.10-dev.yaml b/continuous_integration/environment-3.10-dev.yaml index 653e8fb11..08af189eb 100644 --- a/continuous_integration/environment-3.10-dev.yaml +++ b/continuous_integration/environment-3.10-dev.yaml @@ -4,7 +4,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.7.1 +- dask>=2022.3.0 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/environment-3.9-dev.yaml b/continuous_integration/environment-3.9-dev.yaml index 640569136..47e64e8fc 100644 --- a/continuous_integration/environment-3.9-dev.yaml +++ b/continuous_integration/environment-3.9-dev.yaml @@ -4,7 +4,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.7.1 +- dask>=2022.3.0 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index 8703b8618..d312844d3 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -7,7 +7,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.7.1 +- dask>=2022.3.0 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index cd0043a5a..565869411 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -7,7 +7,7 @@ channels: - nodefaults dependencies: - c-compiler -- dask>=2022.3.0,<=2023.7.1 +- dask>=2022.3.0 - fastapi>=0.92.0 - fugue>=0.7.3 - httpx>=0.24.1 diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index 42a7cbba0..4314efed4 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -35,7 +35,7 @@ requirements: - xz # [linux64] run: - python - - dask >=2022.3.0,<=2023.7.1 + - dask >=2022.3.0 - pandas >=1.4.0 - fastapi >=0.92.0 - httpx >=0.24.1 diff --git a/docker/conda.txt b/docker/conda.txt index 3c37fa08e..83b176843 100644 --- a/docker/conda.txt +++ b/docker/conda.txt @@ -1,5 +1,5 @@ python>=3.8 -dask>=2022.3.0,<=2023.7.1 +dask>=2022.3.0 pandas>=1.4.0 jpype1>=1.0.2 openjdk>=8 diff --git a/docker/main.dockerfile b/docker/main.dockerfile index eba3b5309..c3dbbf8d2 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -16,7 +16,7 @@ RUN mamba install -y \ # build requirements "setuptools-rust>=1.5.2" \ # core dependencies - "dask>=2022.3.0,<=2023.7.1" \ + "dask>=2022.3.0" \ "pandas>=1.4.0" \ "fastapi>=0.92.0" \ "httpx>=0.24.1" \ diff --git a/docs/environment.yml b/docs/environment.yml index bf840400b..e9366eaa4 100644 --- a/docs/environment.yml +++ b/docs/environment.yml @@ -7,7 +7,7 @@ dependencies: - sphinx>=4.0.0 - sphinx-tabs - dask-sphinx-theme>=2.0.3 - - dask>=2022.3.0,<=2023.7.1 + - dask>=2022.3.0 - pandas>=1.4.0 - fugue>=0.7.3 - fastapi>=0.92.0 diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index 66800718d..c039df54a 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -1,7 +1,7 @@ sphinx>=4.0.0 sphinx-tabs dask-sphinx-theme>=3.0.0 -dask>=2022.3.0,<=2023.7.1 +dask>=2022.3.0 pandas>=1.4.0 fugue>=0.7.3 fastapi>=0.92.0 diff --git a/setup.py b/setup.py index 5a8280cbc..387c93125 100644 --- a/setup.py +++ b/setup.py @@ -42,8 +42,8 @@ python_requires=">=3.8", setup_requires=sphinx_requirements, install_requires=[ - "dask[dataframe]>=2022.3.0,<=2023.7.1", - "distributed>=2022.3.0,<=2023.7.1", + "dask[dataframe]>=2022.3.0", + "distributed>=2022.3.0", "pandas>=1.4.0", "fastapi>=0.92.0", "httpx>=0.24.1", From 3fad76ba9713f65adad7ba0dc99dccc06189e064 Mon Sep 17 00:00:00 2001 From: Ayush Dattagupta Date: Mon, 7 Aug 2023 12:54:32 -0700 Subject: [PATCH 21/25] Fix test_cmd for upstream testing (#1212) * unpin dask/distributed for development * Temporarily switch port for cmd test to non dashboard port --- tests/integration/test_cmd.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_cmd.py b/tests/integration/test_cmd.py index fdef31bd3..63e2da9c5 100644 --- a/tests/integration/test_cmd.py +++ b/tests/integration/test_cmd.py @@ -106,13 +106,14 @@ def test_meta_commands(c, client, capsys): captured = capsys.readouterr() assert "Schema not_exists not available\n" == captured.out + # FIXME: Revert to 8787 once https://github.com/dask/distributed/issues/8071 is fixed with pytest.raises( OSError, - match="Timed out .* to tcp://localhost:8787 after 5 s", + match="Timed out .* to tcp://localhost:8788 after 5 s", ): with dask_config.set({"distributed.comm.timeouts.connect": 5}): - client = _meta_commands("\\dsc localhost:8787", context=c, client=client) - assert client.scheduler.__dict__["addr"] == "localhost:8787" + client = _meta_commands("\\dsc localhost:8788", context=c, client=client) + assert client.scheduler.__dict__["addr"] == "localhost:8788" def test_connection_info(c, client, capsys): From 45e8bde86bc184b475ce5be9ebf76f1086e219b3 Mon Sep 17 00:00:00 2001 From: Jeremy Dyer Date: Thu, 17 Aug 2023 14:20:52 -0400 Subject: [PATCH 22/25] [REVIEW] Bump Arrow DataFusion Python dependency to 28.0.0 (#1181) * Bump ADP -> 26.0.0 * warn on optimization failure instead of erroring and exiting * Resolve initial build errors * Switch to crates release, add zlib to host/build deps * Add zlib to aarch build deps * Bump to ADP 27 and introduce support for wildcard expressions, a wildcard expression name will be subbed with the first column in the incoming schema plan * remove bit of logic that is no longer needed to manually check the wildcard 'name' as a '*' * experiment with removing zlib, hoping that fixes os x build * Change expected_df result to 1.5 from 1. 3/2 is in fact 1.5 and not 1 * Fix cargo test * add .cargo/config.toml in hopes of fixing linker build issues on osx * Remove extra config.toml * Try overriding runner-installed toolchain * Revert "Try overriding runner-installed toolchain" This reverts commit b2e85dfc5ac3f1a42c30adab2583fee89aec3c86. * Initial migration to maturin build system * Make some modifications to Rust package name * Adjust native library name from _.internal to dask_planner * Resolve initial conda build issues * Replace setuptools-rust with maturin in CI * Constrain maturin, remove setuptools-rust from CI envs * Update docs and Rust CI * Remove more dask_planner appearances * Bump pyarrow min version to resolve 3.8 conflicts * test commit seeing how CI will respond without cmd_loop import * Rename module to _datafusion_lib * Switch to maturin develop for CI installs * Fix failing cargo tests, changed output, from datafusion version bump * Fix cargo test syntax issue * Fix failing Rust tests * Remove linux config.toml options * Fix Rust object import * Apply code suggestions * Bump to recent ADP commit * Initial unblocker for pyarrow string handling * Compatibility code for old or no pyarrow installation * Added RexCall Operation to handle InSubquery Expr and also adjusted column_name function to examine InSubquery nested Expr instance for name * Add Sarah's fix for datetime.time error * Add condition to guard against complex function names that contain a '.' in their column name * unmarked xfail for queries 6, 9, & 54 * Quick fix for pydantic upstream breakage * Update dask_sql/physical/utils/filter.py Co-authored-by: Sarah Yurick <53962159+sarahyurick@users.noreply.github.com> * Apply Sarah's suggestions * Attempt to unblock failures at parse_datetime * Disable pyarrow strings for now * Remove breakpoint * Remove pydantic constraint now that fastapi is bumped * Apply pyproject suggestions * Bump build system to maturin 1.1 * Move filter datetime handling, remove string datetime handling for now * Actually check containment in InSubquery call * bring back decorrelated_where_exists and decorrelate_when_in * Checkstyle fixes * Remove xfail for queries 58 and 61 which pass now * Fix pytest syntax issue * whatever, have it your way black * Remove debugging println * re-add support for ilike using the case_insensitive member of like * Handle non-decimal scalar args for cuDF in RexCall * Try using maturin with zig for wheel builds * Install protoc for all wheel builds and zlib1g-dev in linux builds * Remove Cargo tests because that code is already being tested in DataFusion anyway * Adjust optimizer/utils test includes * Adjust import path for doctest * Adjust import path for doctest (more) * Check if zlib is installed on ubuntu runners * Try invoking maturin directly for conda builds * Revert "Try invoking maturin directly for conda builds" This reverts commit 24f465f86fab9f3d46e09b60c14785f756f14329. * Install protoc via apt * Add zlib to conda environment so that conda install c-compiler can locate the necessary zlib header files * Remove pytest coalesce option for Sum(b) with a string conditional result as that is not valid sql in some cases * Revert "Install protoc via apt" This reverts commit 488cbaf4086f08c5b1c60dc1a23c33d84e7dee29. * Try not using zig for x86_64 builds * Try installing protoc from apt again * Revert "Try installing protoc from apt again" This reverts commit 66ebed445f5b3b0389b9bdfceb8c99827349b4aa. * Try explicitly setting PROTOC location for x86_64 builds * Where is protoc? * Fix protoc binary location * Disable docker container for linux x86_64 build * Properly upload artifacts for ARM/intel * Disable aarch64 builds for now * Constrain mlflow to avoid import error * Set wheel tags to manylinux_2_17 * Use manylinux docker container for x86_64 builds * No sudo for protoc installation * Install protoc directly from github * Specify PROTOC environment variable for x86_64 runs * More doc updates to reflect new installation style * Fix docker builds * Bump ADP to stable 28.0.0 --------- Co-authored-by: Ayush Dattagupta Co-authored-by: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Co-authored-by: Jeremy Dyer Co-authored-by: Sarah Yurick <53962159+sarahyurick@users.noreply.github.com> --- {dask_planner/.cargo => .cargo}/config.toml | 0 .github/CODEOWNERS | 5 +- .github/workflows/conda.yml | 11 +- .github/workflows/release.yml | 178 +- .github/workflows/rust.yml | 5 - .github/workflows/test-upstream.yml | 5 +- .github/workflows/test.yml | 3 +- .gitignore | 10 +- .pre-commit-config.yaml | 6 +- CONTRIBUTING.md | 30 +- dask_planner/Cargo.lock => Cargo.lock | 1624 ++++------------- dask_planner/Cargo.toml => Cargo.toml | 16 +- README.md | 5 +- .../environment-3.10-dev.yaml | 10 +- .../environment-3.8-dev.yaml | 10 +- .../environment-3.9-dev.yaml | 10 +- .../gpuci/environment-3.10.yaml | 13 +- .../gpuci/environment-3.9.yaml | 13 +- .../recipe/conda_build_config.yaml | 4 +- continuous_integration/recipe/meta.yaml | 5 +- .../scripts}/update-dependencies.sh | 0 dask_planner/.classpath | 55 - dask_planner/.gitignore | 72 - .../org.eclipse.core.resources.prefs | 5 - .../.settings/org.eclipse.jdt.apt.core.prefs | 2 - .../.settings/org.eclipse.jdt.core.prefs | 9 - .../.settings/org.eclipse.m2e.core.prefs | 4 - dask_planner/MANIFEST.in | 2 - dask_planner/README.md | 0 dask_planner/pyproject.toml | 11 - dask_sql/__init__.py | 2 +- dask_sql/context.py | 7 +- dask_sql/input_utils/hive.py | 2 +- dask_sql/mappings.py | 2 +- dask_sql/physical/rel/base.py | 2 +- dask_sql/physical/rel/convert.py | 2 +- dask_sql/physical/rel/custom/alter.py | 2 +- dask_sql/physical/rel/custom/analyze_table.py | 2 +- .../rel/custom/create_catalog_schema.py | 2 +- .../rel/custom/create_memory_table.py | 2 +- dask_sql/physical/rel/custom/create_table.py | 2 +- .../physical/rel/custom/describe_model.py | 2 +- dask_sql/physical/rel/custom/distributeby.py | 2 +- dask_sql/physical/rel/custom/drop_schema.py | 2 +- dask_sql/physical/rel/custom/export_model.py | 2 +- dask_sql/physical/rel/custom/predict_model.py | 2 +- dask_sql/physical/rel/custom/show_columns.py | 2 +- dask_sql/physical/rel/custom/show_models.py | 2 +- dask_sql/physical/rel/custom/show_schemas.py | 2 +- dask_sql/physical/rel/custom/show_tables.py | 2 +- dask_sql/physical/rel/custom/use_schema.py | 2 +- dask_sql/physical/rel/logical/aggregate.py | 32 +- dask_sql/physical/rel/logical/cross_join.py | 2 +- dask_sql/physical/rel/logical/empty.py | 2 +- dask_sql/physical/rel/logical/explain.py | 2 +- dask_sql/physical/rel/logical/filter.py | 2 +- dask_sql/physical/rel/logical/join.py | 2 +- dask_sql/physical/rel/logical/limit.py | 2 +- dask_sql/physical/rel/logical/project.py | 4 +- dask_sql/physical/rel/logical/sort.py | 2 +- .../physical/rel/logical/subquery_alias.py | 2 +- dask_sql/physical/rel/logical/table_scan.py | 2 +- dask_sql/physical/rel/logical/union.py | 2 +- dask_sql/physical/rel/logical/window.py | 2 +- dask_sql/physical/rex/base.py | 2 +- dask_sql/physical/rex/convert.py | 2 +- dask_sql/physical/rex/core/alias.py | 2 +- dask_sql/physical/rex/core/call.py | 90 +- dask_sql/physical/rex/core/input_ref.py | 2 +- dask_sql/physical/rex/core/literal.py | 4 +- dask_sql/physical/rex/core/subquery.py | 2 +- dask_sql/physical/utils/filter.py | 17 + dask_sql/utils.py | 2 +- docker/conda.txt | 6 +- docker/main.dockerfile | 10 +- docs/environment.yml | 1 - docs/requirements-docs.txt | 2 +- docs/source/how_does_it_work.rst | 2 +- docs/source/installation.rst | 7 +- pyproject.toml | 83 +- setup.py | 83 +- {dask_planner/src => src}/dialect.rs | 6 + {dask_planner/src => src}/error.rs | 0 {dask_planner/src => src}/expression.rs | 223 ++- {dask_planner/src => src}/lib.rs | 5 +- {dask_planner/src => src}/parser.rs | 29 +- {dask_planner/src => src}/sql.rs | 48 +- {dask_planner/src => src}/sql/column.rs | 2 +- {dask_planner/src => src}/sql/exceptions.rs | 0 {dask_planner/src => src}/sql/function.rs | 2 +- {dask_planner/src => src}/sql/logical.rs | 19 +- .../src => src}/sql/logical/aggregate.rs | 14 +- .../src => src}/sql/logical/alter_schema.rs | 2 +- .../src => src}/sql/logical/alter_table.rs | 2 +- .../src => src}/sql/logical/analyze_table.rs | 2 +- .../sql/logical/create_catalog_schema.rs | 2 +- .../sql/logical/create_experiment.rs | 2 +- .../sql/logical/create_memory_table.rs | 11 +- .../src => src}/sql/logical/create_model.rs | 2 +- .../src => src}/sql/logical/create_table.rs | 2 +- .../src => src}/sql/logical/describe_model.rs | 2 +- .../src => src}/sql/logical/drop_model.rs | 2 +- .../src => src}/sql/logical/drop_schema.rs | 2 +- .../src => src}/sql/logical/drop_table.rs | 9 +- .../src => src}/sql/logical/empty_relation.rs | 2 +- .../src => src}/sql/logical/explain.rs | 2 +- .../src => src}/sql/logical/export_model.rs | 2 +- .../src => src}/sql/logical/filter.rs | 2 +- {dask_planner/src => src}/sql/logical/join.rs | 2 +- .../src => src}/sql/logical/limit.rs | 2 +- .../src => src}/sql/logical/predict_model.rs | 2 +- .../src => src}/sql/logical/projection.rs | 15 +- .../src => src}/sql/logical/repartition_by.rs | 2 +- .../src => src}/sql/logical/show_columns.rs | 2 +- .../src => src}/sql/logical/show_models.rs | 2 +- .../src => src}/sql/logical/show_schemas.rs | 2 +- .../src => src}/sql/logical/show_tables.rs | 2 +- {dask_planner/src => src}/sql/logical/sort.rs | 2 +- .../src => src}/sql/logical/subquery_alias.rs | 4 +- .../src => src}/sql/logical/table_scan.rs | 19 +- .../src => src}/sql/logical/use_schema.rs | 2 +- .../src => src}/sql/logical/window.rs | 6 +- {dask_planner/src => src}/sql/optimizer.rs | 36 +- src/sql/optimizer/decorrelate_where_exists.rs | 228 +++ src/sql/optimizer/decorrelate_where_in.rs | 258 +++ .../optimizer/dynamic_partition_pruning.rs | 14 +- .../src => src}/sql/optimizer/join_reorder.rs | 0 src/sql/optimizer/utils.rs | 516 ++++++ {dask_planner/src => src}/sql/parser_utils.rs | 0 {dask_planner/src => src}/sql/schema.rs | 2 +- {dask_planner/src => src}/sql/statement.rs | 2 +- {dask_planner/src => src}/sql/table.rs | 8 +- {dask_planner/src => src}/sql/types.rs | 22 +- .../src => src}/sql/types/rel_data_type.rs | 2 +- .../sql/types/rel_data_type_field.rs | 2 +- tests/integration/test_join.py | 4 +- tests/integration/test_rex.py | 8 +- tests/integration/test_select.py | 12 + tests/unit/test_mapping.py | 2 +- tests/unit/test_queries.py | 5 - 140 files changed, 2169 insertions(+), 1957 deletions(-) rename {dask_planner/.cargo => .cargo}/config.toml (100%) rename dask_planner/Cargo.lock => Cargo.lock (68%) rename dask_planner/Cargo.toml => Cargo.toml (53%) rename {dask_planner => continuous_integration/scripts}/update-dependencies.sh (100%) delete mode 100644 dask_planner/.classpath delete mode 100644 dask_planner/.gitignore delete mode 100644 dask_planner/.settings/org.eclipse.core.resources.prefs delete mode 100644 dask_planner/.settings/org.eclipse.jdt.apt.core.prefs delete mode 100644 dask_planner/.settings/org.eclipse.jdt.core.prefs delete mode 100644 dask_planner/.settings/org.eclipse.m2e.core.prefs delete mode 100644 dask_planner/MANIFEST.in delete mode 100644 dask_planner/README.md delete mode 100644 dask_planner/pyproject.toml rename {dask_planner/src => src}/dialect.rs (97%) rename {dask_planner/src => src}/error.rs (100%) rename {dask_planner/src => src}/expression.rs (82%) rename {dask_planner/src => src}/lib.rs (90%) rename {dask_planner/src => src}/parser.rs (95%) rename {dask_planner/src => src}/sql.rs (96%) rename {dask_planner/src => src}/sql/column.rs (91%) rename {dask_planner/src => src}/sql/exceptions.rs (100%) rename {dask_planner/src => src}/sql/function.rs (93%) rename {dask_planner/src => src}/sql/logical.rs (95%) rename {dask_planner/src => src}/sql/logical/aggregate.rs (87%) rename {dask_planner/src => src}/sql/logical/alter_schema.rs (98%) rename {dask_planner/src => src}/sql/logical/alter_table.rs (98%) rename {dask_planner/src => src}/sql/logical/analyze_table.rs (98%) rename {dask_planner/src => src}/sql/logical/create_catalog_schema.rs (98%) rename {dask_planner/src => src}/sql/logical/create_experiment.rs (98%) rename {dask_planner/src => src}/sql/logical/create_memory_table.rs (89%) rename {dask_planner/src => src}/sql/logical/create_model.rs (98%) rename {dask_planner/src => src}/sql/logical/create_table.rs (98%) rename {dask_planner/src => src}/sql/logical/describe_model.rs (97%) rename {dask_planner/src => src}/sql/logical/drop_model.rs (98%) rename {dask_planner/src => src}/sql/logical/drop_schema.rs (97%) rename {dask_planner/src => src}/sql/logical/drop_table.rs (71%) rename {dask_planner/src => src}/sql/logical/empty_relation.rs (94%) rename {dask_planner/src => src}/sql/logical/explain.rs (93%) rename {dask_planner/src => src}/sql/logical/export_model.rs (98%) rename {dask_planner/src => src}/sql/logical/filter.rs (93%) rename {dask_planner/src => src}/sql/logical/join.rs (98%) rename {dask_planner/src => src}/sql/logical/limit.rs (95%) rename {dask_planner/src => src}/sql/logical/predict_model.rs (98%) rename {dask_planner/src => src}/sql/logical/projection.rs (83%) rename {dask_planner/src => src}/sql/logical/repartition_by.rs (96%) rename {dask_planner/src => src}/sql/logical/show_columns.rs (98%) rename {dask_planner/src => src}/sql/logical/show_models.rs (97%) rename {dask_planner/src => src}/sql/logical/show_schemas.rs (98%) rename {dask_planner/src => src}/sql/logical/show_tables.rs (98%) rename {dask_planner/src => src}/sql/logical/sort.rs (93%) rename {dask_planner/src => src}/sql/logical/subquery_alias.rs (85%) rename {dask_planner/src => src}/sql/logical/table_scan.rs (95%) rename {dask_planner/src => src}/sql/logical/use_schema.rs (97%) rename {dask_planner/src => src}/sql/logical/window.rs (96%) rename {dask_planner/src => src}/sql/optimizer.rs (92%) create mode 100644 src/sql/optimizer/decorrelate_where_exists.rs create mode 100644 src/sql/optimizer/decorrelate_where_in.rs rename {dask_planner/src => src}/sql/optimizer/dynamic_partition_pruning.rs (98%) rename {dask_planner/src => src}/sql/optimizer/join_reorder.rs (100%) create mode 100644 src/sql/optimizer/utils.rs rename {dask_planner/src => src}/sql/parser_utils.rs (100%) rename {dask_planner/src => src}/sql/schema.rs (95%) rename {dask_planner/src => src}/sql/statement.rs (88%) rename {dask_planner/src => src}/sql/table.rs (97%) rename {dask_planner/src => src}/sql/types.rs (95%) rename {dask_planner/src => src}/sql/types/rel_data_type.rs (98%) rename {dask_planner/src => src}/sql/types/rel_data_type_field.rs (98%) diff --git a/dask_planner/.cargo/config.toml b/.cargo/config.toml similarity index 100% rename from dask_planner/.cargo/config.toml rename to .cargo/config.toml diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 527d01fa2..1ff63a673 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -2,4 +2,7 @@ * @ayushdg @charlesbluca @galipremsagar # rust codeowners -dask_planner/ @ayushdg @charlesbluca @galipremsagar @jdye64 +.cargo/ @ayushdg @charlesbluca @galipremsagar @jdye64 +src/ @ayushdg @charlesbluca @galipremsagar @jdye64 +Cargo.toml @ayushdg @charlesbluca @galipremsagar @jdye64 +Cargo.lock @ayushdg @charlesbluca @galipremsagar @jdye64 diff --git a/.github/workflows/conda.yml b/.github/workflows/conda.yml index 20294124a..833f37293 100644 --- a/.github/workflows/conda.yml +++ b/.github/workflows/conda.yml @@ -6,10 +6,9 @@ on: pull_request: paths: - setup.py - - dask_planner/Cargo.toml - - dask_planner/Cargo.lock - - dask_planner/pyproject.toml - - dask_planner/rust-toolchain.toml + - Cargo.toml + - Cargo.lock + - pyproject.toml - continuous_integration/recipe/** - .github/workflows/conda.yml schedule: @@ -34,7 +33,9 @@ jobs: fail-fast: false matrix: python: ["3.8", "3.9", "3.10"] - arch: ["linux-64", "linux-aarch64"] + # FIXME: aarch64 builds are consuming too much memory to run on GHA + # arch: ["linux-64", "linux-aarch64"] + arch: ["linux-64"] steps: - uses: actions/checkout@v3 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3795b4823..6d63f6373 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,83 +15,135 @@ concurrency: env: upload: ${{ github.event_name == 'release' && github.repository == 'dask-contrib/dask-sql' }} -# Required shell entrypoint to have properly activated conda environments -defaults: - run: - shell: bash -l {0} - jobs: - wheels: - name: Build and publish py3.${{ matrix.python }} wheels on ${{ matrix.os }} - runs-on: ${{ matrix.os }} + linux: + name: Build and publish wheels for linux ${{ matrix.target }} + runs-on: ubuntu-latest strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest, macos-latest] - python: ["8", "9", "10"] # 3.x + target: [x86_64, aarch64] steps: - uses: actions/checkout@v3 + - name: Install Protoc + uses: arduino/setup-protoc@v1 + if: matrix.target == 'aarch64' + with: + version: '3.x' + repo-token: ${{ secrets.GITHUB_TOKEN }} + - uses: actions/setup-python@v4 + with: + python-version: '3.10' + - name: Build wheels for x86_64 + if: matrix.target == 'x86_64' + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.target }} + args: --release --out dist + sccache: 'true' + manylinux: '2_17' + before-script-linux: > + DOWNLOAD_URL=$(curl --retry 6 --retry-delay 10 -s https://api.github.com/repos/protocolbuffers/protobuf/releases/latest | grep -o '"browser_download_url": "[^"]*' | cut -d'"' -f4 | grep "\linux-x86_64.zip$") && + curl --retry 6 --retry-delay 10 -LO $DOWNLOAD_URL && + unzip protoc-*-linux-x86_64.zip -d $HOME/.local + docker-options: --env PROTOC=/root/.local/bin/protoc + - name: Build wheels for aarch64 + if: matrix.target == 'aarch64' + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.target }} + args: --release --out dist --zig + sccache: 'true' + manylinux: '2_17' + - name: Check dist files + run: | + pip install twine + + twine check dist/* + ls -lh dist/ + - name: Upload binary wheels + uses: actions/upload-artifact@v3 with: - fetch-depth: 0 + name: wheels for linux ${{ matrix.target }} + path: dist/* + - name: Publish package + if: env.upload == 'true' + env: + TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} + run: twine upload dist/* + + windows: + name: Build and publish wheels for windows + runs-on: windows-latest + steps: + - uses: actions/checkout@v3 - name: Install Protoc - if: matrix.os != 'ubuntu-latest' uses: arduino/setup-protoc@v1 with: version: '3.x' repo-token: ${{ secrets.GITHUB_TOKEN }} - - name: Set up QEMU for linux-aarch64 - if: matrix.os == 'ubuntu-latest' - uses: docker/setup-qemu-action@v2 + - uses: actions/setup-python@v4 with: - platforms: arm64 - - name: Add rust toolchain target for macos-aarch64 - if: matrix.os == 'macos-latest' - run: rustup target add aarch64-apple-darwin + python-version: '3.10' + architecture: x64 - name: Build wheels - uses: pypa/cibuildwheel@v2.11.3 + uses: PyO3/maturin-action@v1 + with: + target: x64 + args: --release --out dist + sccache: 'true' + - name: Check dist files + run: | + pip install twine + + twine check dist/* + ls dist/ + - name: Upload binary wheels + uses: actions/upload-artifact@v3 + with: + name: wheels for windows + path: dist/* + - name: Publish package + if: env.upload == 'true' env: - CIBW_BUILD: 'cp3${{ matrix.python }}-*' - CIBW_SKIP: '*musllinux*' - CIBW_ARCHS_LINUX: 'aarch64 x86_64' - CIBW_ARCHS_WINDOWS: 'AMD64' - CIBW_ARCHS_MACOS: 'x86_64 arm64' - # Without CARGO_NET_GIT_FETCH_WITH_CLI we oom (https://github.com/rust-lang/cargo/issues/10583) - CIBW_ENVIRONMENT_LINUX: > - CARGO_NET_GIT_FETCH_WITH_CLI="true" - PATH="$HOME/.cargo/bin:$HOME/.local/bin:$PATH" - CIBW_ENVIRONMENT_WINDOWS: 'PATH="$UserProfile\.cargo\bin;$PATH"' - CIBW_BEFORE_BUILD: 'pip install -U setuptools-rust' - CIBW_BEFORE_BUILD_LINUX: > - ARCH=$([ $(uname -m) == x86_64 ] && echo x86_64 || echo aarch_64) && - DOWNLOAD_URL=$(curl --retry 6 --retry-delay 10 -s https://api.github.com/repos/protocolbuffers/protobuf/releases/latest | grep -o '"browser_download_url": "[^"]*' | cut -d'"' -f4 | grep "\linux-${ARCH}.zip$") && - curl --retry 6 --retry-delay 10 -LO $DOWNLOAD_URL && - unzip protoc-*-linux-$ARCH.zip -d $HOME/.local && - protoc --version && - pip install -U setuptools-rust && - pip list && - curl --retry 6 --retry-delay 10 https://sh.rustup.rs -sSf | sh -s -- --default-toolchain=stable --profile=minimal -y && - rustup show + TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} + run: twine upload dist/* + + macos: + name: Build and publish wheels for macos ${{ matrix.target }} + runs-on: macos-latest + strategy: + fail-fast: false + matrix: + target: [x86_64, aarch64] + steps: + - uses: actions/checkout@v3 + - name: Install Protoc + uses: arduino/setup-protoc@v1 + with: + version: '3.x' + repo-token: ${{ secrets.GITHUB_TOKEN }} + - uses: actions/setup-python@v4 with: - package-dir: . - output-dir: dist - config-file: "dask_planner/pyproject.toml" - - name: Set up Python - uses: conda-incubator/setup-miniconda@v2.2.0 + python-version: '3.10' + - name: Build wheels + uses: PyO3/maturin-action@v1 with: - miniforge-variant: Mambaforge - use-mamba: true - python-version: "3.8" - channel-priority: strict + target: ${{ matrix.target }} + args: --release --out dist + sccache: 'true' - name: Check dist files run: | - mamba install twine + pip install twine twine check dist/* ls -lh dist/ - name: Upload binary wheels uses: actions/upload-artifact@v3 with: - name: wheels for py3.${{ matrix.python }} on ${{ matrix.os }} + name: wheels for macos ${{ matrix.target }} path: dist/* - name: Publish package if: env.upload == 'true' @@ -99,27 +151,23 @@ jobs: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: twine upload dist/* + sdist: - name: Build and publish source distribution runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 + - name: Build sdist + uses: PyO3/maturin-action@v1 with: - fetch-depth: 0 - - name: Set up Python - uses: conda-incubator/setup-miniconda@v2.2.0 + command: sdist + args: --out dist + - uses: actions/setup-python@v4 with: - miniforge-variant: Mambaforge - use-mamba: true - python-version: "3.8" - channel-priority: strict - - name: Build source distribution - run: | - mamba install setuptools-rust twine - - python setup.py sdist + python-version: '3.10' - name: Check dist files run: | + pip install twine + twine check dist/* ls -lh dist/ - name: Publish source distribution diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 7e983172b..a9eeab1ab 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -51,7 +51,6 @@ jobs: - name: Optionally update upstream dependencies if: needs.detect-ci-trigger.outputs.triggered == 'true' run: | - cd dask_planner bash update-dependencies.sh - name: Install Protoc uses: arduino/setup-protoc@v1 @@ -60,11 +59,9 @@ jobs: repo-token: ${{ secrets.GITHUB_TOKEN }} - name: Check workspace in debug mode run: | - cd dask_planner cargo check - name: Check workspace in release mode run: | - cd dask_planner cargo check --release # test the crate @@ -84,7 +81,6 @@ jobs: - name: Optionally update upstream dependencies if: needs.detect-ci-trigger.outputs.triggered == 'true' run: | - cd dask_planner bash update-dependencies.sh - name: Install Protoc uses: arduino/setup-protoc@v1 @@ -93,5 +89,4 @@ jobs: repo-token: ${{ secrets.GITHUB_TOKEN }} - name: Run tests run: | - cd dask_planner cargo test diff --git a/.github/workflows/test-upstream.yml b/.github/workflows/test-upstream.yml index 0305a3ab4..e6c30bf1a 100644 --- a/.github/workflows/test-upstream.yml +++ b/.github/workflows/test-upstream.yml @@ -68,11 +68,10 @@ jobs: - name: Optionally update upstream cargo dependencies if: env.which_upstream == 'DataFusion' run: | - cd dask_planner bash update-dependencies.sh - name: Build the Rust DataFusion bindings run: | - python setup.py build install + maturin develop - name: Install hive testing dependencies if: matrix.os == 'ubuntu-latest' run: | @@ -124,11 +123,9 @@ jobs: env: UPDATE_ALL_CARGO_DEPS: false run: | - cd dask_planner bash update-dependencies.sh - name: Install dependencies and nothing else run: | - mamba install setuptools-rust pip install -e . -vv which python diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e9080cf2f..745cdcfe0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -72,7 +72,7 @@ jobs: shared-key: test - name: Build the Rust DataFusion bindings run: | - python setup.py build install + maturin develop - name: Install hive testing dependencies if: matrix.os == 'ubuntu-latest' run: | @@ -118,7 +118,6 @@ jobs: repo-token: ${{ secrets.GITHUB_TOKEN }} - name: Install dependencies and nothing else run: | - mamba install "setuptools-rust>=1.5.2" pip install -e . -vv which python diff --git a/.gitignore b/.gitignore index 245817fc1..d41df8a68 100644 --- a/.gitignore +++ b/.gitignore @@ -46,23 +46,15 @@ venv # IDE .idea .vscode -planner/.classpath -planner/.project -planner/.settings/ -planner/.idea -planner/*.iml *.swp # project specific -planner/dependency-reduced-pom.xml -planner/target/ -dask_sql/jar -.next/ dask-worker-space/ node_modules/ docs/source/_build/ tests/unit/queries tests/unit/data +target/* # Ignore development specific local testing files dev_tests diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ed701014a..094c4ada1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -20,9 +20,9 @@ repos: rev: v1.0 hooks: - id: cargo-check - args: ['--manifest-path', './dask_planner/Cargo.toml', '--verbose', '--'] + args: ['--manifest-path', './Cargo.toml', '--verbose', '--'] - id: clippy - args: ['--manifest-path', './dask_planner/Cargo.toml', '--verbose', '--', '-D', 'warnings'] + args: ['--manifest-path', './Cargo.toml', '--verbose', '--', '-D', 'warnings'] - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.2.0 hooks: @@ -39,4 +39,4 @@ repos: entry: cargo +nightly fmt language: system types: [rust] - args: ['--manifest-path', './dask_planner/Cargo.toml', '--verbose', '--'] + args: ['--manifest-path', './Cargo.toml', '--verbose', '--'] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ab31230f..0f5adc85a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,17 +39,17 @@ DataFusion provides Dask-SQL with key functionality. ### Building Building the Dask-SQL Rust codebase is a straightforward process. If you create and activate the Dask-SQL Conda environment the Rust compiler and all necessary components will be installed for you during that process and therefore requires no further manual setup. -`setuptools-rust` is used by Dask-SQL for building and bundling the resulting Rust binaries. This helps make building and installing the Rust binaries feel much more like a native Python workflow. +`maturin` is used by Dask-SQL for building and bundling the resulting Rust binaries. This helps make building and installing the Rust binaries feel much more like a native Python workflow. -More details about the building setup can be found at [setup.py](setup.py) and searching for `rust_extensions` which is the hook for the Rust code build and inclusion. +More details about the building setup can be found in [pyproject.toml](pyproject.toml) and [Cargo.toml](Cargo.toml) -Note that while `setuptools-rust` is used by CI and should be used during your development cycle, if the need arises to do something more specific that is not yet supported by `setuptools-rust` you can opt to use `cargo` directly from the command line. +Note that while `maturin` is used by CI and should be used during your development cycle, if the need arises to do something more specific that is not yet supported by `maturin` you can opt to use `cargo` directly from the command line. #### Building with Python -Building Dask-SQL is straightforward with Python. To build run ```python setup.py install```. This will build both the Rust and Python codebase and install it into your locally activated conda environment. While not required, if you have updated dependencies for Rust you might prefer a clean build. To clean your setup run ```python setup.py clean``` and then run ```python setup.py install``` +Building Dask-SQL is straightforward with Python. To build run ```pip install .```. This will build both the Rust and Python codebase and install it into your locally activated conda environment; note that if your Rust dependencies have been updated, this command must be rerun to rebuild the Rust codebase. #### DataFusion Modules -DataFusion is broken down into a few modules. We consume those modules in our [Cargo.toml](dask_planner/Cargo.toml). The modules that we use currently are +DataFusion is broken down into a few modules. We consume those modules in our [Cargo.toml](Cargo.toml). The modules that we use currently are - `datafusion-common` - Datastructures and core logic - `datafusion-expr` - Expression based logic and operators @@ -57,9 +57,7 @@ DataFusion is broken down into a few modules. We consume those modules in our [C - `datafusion-optimizer` - Optimization logic and datastructures for modifying current plans into more efficient ones. #### Retrieving Upstream Dependencies -During development you might find yourself needing some upstream DataFusion changes not present in the projects current version. Luckily this can easily be achieved by updating [Cargo.toml](dask_planner/Cargo.toml) and changing the `rev` to the SHA of the version you need. Note that the same SHA should be used for all DataFusion modules. - -After updating the `Cargo.toml` file the codebase can be re-built to reflect those changes by running `python setup.py install` +During development you might find yourself needing some upstream DataFusion changes not present in the projects current version. Luckily this can easily be achieved by updating [Cargo.toml](Cargo.toml) and changing the `rev` to the SHA of the version you need. Note that the same SHA should be used for all DataFusion modules. #### Local Documentation Sometimes when building against the latest Github commits for DataFusion you may find that the features you are consuming do not have their documentation public yet. In this case it can be helpful to build the DataFusion documentation locally so that it can be referenced to assist with development. Here is a rough outline for building that documentation locally. @@ -72,40 +70,40 @@ Sometimes when building against the latest Github commits for DataFusion you may ### Datastructures While working in the Rust codebase there are a few datastructures that you should make yourself familiar with. This section does not aim to verbosely list out all of the datastructure with in the project but rather just the key datastructures that you are likely to encounter while working on almost any feature/issue. The aim is to give you a better overview of the codebase without having to manually dig through the all the source code. -- [`PyLogicalPlan`](dask_planner/src/sql/logical.rs) -> [DataFusion LogicalPlan](https://docs.rs/datafusion/latest/datafusion/logical_plan/enum.LogicalPlan.html) +- [`PyLogicalPlan`](src/sql/logical.rs) -> [DataFusion LogicalPlan](https://docs.rs/datafusion/latest/datafusion/logical_plan/enum.LogicalPlan.html) - Often encountered in Python code with variable name `rel` - Python serializable umbrella representation of the entire LogicalPlan that was generated by DataFusion - Provides access to `DaskTable` instances and type information for each table - Access to individual nodes in the logical plan tree. Ex: `TableScan` -- [`DaskSQLContext`](dask_planner/src/sql.rs) +- [`DaskSQLContext`](src/sql.rs) - Analogous to Python `Context` - Contains metadata about the tables, schemas, functions, operators, and configurations that are persent within the current execution context - When adding custom functions/UDFs this is the location that you would register them - Entry point for parsing SQL strings to sql node trees. This is the location Python will begin its interactions with Rust -- [`PyExpr`](dask_planner/src/expression.rs) -> [DataFusion Expr](https://docs.rs/datafusion/latest/datafusion/prelude/enum.Expr.html) +- [`PyExpr`](src/expression.rs) -> [DataFusion Expr](https://docs.rs/datafusion/latest/datafusion/prelude/enum.Expr.html) - Arguably where most of your time will be spent - Represents a single node in sql tree. Ex: `avg(age)` from `SELECT avg(age) FROM people` - Is associate with a single `RexType` - Can contain literal values or represent function calls, `avg()` for example - The expressions "index" in the tree can be retrieved by calling `PyExpr.index()` on an instance. This is useful when mapping frontend column names in Dask code to backend Dataframe columns - Certain `PyExpr`s contain operands. Ex: `2 + 2` would contain 3 operands. 1) A literal `PyExpr` instance with value 2 2) Another literal `PyExpr` instance with a value of 2. 3) A `+` `PyExpr` representing the addition of the 2 literals. -- [`DaskSqlOptimizer`](dask_planner/src/sql/optimizer.rs) +- [`DaskSqlOptimizer`](src/sql/optimizer.rs) - Registering location for all Dask-SQL specific logical plan optimizations - Optimizations that are written either custom or use from another source, DataFusion, are registered here in the order they are wished to be executed - Represents functions that modify/convert an original `PyLogicalPlan` into another `PyLogicalPlan` that would be more efficient when running in the underlying Dask framework -- [`RelDataType`](dask_planner/src/sql/types/rel_data_type.rs) +- [`RelDataType`](src/sql/types/rel_data_type.rs) - Not a fan of this name, was chosen to match existing Calcite logic - Represents a "row" in a table - Contains a list of "columns" that are present in that row - - [RelDataTypeField](dask_planner/src/sql/types/rel_data_type_field.rs) -- [RelDataTypeField](dask_planner/src/sql/types/rel_data_type_field.rs) + - [RelDataTypeField](src/sql/types/rel_data_type_field.rs) +- [RelDataTypeField](src/sql/types/rel_data_type_field.rs) - Represents an individual column in a table - Contains: - `qualifier` - schema the field belongs to - `name` - name of the column/field - `data_type` - `DaskTypeMap` instance containing information about the SQL type and underlying Arrow DataType - `index` - location of the field in the LogicalPlan -- [DaskTypeMap](dask_planner/src/sql/types.rs) +- [DaskTypeMap](src/sql/types.rs) - Maps a conventional SQL type to an underlying Arrow DataType diff --git a/dask_planner/Cargo.lock b/Cargo.lock similarity index 68% rename from dask_planner/Cargo.lock rename to Cargo.lock index ee67cfb89..c3f7d8600 100644 --- a/dask_planner/Cargo.lock +++ b/Cargo.lock @@ -29,9 +29,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67fc08ce920c31afb70f013dcce1bfc3a3195de6a228474e45e1f145b36f8d04" +checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" dependencies = [ "memchr", ] @@ -51,6 +51,18 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "allocator-api2" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56fc6cf8dc8c4158eed8649f9b8b0ea1518eb62b544fe9490d66fa0b349eafe9" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + [[package]] name = "android_system_properties" version = "0.1.5" @@ -85,8 +97,8 @@ dependencies = [ "serde", "serde_json", "snap", - "strum", - "strum_macros", + "strum 0.24.1", + "strum_macros 0.24.3", "thiserror", "typed-builder", "uuid", @@ -107,15 +119,15 @@ checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" [[package]] name = "arrayvec" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" +checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c" [[package]] name = "arrow" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990dfa1a9328504aa135820da1c95066537b69ad94c04881b785f64328e0fa6b" +checksum = "2feeebd77b34b0bc88f224e06d01c27da4733997cc4789a4e056196656cdc59a" dependencies = [ "ahash", "arrow-arith", @@ -136,9 +148,9 @@ dependencies = [ [[package]] name = "arrow-arith" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b2e52de0ab54173f9b08232b7184c26af82ee7ab4ac77c83396633c90199fa" +checksum = "7173f5dc49c0ecb5135f52565af33afd3fdc9a12d13bd6f9973e8b96305e4b2e" dependencies = [ "arrow-array", "arrow-buffer", @@ -151,9 +163,9 @@ dependencies = [ [[package]] name = "arrow-array" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10849b60c17dbabb334be1f4ef7550701aa58082b71335ce1ed586601b2f423" +checksum = "63d7ea725f7d1f8bb2cffc53ef538557e95fc802e217d5be25122d402e22f3d0" dependencies = [ "ahash", "arrow-buffer", @@ -162,15 +174,15 @@ dependencies = [ "chrono", "chrono-tz", "half", - "hashbrown 0.13.2", + "hashbrown 0.14.0", "num", ] [[package]] name = "arrow-buffer" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0746ae991b186be39933147117f8339eb1c4bbbea1c8ad37e7bf5851a1a06ba" +checksum = "bdbe439e077f484e5000b9e1d47b5e4c0d15f2b311a8f5bcc682553d5d67a722" dependencies = [ "half", "num", @@ -178,9 +190,9 @@ dependencies = [ [[package]] name = "arrow-cast" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b88897802515d7b193e38b27ddd9d9e43923d410a9e46307582d756959ee9595" +checksum = "93913cc14875770aa1eef5e310765e855effa352c094cb1c7c00607d0f37b4e1" dependencies = [ "arrow-array", "arrow-buffer", @@ -189,15 +201,16 @@ dependencies = [ "arrow-select", "chrono", "comfy-table", + "half", "lexical-core", "num", ] [[package]] name = "arrow-csv" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c8220d9741fc37961262710ceebd8451a5b393de57c464f0267ffdda1775c0a" +checksum = "ef55b67c55ed877e6fe7b923121c19dae5e31ca70249ea2779a17b58fb0fbd9a" dependencies = [ "arrow-array", "arrow-buffer", @@ -214,9 +227,9 @@ dependencies = [ [[package]] name = "arrow-data" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "533f937efa1aaad9dc86f6a0e382c2fa736a4943e2090c946138079bdf060cef" +checksum = "d4f4f4a3c54614126a71ab91f6631c9743eb4643d6e9318b74191da9dc6e028b" dependencies = [ "arrow-buffer", "arrow-schema", @@ -226,9 +239,9 @@ dependencies = [ [[package]] name = "arrow-ipc" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18b75296ff01833f602552dff26a423fc213db8e5049b540ca4a00b1c957e41c" +checksum = "d41a3659f984a524ef1c2981d43747b24d8eec78e2425267fcd0ef34ce71cd18" dependencies = [ "arrow-array", "arrow-buffer", @@ -240,9 +253,9 @@ dependencies = [ [[package]] name = "arrow-json" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e501d3de4d612c90677594896ca6c0fa075665a7ff980dc4189bb531c17e19f6" +checksum = "10b95faa95a378f56ef32d84cc0104ea998c39ef7cd1faaa6b4cebf8ea92846d" dependencies = [ "arrow-array", "arrow-buffer", @@ -251,17 +264,18 @@ dependencies = [ "arrow-schema", "chrono", "half", - "indexmap", + "indexmap 2.0.0", "lexical-core", "num", + "serde", "serde_json", ] [[package]] name = "arrow-ord" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d2671eb3793f9410230ac3efb0e6d36307be8a2dac5fad58ac9abde8e9f01e" +checksum = "c68549a4284d9f8b39586afb8d5ff8158b8f0286353a4844deb1d11cf1ba1f26" dependencies = [ "arrow-array", "arrow-buffer", @@ -274,9 +288,9 @@ dependencies = [ [[package]] name = "arrow-row" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc11fa039338cebbf4e29cf709c8ac1d6a65c7540063d4a25f991ab255ca85c8" +checksum = "0a75a4a757afc301ce010adadff54d79d66140c4282ed3de565f6ccb716a5cf3" dependencies = [ "ahash", "arrow-array", @@ -284,23 +298,23 @@ dependencies = [ "arrow-data", "arrow-schema", "half", - "hashbrown 0.13.2", + "hashbrown 0.14.0", ] [[package]] name = "arrow-schema" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d04f17f7b86ded0b5baf98fe6123391c4343e031acc3ccc5fa604cc180bff220" +checksum = "2bebcb57eef570b15afbcf2d07d813eb476fde9f6dd69c81004d6476c197e87e" dependencies = [ - "bitflags 2.2.1", + "bitflags 2.3.2", ] [[package]] name = "arrow-select" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "163e35de698098ff5f5f672ada9dc1f82533f10407c7a11e2cd09f3bcf31d18a" +checksum = "f6e2943fa433a48921e914417173816af64eef61c0a3d448280e6c40a62df221" dependencies = [ "arrow-array", "arrow-buffer", @@ -311,24 +325,25 @@ dependencies = [ [[package]] name = "arrow-string" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfdfbed1b10209f0dc68e6aa4c43dc76079af65880965c7c3b73f641f23d4aba" +checksum = "bbc92ed638851774f6d7af1ad900b92bc1486746497511868b4298fcbcfa35af" dependencies = [ "arrow-array", "arrow-buffer", "arrow-data", "arrow-schema", "arrow-select", + "num", "regex", - "regex-syntax 0.6.29", + "regex-syntax", ] [[package]] name = "async-compression" -version = "0.3.15" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942c7cd7ae39e91bde4820d74132e9862e62c2f386c3aa90ccf55949f5bad63a" +checksum = "5b0122885821398cc923ece939e24d1056a2384ee719432397fa9db87230ff11" dependencies = [ "bzip2", "flate2", @@ -338,8 +353,8 @@ dependencies = [ "pin-project-lite", "tokio", "xz2", - "zstd 0.11.2+zstd.1.5.2", - "zstd-safe 5.0.2+zstd.1.5.2", + "zstd", + "zstd-safe", ] [[package]] @@ -372,9 +387,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "base64" -version = "0.21.0" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" +checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" [[package]] name = "bitflags" @@ -384,9 +399,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.2.1" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24a6904aef64d73cf10ab17ebace7befb918b82164785cb89907993be7f83813" +checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded" [[package]] name = "blake2" @@ -399,9 +414,9 @@ dependencies = [ [[package]] name = "blake3" -version = "1.3.3" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef" +checksum = "729b71f35bd3fa1a4c86b85d32c8b9069ea7fe14f7a53cfabb65f62d4265b888" dependencies = [ "arrayref", "arrayvec", @@ -441,32 +456,11 @@ dependencies = [ "alloc-stdlib", ] -[[package]] -name = "bstr" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d4260bcc2e8fc9df1eac4919a720effeb63a3f0952f5bf4944adfa18897f09" -dependencies = [ - "memchr", - "once_cell", - "regex-automata", - "serde", -] - -[[package]] -name = "btoi" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" -dependencies = [ - "num-traits", -] - [[package]] name = "bumpalo" -version = "3.12.1" +version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b1ce199063694f33ffb7dd4e0ee620741495c32833cde5aa08f02a0bf96f0c8" +checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" [[package]] name = "byteorder" @@ -518,17 +512,14 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.24" +version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" +checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" dependencies = [ + "android-tzdata", "iana-time-zone", - "js-sys", - "num-integer", "num-traits", "serde", - "time 0.1.45", - "wasm-bindgen", "winapi", ] @@ -554,30 +545,14 @@ dependencies = [ "phf_codegen", ] -[[package]] -name = "clru" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8191fa7302e03607ff0e237d4246cc043ff5b3cb9409d995172ba3bea16b807" - -[[package]] -name = "codespan-reporting" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" -dependencies = [ - "termcolor", - "unicode-width", -] - [[package]] name = "comfy-table" -version = "6.1.4" +version = "7.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e7b787b0dc42e8111badfdbe4c3059158ccb2db8780352fa1b01e8ccf45cc4d" +checksum = "9ab77dbd8adecaf3f0db40581631b995f312a8a5ae3aa9993188bb8f23d83a5b" dependencies = [ - "strum", - "strum_macros", + "strum 0.24.1", + "strum_macros 0.24.3", "unicode-width", ] @@ -605,9 +580,9 @@ dependencies = [ [[package]] name = "constant_time_eq" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13418e745008f7349ec7e449155f419a61b92b58a99cc3616942b926825ec76b" +checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6" [[package]] name = "core-foundation-sys" @@ -651,9 +626,9 @@ dependencies = [ [[package]] name = "csv" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b015497079b9a9d69c02ad25de6c0a6edef051ea6360a327d0bd05802ef64ad" +checksum = "626ae34994d3d8d668f4269922248239db4ae42d538b14c398b74a52208e8086" dependencies = [ "csv-core", "itoa", @@ -670,50 +645,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "cxx" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f61f1b6389c3fe1c316bf8a4dccc90a38208354b330925bce1f74a6c4756eb93" -dependencies = [ - "cc", - "cxxbridge-flags", - "cxxbridge-macro", - "link-cplusplus", -] - -[[package]] -name = "cxx-build" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cee708e8962df2aeb38f594aae5d827c022b6460ac71a7a3e2c3c2aae5a07b" -dependencies = [ - "cc", - "codespan-reporting", - "once_cell", - "proc-macro2", - "quote", - "scratch", - "syn 2.0.23", -] - -[[package]] -name = "cxxbridge-flags" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7944172ae7e4068c533afbb984114a56c46e9ccddda550499caa222902c7f7bb" - -[[package]] -name = "cxxbridge-macro" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.23", -] - [[package]] name = "dashmap" version = "5.4.0" @@ -728,27 +659,29 @@ dependencies = [ ] [[package]] -name = "dask_planner" -version = "0.1.0" +name = "dask-sql" +version = "2023.6.0" dependencies = [ "async-trait", "datafusion-python", "env_logger", "log", "pyo3", - "pyo3-build-config 0.19.1", + "pyo3-build-config", "pyo3-log", ] [[package]] name = "datafusion" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bdb93fee4f30368f1f71bfd5cd28882ec9fab0183db7924827b76129d33227c" +checksum = "5ddbcb2dda5b5033537457992ebde78938014390b2b19f9f4282e3be0e18b0c3" dependencies = [ "ahash", "apache-avro", "arrow", + "arrow-array", + "arrow-schema", "async-compression", "async-trait", "bytes", @@ -760,14 +693,14 @@ dependencies = [ "datafusion-expr", "datafusion-optimizer", "datafusion-physical-expr", - "datafusion-row", "datafusion-sql", "flate2", "futures", "glob", - "hashbrown 0.13.2", - "indexmap", - "itertools", + "half", + "hashbrown 0.14.0", + "indexmap 2.0.0", + "itertools 0.11.0", "lazy_static", "log", "num-traits", @@ -782,19 +715,18 @@ dependencies = [ "sqlparser", "tempfile", "tokio", - "tokio-stream", "tokio-util", "url", "uuid", "xz2", - "zstd 0.12.3+zstd.1.5.2", + "zstd", ] [[package]] name = "datafusion-common" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e82401ce129e601d406012b6d718f8978ba84c386e1c342fa155877120d68824" +checksum = "85fbb7b4da925031311743ab96662d55f0f7342d3692744f184f99b2257ef435" dependencies = [ "apache-avro", "arrow", @@ -809,14 +741,14 @@ dependencies = [ [[package]] name = "datafusion-execution" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b08b2078aed21a27239cd93f3015e492a58b0d50ebeeaf8d2236cf108ef583ce" +checksum = "5bb3617466d894eb0ad11d06bab1e6e89c571c0a27d660685d327d0c6e1e1ccd" dependencies = [ "dashmap", "datafusion-common", "datafusion-expr", - "hashbrown 0.13.2", + "hashbrown 0.14.0", "log", "object_store", "parking_lot", @@ -827,21 +759,24 @@ dependencies = [ [[package]] name = "datafusion-expr" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b5b977ce9695fb4c67614266ec57f384fc11e9a9f9b3e6d0e62b9c5a9f2c1f" +checksum = "3bd8220a0dfcdfddcc785cd7e71770ef1ce54fbe1e08984e5adf537027ecb6de" dependencies = [ "ahash", "arrow", "datafusion-common", + "lazy_static", "sqlparser", + "strum 0.25.0", + "strum_macros 0.25.1", ] [[package]] name = "datafusion-optimizer" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0b2bb9e73ed778d1bc5af63a270f0154bf6eab5099c77668a6362296888e46b" +checksum = "1d685a100c66952aaadd0cbe766df46d1887d58fc8bcf3589e6387787f18492b" dependencies = [ "arrow", "async-trait", @@ -849,34 +784,37 @@ dependencies = [ "datafusion-common", "datafusion-expr", "datafusion-physical-expr", - "hashbrown 0.13.2", - "itertools", + "hashbrown 0.14.0", + "itertools 0.11.0", "log", - "regex-syntax 0.6.29", + "regex-syntax", ] [[package]] name = "datafusion-physical-expr" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80cd8ea5ab0a07b1b2a3e17d5909f1b1035bd129ffeeb5c66842a32e682f8f79" +checksum = "0f2c635da9b05b4b4c6c8d935f46fd99f9b6225f834091cf4e3c8a045b68beab" dependencies = [ "ahash", "arrow", "arrow-array", "arrow-buffer", "arrow-schema", + "base64", "blake2", "blake3", "chrono", "datafusion-common", "datafusion-expr", - "datafusion-row", "half", - "hashbrown 0.13.2", - "indexmap", - "itertools", + "hashbrown 0.14.0", + "hex", + "indexmap 2.0.0", + "itertools 0.11.0", "lazy_static", + "libc", + "log", "md-5", "paste", "petgraph", @@ -889,8 +827,9 @@ dependencies = [ [[package]] name = "datafusion-python" -version = "22.0.0" -source = "git+https://github.com/apache/arrow-datafusion-python.git?rev=9493638#94936380e58a266f5dd5de6b70a06d3aa36fbe22" +version = "28.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a2441774e84875ae16a8b5277090ed6ab77ce94ab1820c315ed02cd3813de29" dependencies = [ "async-trait", "datafusion", @@ -903,33 +842,23 @@ dependencies = [ "mimalloc", "object_store", "parking_lot", + "prost", + "prost-types", "pyo3", - "pyo3-build-config 0.18.3", + "pyo3-build-config", "rand", - "regex-syntax 0.6.29", + "regex-syntax", "syn 2.0.23", "tokio", "url", "uuid", ] -[[package]] -name = "datafusion-row" -version = "22.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a95d6badab19fd6e9195fdc5209ac0a7e5ce9bcdedc67767b9ffc1b4e645760" -dependencies = [ - "arrow", - "datafusion-common", - "paste", - "rand", -] - [[package]] name = "datafusion-sql" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37a78f8fc67123c4357e63bc0c87622a2a663d26f074958d749a633d0ecde90f" +checksum = "b3ef8abf4dd84d3f20c910822b52779c035ab7f4f2d5e7125ede3bae618e9de8" dependencies = [ "arrow", "arrow-schema", @@ -941,63 +870,38 @@ dependencies = [ [[package]] name = "datafusion-substrait" -version = "22.0.0" +version = "28.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae6ed64a2005f0d78f2b1b3ec3f8148183f4523d5d364e5367115f8d8a82b7df" +checksum = "2c97d351bbd6bd6497e7c9606ddd3c00cd63e9d185d7ab96fc8a66cf3c449177" dependencies = [ "async-recursion", "chrono", "datafusion", - "itertools", + "itertools 0.11.0", "object_store", "prost", + "prost-types", "substrait", "tokio", ] [[package]] name = "digest" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", "subtle", ] -[[package]] -name = "dirs" -version = "4.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" -dependencies = [ - "libc", - "redox_users", - "winapi", -] - [[package]] name = "doc-comment" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" -[[package]] -name = "dunce" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56ce8c6da7551ec6c462cbaf3bfbc75131ebbfa1c944aeaa9dab51ca1c5f0c3b" - [[package]] name = "dyn-clone" version = "1.0.11" @@ -1032,6 +936,12 @@ dependencies = [ "termcolor", ] +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + [[package]] name = "errno" version = "0.3.1" @@ -1040,7 +950,7 @@ checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" dependencies = [ "errno-dragonfly", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -1062,18 +972,6 @@ dependencies = [ "instant", ] -[[package]] -name = "filetime" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cbc844cecaee9d4443931972e1289c8ff485cb4cc2767cb03ca139ed6885153" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall 0.2.16", - "windows-sys 0.48.0", -] - [[package]] name = "fixedbitset" version = "0.4.2" @@ -1082,9 +980,9 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" [[package]] name = "flatbuffers" -version = "23.1.21" +version = "23.5.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77f5399c2c9c50ae9418e522842ad362f61ee48b346ac106807bd355a8a7c619" +checksum = "4dac53e22462d78c16d64a1cd22371b54cc3fe94aa15e7886a2fa6e5d1ab8640" dependencies = [ "bitflags 1.3.2", "rustc_version", @@ -1108,9 +1006,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "form_urlencoded" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" +checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" dependencies = [ "percent-encoding", ] @@ -1216,555 +1114,28 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", -] - -[[package]] -name = "gix" -version = "0.43.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c256ea71cc1967faaefdaad15f334146b7c806f12460dcafd3afed845c8c78dd" -dependencies = [ - "gix-actor", - "gix-attributes", - "gix-config", - "gix-credentials", - "gix-date", - "gix-diff", - "gix-discover", - "gix-features 0.28.1", - "gix-glob", - "gix-hash 0.10.4", - "gix-hashtable", - "gix-index", - "gix-lock", - "gix-mailmap", - "gix-object", - "gix-odb", - "gix-pack", - "gix-path", - "gix-prompt", - "gix-ref", - "gix-refspec", - "gix-revision", - "gix-sec", - "gix-tempfile", - "gix-traverse", - "gix-url", - "gix-validate", - "gix-worktree", - "log", - "once_cell", - "signal-hook", - "smallvec", - "thiserror", - "unicode-normalization", -] - -[[package]] -name = "gix-actor" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc22b0cdc52237667c301dd7cdc6ead8f8f73c9f824e9942c8ebd6b764f6c0bf" -dependencies = [ - "bstr", - "btoi", - "gix-date", - "itoa", - "nom", - "thiserror", + "wasi", ] [[package]] -name = "gix-attributes" -version = "0.10.0" +name = "git2" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2231a25934a240d0a4b6f4478401c73ee81d8be52de0293eedbc172334abf3e1" -dependencies = [ - "bstr", - "gix-features 0.28.1", - "gix-glob", - "gix-path", - "gix-quote", - "thiserror", - "unicode-bom", -] - -[[package]] -name = "gix-bitmap" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55a95f4942360766c3880bdb2b4b57f1ef73b190fc424755e7fdf480430af618" -dependencies = [ - "thiserror", -] - -[[package]] -name = "gix-chunk" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0d39583cab06464b8bf73b3f1707458270f0e7383cb24c3c9c1a16e6f792978" -dependencies = [ - "thiserror", -] - -[[package]] -name = "gix-command" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2c6f75c1e0f924de39e750880a6e21307194bb1ab773efe3c7d2d787277f8ab" -dependencies = [ - "bstr", -] - -[[package]] -name = "gix-config" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fbad5ce54a8fc997acc50febd89ec80fa6e97cb7f8d0654cb229936407489d8" -dependencies = [ - "bstr", - "gix-config-value", - "gix-features 0.28.1", - "gix-glob", - "gix-path", - "gix-ref", - "gix-sec", - "log", - "memchr", - "nom", - "once_cell", - "smallvec", - "thiserror", - "unicode-bom", -] - -[[package]] -name = "gix-config-value" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d09154c0c8677e4da0ec35e896f56ee3e338e741b9599fae06075edd83a4081c" +checksum = "7b989d6a7ca95a362cf2cfc5ad688b3a467be1f87e480b8dad07fee8c79b0044" dependencies = [ "bitflags 1.3.2", - "bstr", - "gix-path", "libc", - "thiserror", -] - -[[package]] -name = "gix-credentials" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "750b684197374518ea057e0a0594713e07683faa0a3f43c0f93d97f64130ad8d" -dependencies = [ - "bstr", - "gix-command", - "gix-config-value", - "gix-path", - "gix-prompt", - "gix-sec", - "gix-url", - "thiserror", -] - -[[package]] -name = "gix-date" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96271912ce39822501616f177dea7218784e6c63be90d5f36322ff3a722aae2" -dependencies = [ - "bstr", - "itoa", - "thiserror", - "time 0.3.20", -] - -[[package]] -name = "gix-diff" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "103a0fa79b0d438f5ecb662502f052e530ace4fe1fe8e1c83c0c6da76d728e67" -dependencies = [ - "gix-hash 0.10.4", - "gix-object", - "imara-diff", - "thiserror", -] - -[[package]] -name = "gix-discover" -version = "0.16.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eba8ba458cb8f4a6c33409b0fe650b1258655175a7ffd1d24fafd3ed31d880b" -dependencies = [ - "bstr", - "dunce", - "gix-hash 0.10.4", - "gix-path", - "gix-ref", - "gix-sec", - "thiserror", -] - -[[package]] -name = "gix-features" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b76f9a80f6dd7be66442ae86e1f534effad9546676a392acc95e269d0c21c22" -dependencies = [ - "crc32fast", - "flate2", - "gix-hash 0.10.4", - "libc", - "once_cell", - "prodash", - "sha1_smol", - "thiserror", - "walkdir", -] - -[[package]] -name = "gix-features" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf69b0f5c701cc3ae22d3204b671907668f6437ca88862d355eaf9bc47a4f897" -dependencies = [ - "gix-hash 0.11.1", - "libc", -] - -[[package]] -name = "gix-fs" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b37a1832f691fdc09910bd267f9a2e413737c1f9ec68c6e31f9e802616278a9" -dependencies = [ - "gix-features 0.29.0", -] - -[[package]] -name = "gix-glob" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93e43efd776bc543f46f0fd0ca3d920c37af71a764a16f2aebd89765e9ff2993" -dependencies = [ - "bitflags 1.3.2", - "bstr", -] - -[[package]] -name = "gix-hash" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a258595457bc192d1f1c59d0d168a1e34e2be9b97a614e14995416185de41a7" -dependencies = [ - "hex", - "thiserror", -] - -[[package]] -name = "gix-hash" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "078eec3ac2808cc03f0bddd2704cb661da5c5dc33b41a9d7947b141d499c7c42" -dependencies = [ - "hex", - "thiserror", -] - -[[package]] -name = "gix-hashtable" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4e55e40dfd694884f0eb78796c5bddcf2f8b295dace47039099dd7e76534973" -dependencies = [ - "gix-hash 0.10.4", - "hashbrown 0.13.2", - "parking_lot", -] - -[[package]] -name = "gix-index" -version = "0.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "717ab601ece7921f59fe86849dbe27d44a46ebb883b5885732c4f30df4996177" -dependencies = [ - "bitflags 1.3.2", - "bstr", - "btoi", - "filetime", - "gix-bitmap", - "gix-features 0.28.1", - "gix-hash 0.10.4", - "gix-lock", - "gix-object", - "gix-traverse", - "itoa", - "memmap2", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-lock" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c693d7f05730fa74a7c467150adc7cea393518410c65f0672f80226b8111555" -dependencies = [ - "gix-tempfile", - "gix-utils", - "thiserror", -] - -[[package]] -name = "gix-mailmap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b66aea5e52875cd4915f4957a6f4b75831a36981e2ec3f5fad9e370e444fe1a" -dependencies = [ - "bstr", - "gix-actor", - "thiserror", -] - -[[package]] -name = "gix-object" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df068db9180ee935fbb70504848369e270bdcb576b05c0faa8b9fd3b86fc017" -dependencies = [ - "bstr", - "btoi", - "gix-actor", - "gix-features 0.28.1", - "gix-hash 0.10.4", - "gix-validate", - "hex", - "itoa", - "nom", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-odb" -version = "0.43.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e83af2e3e36005bfe010927f0dff41fb5acc3e3d89c6f1174135b3a34086bda2" -dependencies = [ - "arc-swap", - "gix-features 0.28.1", - "gix-hash 0.10.4", - "gix-object", - "gix-pack", - "gix-path", - "gix-quote", - "parking_lot", - "tempfile", - "thiserror", -] - -[[package]] -name = "gix-pack" -version = "0.33.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9401911c7fe032ad7b31c6a6b5be59cb283d1d6c999417a8215056efe6d635f3" -dependencies = [ - "clru", - "gix-chunk", - "gix-diff", - "gix-features 0.28.1", - "gix-hash 0.10.4", - "gix-hashtable", - "gix-object", - "gix-path", - "gix-tempfile", - "gix-traverse", - "memmap2", - "parking_lot", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-path" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32370dce200bb951df013e03dff35b4233fc7a89458642b047629b91734a7e19" -dependencies = [ - "bstr", - "thiserror", -] - -[[package]] -name = "gix-prompt" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f3034d4d935aef2c7bf719aaa54b88c520e82413118d886ae880a31d5bdee57" -dependencies = [ - "gix-command", - "gix-config-value", - "nix", - "parking_lot", - "thiserror", -] - -[[package]] -name = "gix-quote" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a282f5a8d9ee0b09ec47390ac727350c48f2f5c76d803cd8da6b3e7ad56e0bcb" -dependencies = [ - "bstr", - "btoi", - "thiserror", -] - -[[package]] -name = "gix-ref" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4e909396ed3b176823991ccc391c276ae2a015e54edaafa3566d35123cfac9d" -dependencies = [ - "gix-actor", - "gix-features 0.28.1", - "gix-hash 0.10.4", - "gix-lock", - "gix-object", - "gix-path", - "gix-tempfile", - "gix-validate", - "memmap2", - "nom", - "thiserror", -] - -[[package]] -name = "gix-refspec" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aba332462bda2e8efeae4302b39a6ed01ad56ef772fd5b7ef197cf2798294d65" -dependencies = [ - "bstr", - "gix-hash 0.10.4", - "gix-revision", - "gix-validate", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-revision" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c6f6ff53f888858afc24bf12628446a14279ceec148df6194481f306f553ad2" -dependencies = [ - "bstr", - "gix-date", - "gix-hash 0.10.4", - "gix-hashtable", - "gix-object", - "thiserror", -] - -[[package]] -name = "gix-sec" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8ffa5bf0772f9b01de501c035b6b084cf9b8bb07dec41e3afc6a17336a65f47" -dependencies = [ - "bitflags 1.3.2", - "dirs", - "gix-path", - "libc", - "windows 0.43.0", -] - -[[package]] -name = "gix-tempfile" -version = "5.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71a0d32f34e71e86586124225caefd78dabc605d0486de580d717653addf182" -dependencies = [ - "gix-fs", - "libc", - "once_cell", - "parking_lot", - "signal-hook", - "signal-hook-registry", - "tempfile", -] - -[[package]] -name = "gix-traverse" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd9a4a07bb22168dc79c60e1a6a41919d198187ca83d8a5940ad8d7122a45df3" -dependencies = [ - "gix-hash 0.10.4", - "gix-hashtable", - "gix-object", - "thiserror", -] - -[[package]] -name = "gix-url" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6a22b4b32ad14d68f7b7fb6458fa58d44b01797d94c1b8f4db2d9c7b3c366b5" -dependencies = [ - "bstr", - "gix-features 0.28.1", - "gix-path", - "home", - "thiserror", + "libgit2-sys", + "log", "url", ] -[[package]] -name = "gix-utils" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c10b69beac219acb8df673187a1f07dde2d74092f974fb3f9eb385aeb667c909" -dependencies = [ - "fastrand", -] - -[[package]] -name = "gix-validate" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd629d3680773e1785e585d76fd4295b740b559cad9141517300d99a0c8c049" -dependencies = [ - "bstr", - "thiserror", -] - -[[package]] -name = "gix-worktree" -version = "0.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54ec9a000b4f24af706c3cc680c7cda235656cbe3216336522f5692773b8a301" -dependencies = [ - "bstr", - "gix-attributes", - "gix-features 0.28.1", - "gix-glob", - "gix-hash 0.10.4", - "gix-index", - "gix-object", - "gix-path", - "io-close", - "thiserror", -] - [[package]] name = "glob" version = "0.3.1" @@ -1773,9 +1144,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.18" +version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17f8a914c2987b688368b5138aa05321db91f4090cf26118185672ad588bce21" +checksum = "d357c7ae988e7d2182f7d7871d0b963962420b0678b0997ce7de72001aeab782" dependencies = [ "bytes", "fnv", @@ -1783,7 +1154,7 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap", + "indexmap 1.9.3", "slab", "tokio", "tokio-util", @@ -1815,6 +1186,16 @@ dependencies = [ "ahash", ] +[[package]] +name = "hashbrown" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" +dependencies = [ + "ahash", + "allocator-api2", +] + [[package]] name = "heck" version = "0.4.1" @@ -1842,15 +1223,6 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "home" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" -dependencies = [ - "windows-sys 0.48.0", -] - [[package]] name = "http" version = "0.2.9" @@ -1917,9 +1289,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.23.2" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c" +checksum = "0646026eb1b3eea4cd9ba47912ea5ce9cc07713d105b1a14698f4e6433d348b7" dependencies = [ "http", "hyper", @@ -1930,56 +1302,55 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.56" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0722cd7114b7de04316e7ea5456a0bbb20e4adb46fd27a3697adb812cff0f37c" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "windows 0.48.0", + "windows", ] [[package]] name = "iana-time-zone-haiku" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" dependencies = [ - "cxx", - "cxx-build", + "cc", ] [[package]] name = "idna" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" dependencies = [ "unicode-bidi", "unicode-normalization", ] [[package]] -name = "imara-diff" -version = "0.1.5" +name = "indexmap" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e98c1d0ad70fc91b8b9654b1f33db55e59579d3b3de2bffdced0fdb810570cb8" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ - "ahash", + "autocfg", "hashbrown 0.12.3", ] [[package]] name = "indexmap" -version = "1.9.3" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" dependencies = [ - "autocfg", - "hashbrown 0.12.3", + "equivalent", + "hashbrown 0.14.0", ] [[package]] @@ -2003,25 +1374,15 @@ version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02" -[[package]] -name = "io-close" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cadcf447f06744f8ce713d2d6239bb5bde2c357a452397a9ed90c625da390bc" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "io-lifetimes" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ "hermit-abi 0.3.1", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2039,7 +1400,7 @@ dependencies = [ "hermit-abi 0.3.1", "io-lifetimes", "rustix", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2051,6 +1412,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.6" @@ -2068,9 +1438,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.61" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" dependencies = [ "wasm-bindgen", ] @@ -2147,15 +1517,15 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.142" +version = "0.2.146" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a987beff54b60ffa6d51982e1aa1146bc42f19bd26be28b0586f252fccf5317" +checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" [[package]] name = "libflate" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97822bf791bd4d5b403713886a5fbe8bf49520fe78e323b0dc480ca1a03e50b0" +checksum = "5ff4ae71b685bbad2f2f391fe74f6b7659a34871c08b210fdc039e43bee07d18" dependencies = [ "adler32", "crc32fast", @@ -2171,11 +1541,23 @@ dependencies = [ "rle-decode-fast", ] +[[package]] +name = "libgit2-sys" +version = "0.15.2+1.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a80df2e11fb4a61f4ba2ab42dbe7f74468da143f1a75c74e11dee7c813f694fa" +dependencies = [ + "cc", + "libc", + "libz-sys", + "pkg-config", +] + [[package]] name = "libm" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" +checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4" [[package]] name = "libmimalloc-sys" @@ -2188,25 +1570,28 @@ dependencies = [ ] [[package]] -name = "link-cplusplus" -version = "1.0.8" +name = "libz-sys" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" +checksum = "56ee889ecc9568871456d42f603d6a0ce59ff328d291063a45cbdf0036baf6db" dependencies = [ "cc", + "libc", + "pkg-config", + "vcpkg", ] [[package]] name = "linux-raw-sys" -version = "0.3.7" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ece97ea872ece730aed82664c424eb4c8291e1ff2480247ccf7409044bc6479f" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "lock_api" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" dependencies = [ "autocfg", "scopeguard", @@ -2264,20 +1649,11 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" -[[package]] -name = "memmap2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327" -dependencies = [ - "libc", -] - [[package]] name = "memoffset" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" dependencies = [ "autocfg", ] @@ -2297,12 +1673,6 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - [[package]] name = "miniz_oxide" version = "0.7.1" @@ -2314,14 +1684,13 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" +checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" dependencies = [ "libc", - "log", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.45.0", + "wasi", + "windows-sys", ] [[package]] @@ -2330,28 +1699,6 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" -[[package]] -name = "nix" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfdda3d196821d6af13126e40375cdf7da646a96114af134d5f417a9a1dc8e1a" -dependencies = [ - "bitflags 1.3.2", - "cfg-if", - "libc", - "static_assertions", -] - -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - [[package]] name = "num" version = "0.4.0" @@ -2439,27 +1786,20 @@ dependencies = [ "libc", ] -[[package]] -name = "num_threads" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" -dependencies = [ - "libc", -] - [[package]] name = "object_store" -version = "0.5.6" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec9cd6ca25e796a49fa242876d1c4de36a24a6da5258e9f0bc062dbf5e81c53b" +checksum = "27c776db4f332b571958444982ff641d2531417a326ca368995073b639205d58" dependencies = [ "async-trait", "base64", "bytes", "chrono", "futures", - "itertools", + "humantime", + "hyper", + "itertools 0.10.5", "parking_lot", "percent-encoding", "quick-xml", @@ -2478,9 +1818,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.17.1" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" [[package]] name = "ordered-float" @@ -2503,22 +1843,22 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.7" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" +checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.2.16", + "redox_syscall", "smallvec", - "windows-sys 0.45.0", + "windows-targets", ] [[package]] name = "parquet" -version = "36.0.0" +version = "43.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "321a15f8332645759f29875b07f8233d16ed8ec1b3582223de81625a9f8506b7" +checksum = "ec7267a9607c3f955d4d0ac41b88a67cecc0d8d009173ad3da390699a6cb3750" dependencies = [ "ahash", "arrow-array", @@ -2534,17 +1874,18 @@ dependencies = [ "chrono", "flate2", "futures", - "hashbrown 0.13.2", + "hashbrown 0.14.0", "lz4", "num", "num-bigint", + "object_store", "paste", "seq-macro", "snap", "thrift", "tokio", "twox-hash", - "zstd 0.12.3+zstd.1.5.2", + "zstd", ] [[package]] @@ -2564,9 +1905,9 @@ checksum = "9f746c4065a8fa3fe23974dd82f15431cc8d40779821001404d10d2e79ca7d79" [[package]] name = "percent-encoding" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" +checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "petgraph" @@ -2575,7 +1916,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4dd7d28ee937e54fe3080c91faa1c3a46c06de6252988a7f4592ba2310ef22a4" dependencies = [ "fixedbitset", - "indexmap", + "indexmap 1.9.3", ] [[package]] @@ -2642,9 +1983,9 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "prettyplease" -version = "0.2.4" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ceca8aaf45b5c46ec7ed39fff75f57290368c1846d33d24a122ca81416ab058" +checksum = "3b69d39aab54d069e7f2fe8cb970493e7834601ca2d8c65fd7bbd183578080d1" dependencies = [ "proc-macro2", "syn 2.0.23", @@ -2665,12 +2006,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "prodash" -version = "23.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9516b775656bc3e8985e19cd4b8c0c0de045095074e453d2c0a513b5f978392d" - [[package]] name = "prost" version = "0.11.9" @@ -2689,7 +2024,7 @@ checksum = "119533552c9a7ffacc21e099c24a0ac8bb19c2a2a3f363de84cd9b844feab270" dependencies = [ "bytes", "heck", - "itertools", + "itertools 0.10.5", "lazy_static", "log", "multimap", @@ -2708,7 +2043,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4" dependencies = [ "anyhow", - "itertools", + "itertools 0.10.5", "proc-macro2", "quote", "syn 1.0.109", @@ -2725,31 +2060,21 @@ dependencies = [ [[package]] name = "pyo3" -version = "0.18.3" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b1ac5b3731ba34fdaa9785f8d74d17448cd18f30cf19e0c7e7b1fdb5272109" +checksum = "ffb88ae05f306b4bfcde40ac4a51dc0b05936a9207a4b75b798c7729c4258a59" dependencies = [ "cfg-if", "indoc", "libc", "memoffset", "parking_lot", - "pyo3-build-config 0.18.3", + "pyo3-build-config", "pyo3-ffi", "pyo3-macros", "unindent", ] -[[package]] -name = "pyo3-build-config" -version = "0.18.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cb946f5ac61bb61a5014924910d936ebd2b23b705f7a4a3c40b05c720b079a3" -dependencies = [ - "once_cell", - "target-lexicon", -] - [[package]] name = "pyo3-build-config" version = "0.19.1" @@ -2762,12 +2087,12 @@ dependencies = [ [[package]] name = "pyo3-ffi" -version = "0.18.3" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd4d7c5337821916ea2a1d21d1092e8443cf34879e53a0ac653fbb98f44ff65c" +checksum = "922ede8759e8600ad4da3195ae41259654b9c55da4f7eec84a0ccc7d067a70a4" dependencies = [ "libc", - "pyo3-build-config 0.18.3", + "pyo3-build-config", ] [[package]] @@ -2783,9 +2108,9 @@ dependencies = [ [[package]] name = "pyo3-macros" -version = "0.18.3" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d39c55dab3fc5a4b25bbd1ac10a2da452c4aca13bb450f22818a002e29648d" +checksum = "8a5caec6a1dd355964a841fcbeeb1b89fe4146c87295573f94228911af3cc5a2" dependencies = [ "proc-macro2", "pyo3-macros-backend", @@ -2795,9 +2120,9 @@ dependencies = [ [[package]] name = "pyo3-macros-backend" -version = "0.18.3" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97daff08a4c48320587b5224cc98d609e3c27b6d437315bd40b605c98eeb5918" +checksum = "e0b78ccbb160db1556cdb6fd96c50334c5d4ec44dc5e0a968d0a1208fa0efa8b" dependencies = [ "proc-macro2", "quote", @@ -2859,15 +2184,6 @@ dependencies = [ "getrandom", ] -[[package]] -name = "redox_syscall" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "redox_syscall" version = "0.3.5" @@ -2877,51 +2193,28 @@ dependencies = [ "bitflags 1.3.2", ] -[[package]] -name = "redox_users" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" -dependencies = [ - "getrandom", - "redox_syscall 0.2.16", - "thiserror", -] - [[package]] name = "regex" -version = "1.8.1" +version = "1.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af83e617f331cc6ae2da5443c602dfa5af81e517212d9d611a5b3ba1777b5370" +checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.7.1", + "regex-syntax", ] -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.6.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" - [[package]] name = "regex-syntax" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5996294f19bd3aae0453a862ad728f60e6600695733dd5df01da90c54363a3c" +checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78" [[package]] name = "regress" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d995d590bd8ec096d1893f414bf3f5e8b0ee4c9eed9a5642b9766ef2c8e2e8e9" +checksum = "82a9ecfa0cb04d0b04dddb99b8ccf4f66bc8dfd23df694b398570bd8ae3a50fb" dependencies = [ "hashbrown 0.13.2", "memchr", @@ -2929,9 +2222,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.17" +version = "0.11.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13293b639a097af28fc8a90f22add145a9c954e49d77da06263d58cf44d5fb91" +checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" dependencies = [ "base64", "bytes", @@ -3000,28 +2293,28 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.19" +version = "0.37.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acf8729d8542766f1b2cf77eb034d52f40d375bb8b615d0b147089946e16613d" +checksum = "b96e891d04aa506a6d1f318d2771bcb1c7dfda84e126660ace067c9b474bb2c0" dependencies = [ "bitflags 1.3.2", "errno", "io-lifetimes", "libc", "linux-raw-sys", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] name = "rustls" -version = "0.20.8" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f" +checksum = "c911ba11bc8433e811ce56fde130ccf32f5127cab0e0194e9c68c5a5b671791e" dependencies = [ "log", "ring", + "rustls-webpki", "sct", - "webpki", ] [[package]] @@ -3033,6 +2326,16 @@ dependencies = [ "base64", ] +[[package]] +name = "rustls-webpki" +version = "0.100.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6207cd5ed3d8dca7816f8f3725513a34609c0c765bf652b8c3cb4cfd87db46b" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.12" @@ -3084,12 +2387,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" -[[package]] -name = "scratch" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" - [[package]] name = "sct" version = "0.7.0" @@ -3114,18 +2411,18 @@ checksum = "e6b44e8fc93a14e66336d230954dda83d18b4605ccace8fe09bc7514a71ad0bc" [[package]] name = "serde" -version = "1.0.160" +version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" +checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.160" +version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" +checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" dependencies = [ "proc-macro2", "quote", @@ -3156,13 +2453,14 @@ dependencies = [ [[package]] name = "serde_tokenstream" -version = "0.1.7" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "797ba1d80299b264f3aac68ab5d12e5825a561749db4df7cd7c8083900c5d4e9" +checksum = "8a00ffd23fd882d096f09fcaae2a9de8329a328628e86027e049ee051dc1621f" dependencies = [ "proc-macro2", + "quote", "serde", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] @@ -3183,19 +2481,13 @@ version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9d684e3ec7de3bf5466b32bd75303ac16f0736426e5a4e0d6e489559ce1249c" dependencies = [ - "indexmap", + "indexmap 1.9.3", "itoa", "ryu", "serde", "unsafe-libyaml", ] -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - [[package]] name = "sha2" version = "0.10.6" @@ -3207,25 +2499,6 @@ dependencies = [ "digest", ] -[[package]] -name = "signal-hook" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9" -dependencies = [ - "libc", - "signal-hook-registry", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" -dependencies = [ - "libc", -] - [[package]] name = "siphasher" version = "0.3.10" @@ -3293,9 +2566,9 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" [[package]] name = "sqlparser" -version = "0.32.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0366f270dbabb5cc2e4c88427dc4c08bba144f81e32fbd459a013f26a4d16aa0" +checksum = "ca597d77c98894be1f965f2e4e2d2a61575d4998088e655476c73715c54b2b43" dependencies = [ "log", "sqlparser_derive", @@ -3324,6 +2597,15 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros 0.25.1", +] + [[package]] name = "strum_macros" version = "0.24.3" @@ -3337,13 +2619,26 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "strum_macros" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6069ca09d878a33f883cc06aaa9718ede171841d3832450354410b718b097232" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.23", +] + [[package]] name = "substrait" -version = "0.7.5" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3ae64fb7ad0670c7d6d53d57b1b91beb2212afc30e164cc8edb02d6b2cff32a" +checksum = "2ac1ce8315086b127ca0abf162c62279550942bb26ebf7946fe17fe114446472" dependencies = [ - "gix", + "git2", "heck", "prettyplease", "prost", @@ -3361,9 +2656,9 @@ dependencies = [ [[package]] name = "subtle" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" [[package]] name = "syn" @@ -3395,15 +2690,16 @@ checksum = "fd1ba337640d60c3e96bc6f0638a939b9c9a7f2c316a1598c279828b3d1dc8c5" [[package]] name = "tempfile" -version = "3.5.0" +version = "3.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" +checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" dependencies = [ + "autocfg", "cfg-if", "fastrand", - "redox_syscall 0.3.5", + "redox_syscall", "rustix", - "windows-sys 0.45.0", + "windows-sys", ] [[package]] @@ -3446,46 +2742,6 @@ dependencies = [ "ordered-float", ] -[[package]] -name = "time" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" -dependencies = [ - "libc", - "wasi 0.10.0+wasi-snapshot-preview1", - "winapi", -] - -[[package]] -name = "time" -version = "0.3.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890" -dependencies = [ - "itoa", - "libc", - "num_threads", - "serde", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" - -[[package]] -name = "time-macros" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36" -dependencies = [ - "time-core", -] - [[package]] name = "tiny-keccak" version = "2.0.2" @@ -3512,9 +2768,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.28.0" +version = "1.28.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c786bf8134e5a3a166db9b29ab8f48134739014a3eca7bc6bfa95d673b136f" +checksum = "94d7b1cfd2aa4011f2de74c2c4c63665e27a71006b0a192dcd2710272e73dfa2" dependencies = [ "autocfg", "bytes", @@ -3525,7 +2781,7 @@ dependencies = [ "pin-project-lite", "socket2", "tokio-macros", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -3541,24 +2797,12 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.23.4" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ "rustls", "tokio", - "webpki", -] - -[[package]] -name = "tokio-stream" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", ] [[package]] @@ -3606,9 +2850,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" dependencies = [ "once_cell", ] @@ -3648,9 +2892,9 @@ checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" [[package]] name = "typify" -version = "0.0.11" +version = "0.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30bfde96849e25d7feef1bbf652e9cfc51deb63203fdc07b115b8bc3bcfe20b9" +checksum = "be9bb640c0eece20cac2028ebbc2ca1a3d17e3b1ddd98540309c309ed178d158" dependencies = [ "typify-impl", "typify-macro", @@ -3658,9 +2902,9 @@ dependencies = [ [[package]] name = "typify-impl" -version = "0.0.11" +version = "0.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95d27d749378ceab6ec22188ed7ad102205c89ddb92ab662371c850ffc71aa1a" +checksum = "5c8d9ecedde2fd77e975c38eeb9ca40b34ad0247b2259c6e6bbd2a8d6cc2444f" dependencies = [ "heck", "log", @@ -3669,16 +2913,16 @@ dependencies = [ "regress", "schemars", "serde_json", - "syn 1.0.109", + "syn 2.0.23", "thiserror", "unicode-ident", ] [[package]] name = "typify-macro" -version = "0.0.11" +version = "0.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35db6fc2bd9220ecdac6eeb88158824b83610de3dda0c6d0f2142b49efd858b0" +checksum = "c08942cd65d458d2da15777a649cb6400cb545f17964f1ca965583f22e9cc3a9" dependencies = [ "proc-macro2", "quote", @@ -3686,7 +2930,7 @@ dependencies = [ "serde", "serde_json", "serde_tokenstream", - "syn 1.0.109", + "syn 2.0.23", "typify-impl", ] @@ -3696,17 +2940,11 @@ version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" -[[package]] -name = "unicode-bom" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63ec69f541d875b783ca40184d655f2927c95f0bffd486faa83cd3ac3529ec32" - [[package]] name = "unicode-ident" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" +checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" [[package]] name = "unicode-normalization" @@ -3749,9 +2987,9 @@ checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" [[package]] name = "url" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" +checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" dependencies = [ "form_urlencoded", "idna", @@ -3760,14 +2998,20 @@ dependencies = [ [[package]] name = "uuid" -version = "1.3.2" +version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dad5567ad0cf5b760e5665964bec1b47dfd077ba8a2544b513f3556d3d239a2" +checksum = "0fa2982af2eec27de306107c027578ff7f423d65f7250e40ce0fea8f45248b81" dependencies = [ "getrandom", "serde", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.4" @@ -3794,12 +3038,6 @@ dependencies = [ "try-lock", ] -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" @@ -3808,9 +3046,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3818,24 +3056,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.23", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.34" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" dependencies = [ "cfg-if", "js-sys", @@ -3845,9 +3083,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3855,22 +3093,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.23", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" [[package]] name = "wasm-streams" @@ -3887,9 +3125,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.61" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33b99f4b23ba3eec1a53ac264e35a755f00e966e0065077d6027c0f575b0b97" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" dependencies = [ "js-sys", "wasm-bindgen", @@ -3956,37 +3194,13 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows" -version = "0.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets 0.48.0", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", + "windows-targets", ] [[package]] @@ -3995,22 +3209,7 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets 0.48.0", -] - -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", + "windows-targets", ] [[package]] @@ -4019,93 +3218,51 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - [[package]] name = "windows_x86_64_msvc" version = "0.48.0" @@ -4151,32 +3308,13 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "zstd" -version = "0.11.2+zstd.1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" -dependencies = [ - "zstd-safe 5.0.2+zstd.1.5.2", -] - [[package]] name = "zstd" version = "0.12.3+zstd.1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76eea132fb024e0e13fd9c2f5d5d595d8a967aa72382ac2f9d39fcc95afd0806" dependencies = [ - "zstd-safe 6.0.5+zstd.1.5.4", -] - -[[package]] -name = "zstd-safe" -version = "5.0.2+zstd.1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db" -dependencies = [ - "libc", - "zstd-sys", + "zstd-safe", ] [[package]] diff --git a/dask_planner/Cargo.toml b/Cargo.toml similarity index 53% rename from dask_planner/Cargo.toml rename to Cargo.toml index a3dce7aff..826a5df7f 100644 --- a/dask_planner/Cargo.toml +++ b/Cargo.toml @@ -1,23 +1,29 @@ [package] -name = "dask_planner" +name = "dask-sql" repository = "https://github.com/dask-contrib/dask-sql" -version = "0.1.0" +version = "2023.6.0" description = "Bindings for DataFusion used by Dask-SQL" readme = "README.md" license = "Apache-2.0" edition = "2021" rust-version = "1.65" +include = ["/src", "/dask_sql", "/LICENSE.txt", "pyproject.toml", "Cargo.toml", "Cargo.lock"] [dependencies] async-trait = "0.1.71" -datafusion-python = { git = "https://github.com/apache/arrow-datafusion-python.git", rev = "9493638" } +datafusion-python = "28.0.0" env_logger = "0.10" log = "^0.4" -pyo3 = { version = "0.18.3", features = ["extension-module", "abi3", "abi3-py38"] } +pyo3 = { version = "0.19.1", features = ["extension-module", "abi3", "abi3-py38"] } pyo3-log = "0.8.3" [build-dependencies] pyo3-build-config = "0.19.1" [lib] -crate-type = ["cdylib"] +name = "dask_sql" +crate-type = ["cdylib", "rlib"] + +[profile.release] +lto = true +codegen-units = 1 diff --git a/README.md b/README.md index e978fadf8..d08aa0328 100644 --- a/README.md +++ b/README.md @@ -110,10 +110,7 @@ After that, you can install the package in development mode pip install -e ".[dev]" The Rust DataFusion bindings are built as part of the `pip install`. -If changes are made to the Rust source in `dask_planner/`, another build/install must be run to recompile the bindings: - - python setup.py build install - +Note that if changes are made to the Rust source in `src/`, another build must be run to recompile the bindings. This repository uses [pre-commit](https://pre-commit.com/) hooks. To install them, call pre-commit install diff --git a/continuous_integration/environment-3.10-dev.yaml b/continuous_integration/environment-3.10-dev.yaml index 08af189eb..4589cc1b5 100644 --- a/continuous_integration/environment-3.10-dev.yaml +++ b/continuous_integration/environment-3.10-dev.yaml @@ -11,15 +11,17 @@ dependencies: - intake>=0.6.0 - jsonschema - lightgbm -- maturin>=0.12.8 -- mlflow +- maturin>=1.1,<1.2 +# FIXME: mlflow 2.6.0 has import issues related to pydantic +# https://github.com/mlflow/mlflow/issues/9331 +- mlflow<2.6 - mock - numpy>=1.21.6 - pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 -- pyarrow>=6.0.1 +- pyarrow>=6.0.2 - pygments>=2.7.1 - pyhive - pytest-cov @@ -28,10 +30,10 @@ dependencies: - pytest - python=3.10 - scikit-learn>=1.0.0 -- setuptools-rust>=1.5.2 - sphinx - sqlalchemy<2 - tpot>=0.12.0 - tzlocal>=2.1 - uvicorn>=0.13.4 - libprotobuf=3 +- zlib diff --git a/continuous_integration/environment-3.8-dev.yaml b/continuous_integration/environment-3.8-dev.yaml index 15abe79b5..5a9255390 100644 --- a/continuous_integration/environment-3.8-dev.yaml +++ b/continuous_integration/environment-3.8-dev.yaml @@ -11,15 +11,17 @@ dependencies: - intake=0.6.0 - jsonschema - lightgbm -- maturin=0.12.8 -- mlflow +- maturin=1.1 +# FIXME: mlflow 2.6.0 has import issues related to pydantic +# https://github.com/mlflow/mlflow/issues/9331 +- mlflow<2.6 - mock - numpy=1.21.6 - pandas=1.4.0 - pre-commit - prompt_toolkit=3.0.8 - psycopg2 -- pyarrow=6.0.1 +- pyarrow=6.0.2 - pygments=2.7.1 - pyhive - pytest-cov @@ -28,10 +30,10 @@ dependencies: - pytest - python=3.8 - scikit-learn=1.0.0 -- setuptools-rust=1.5.2 - sphinx - sqlalchemy<2 - tpot>=0.12.0 - tzlocal=2.1 - uvicorn=0.13.4 - libprotobuf=3 +- zlib diff --git a/continuous_integration/environment-3.9-dev.yaml b/continuous_integration/environment-3.9-dev.yaml index 47e64e8fc..f807d2e87 100644 --- a/continuous_integration/environment-3.9-dev.yaml +++ b/continuous_integration/environment-3.9-dev.yaml @@ -11,15 +11,17 @@ dependencies: - intake>=0.6.0 - jsonschema - lightgbm -- maturin>=0.12.8 -- mlflow +- maturin>=1.1,<1.2 +# FIXME: mlflow 2.6.0 has import issues related to pydantic +# https://github.com/mlflow/mlflow/issues/9331 +- mlflow<2.6 - mock - numpy>=1.21.6 - pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 -- pyarrow>=6.0.1 +- pyarrow>=6.0.2 - pygments>=2.7.1 - pyhive - pytest-cov @@ -28,10 +30,10 @@ dependencies: - pytest - python=3.9 - scikit-learn>=1.0.0 -- setuptools-rust>=1.5.2 - sphinx - sqlalchemy<2 - tpot>=0.12.0 - tzlocal>=2.1 - uvicorn>=0.13.4 - libprotobuf=3 +- zlib diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index d312844d3..6d8372da4 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -14,15 +14,17 @@ dependencies: - intake>=0.6.0 - jsonschema - lightgbm -- maturin>=0.12.8 -- mlflow +- maturin>=1.1,<1.2 +# FIXME: mlflow 2.6.0 has import issues related to pydantic +# https://github.com/mlflow/mlflow/issues/9331 +- mlflow<2.6 - mock - numpy>=1.21.6 - pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 -- pyarrow>=6.0.1 +- pyarrow>=6.0.2 - pygments>=2.7.1 - pyhive - pytest-cov @@ -31,7 +33,6 @@ dependencies: - pytest - python=3.10 - scikit-learn>=1.0.0 -- setuptools-rust>=1.5.2 - sphinx - sqlalchemy<2 - tpot>=0.12.0 @@ -45,4 +46,6 @@ dependencies: - dask-cuda=23.08 - ucx-proc=*=gpu - ucx-py=0.33 -- xgboost=*rapidsai23.08 +- xgboost=*=rapidsai_py* +- libxgboost=*=rapidsai_h* +- zlib diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index 565869411..52c82a1e2 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -14,15 +14,17 @@ dependencies: - intake>=0.6.0 - jsonschema - lightgbm -- maturin>=0.12.8 -- mlflow +- maturin>=1.1,<1.2 +# FIXME: mlflow 2.6.0 has import issues related to pydantic +# https://github.com/mlflow/mlflow/issues/9331 +- mlflow<2.6 - mock - numpy>=1.21.6 - pandas>=1.4.0 - pre-commit - prompt_toolkit>=3.0.8 - psycopg2 -- pyarrow>=6.0.1 +- pyarrow>=6.0.2 - pygments>=2.7.1 - pyhive - pytest-cov @@ -31,7 +33,6 @@ dependencies: - pytest - python=3.9 - scikit-learn>=1.0.0 -- setuptools-rust>=1.5.2 - sphinx - sqlalchemy<2 - tpot>=0.12.0 @@ -45,4 +46,6 @@ dependencies: - dask-cuda=23.08 - ucx-proc=*=gpu - ucx-py=0.33 -- xgboost=*rapidsai23.08 +- xgboost=*=rapidsai_py* +- libxgboost=*=rapidsai_h* +- zlib diff --git a/continuous_integration/recipe/conda_build_config.yaml b/continuous_integration/recipe/conda_build_config.yaml index b1c3c40cc..df3cde4e1 100644 --- a/continuous_integration/recipe/conda_build_config.yaml +++ b/continuous_integration/recipe/conda_build_config.yaml @@ -4,5 +4,5 @@ rust_compiler_version: - 1.69 libprotobuf: - 3 -setuptools_rust: - - 1.5.2 +maturin: + - 1.1 diff --git a/continuous_integration/recipe/meta.yaml b/continuous_integration/recipe/meta.yaml index 4314efed4..48cc8b748 100644 --- a/continuous_integration/recipe/meta.yaml +++ b/continuous_integration/recipe/meta.yaml @@ -24,14 +24,17 @@ requirements: build: - python # [build_platform != target_platform] - cross-python_{{ target_platform }} # [build_platform != target_platform] + - maturin # [build_platform != target_platform] - libprotobuf # [build_platform != target_platform] + - zlib # [build_platform != target_platform] - {{ compiler('c') }} - {{ compiler('rust') }} host: - pip - python - - setuptools-rust + - maturin - libprotobuf + - zlib - xz # [linux64] run: - python diff --git a/dask_planner/update-dependencies.sh b/continuous_integration/scripts/update-dependencies.sh similarity index 100% rename from dask_planner/update-dependencies.sh rename to continuous_integration/scripts/update-dependencies.sh diff --git a/dask_planner/.classpath b/dask_planner/.classpath deleted file mode 100644 index b14b13a76..000000000 --- a/dask_planner/.classpath +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dask_planner/.gitignore b/dask_planner/.gitignore deleted file mode 100644 index c8f044299..000000000 --- a/dask_planner/.gitignore +++ /dev/null @@ -1,72 +0,0 @@ -/target - -# Byte-compiled / optimized / DLL files -__pycache__/ -.pytest_cache/ -*.py[cod] - -# C extensions -*.so - -# Distribution / packaging -.Python -.venv/ -env/ -bin/ -build/ -develop-eggs/ -dist/ -eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -include/ -man/ -venv/ -*.egg-info/ -.installed.cfg -*.egg - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt -pip-selfcheck.json - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.cache -nosetests.xml -coverage.xml - -# Translations -*.mo - -# Mr Developer -.mr.developer.cfg -.project -.pydevproject - -# Rope -.ropeproject - -# Django stuff: -*.log -*.pot - -.DS_Store - -# Sphinx documentation -docs/_build/ - -# PyCharm -.idea/ - -# VSCode -.vscode/ - -# Pyenv -.python-version diff --git a/dask_planner/.settings/org.eclipse.core.resources.prefs b/dask_planner/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 92920805e..000000000 --- a/dask_planner/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/main/resources=UTF-8 -encoding//target/generated-sources/annotations=UTF-8 -encoding/=UTF-8 diff --git a/dask_planner/.settings/org.eclipse.jdt.apt.core.prefs b/dask_planner/.settings/org.eclipse.jdt.apt.core.prefs deleted file mode 100644 index d4313d4b2..000000000 --- a/dask_planner/.settings/org.eclipse.jdt.apt.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.apt.aptEnabled=false diff --git a/dask_planner/.settings/org.eclipse.jdt.core.prefs b/dask_planner/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 1b6e1ef22..000000000 --- a/dask_planner/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,9 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore -org.eclipse.jdt.core.compiler.processAnnotations=disabled -org.eclipse.jdt.core.compiler.release=disabled -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/dask_planner/.settings/org.eclipse.m2e.core.prefs b/dask_planner/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1c..000000000 --- a/dask_planner/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/dask_planner/MANIFEST.in b/dask_planner/MANIFEST.in deleted file mode 100644 index 7c68298bd..000000000 --- a/dask_planner/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -include Cargo.toml -recursive-include src * diff --git a/dask_planner/README.md b/dask_planner/README.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/dask_planner/pyproject.toml b/dask_planner/pyproject.toml deleted file mode 100644 index f153e3f5a..000000000 --- a/dask_planner/pyproject.toml +++ /dev/null @@ -1,11 +0,0 @@ -[build-system] -requires = ["setuptools", "wheel", "setuptools-rust"] - -[project] -name = "datafusion_planner" -requires-python = ">=3.8" -classifiers = [ - "Programming Language :: Rust", - "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", -] diff --git a/dask_sql/__init__.py b/dask_sql/__init__.py index d923876b8..fd8339b5a 100644 --- a/dask_sql/__init__.py +++ b/dask_sql/__init__.py @@ -1,6 +1,6 @@ # FIXME: can we modify TLS model of Rust object to avoid aarch64 glibc bug? # https://github.com/dask-contrib/dask-sql/issues/1169 -import dask_planner.rust +from . import _datafusion_lib # isort:skip from . import _version, config from .cmd import cmd_loop diff --git a/dask_sql/context.py b/dask_sql/context.py index 17c6d0055..ab0c2ae71 100644 --- a/dask_sql/context.py +++ b/dask_sql/context.py @@ -10,7 +10,7 @@ from dask.base import optimize from dask.utils_test import hlg_layer -from dask_planner.rust import ( +from dask_sql._datafusion_lib import ( DaskSchema, DaskSQLContext, DaskTable, @@ -42,7 +42,7 @@ from dask_sql.mappings import python_to_sql_type from dask_sql.physical.rel import RelConverter, custom, logical from dask_sql.physical.rex import RexConverter, core -from dask_sql.utils import OptimizationException, ParsingException +from dask_sql.utils import ParsingException logger = logging.getLogger(__name__) @@ -831,8 +831,9 @@ def _get_ral(self, sql): try: rel = self.context.optimize_relational_algebra(nonOptimizedRel) except DFOptimizationException as oe: + # Use original plan and warn about inability to optimize plan rel = nonOptimizedRel - raise OptimizationException(str(oe)) from None + logger.warn(str(oe)) else: rel = nonOptimizedRel diff --git a/dask_sql/input_utils/hive.py b/dask_sql/input_utils/hive.py index 4d0eb9cce..14bc547f0 100644 --- a/dask_sql/input_utils/hive.py +++ b/dask_sql/input_utils/hive.py @@ -6,7 +6,7 @@ import dask.dataframe as dd -from dask_planner.rust import SqlTypeName +from dask_sql._datafusion_lib import SqlTypeName try: from pyhive import hive diff --git a/dask_sql/mappings.py b/dask_sql/mappings.py index 9ba22f797..ca0e23691 100644 --- a/dask_sql/mappings.py +++ b/dask_sql/mappings.py @@ -8,7 +8,7 @@ import numpy as np import pandas as pd -from dask_planner.rust import DaskTypeMap, SqlTypeName +from dask_sql._datafusion_lib import DaskTypeMap, SqlTypeName logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/base.py b/dask_sql/physical/rel/base.py index a1f378197..5f70cde4e 100644 --- a/dask_sql/physical/rel/base.py +++ b/dask_sql/physical/rel/base.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan, RelDataType + from dask_sql._datafusion_lib import LogicalPlan, RelDataType logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/convert.py b/dask_sql/physical/rel/convert.py index 29ad8c327..6d2beceff 100644 --- a/dask_sql/physical/rel/convert.py +++ b/dask_sql/physical/rel/convert.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/alter.py b/dask_sql/physical/rel/custom/alter.py index 9c8a159b0..b29eb7737 100644 --- a/dask_sql/physical/rel/custom/alter.py +++ b/dask_sql/physical/rel/custom/alter.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class AlterSchemaPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/custom/analyze_table.py b/dask_sql/physical/rel/custom/analyze_table.py index 69f734a54..49308cf3a 100644 --- a/dask_sql/physical/rel/custom/analyze_table.py +++ b/dask_sql/physical/rel/custom/analyze_table.py @@ -9,7 +9,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class AnalyzeTablePlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/custom/create_catalog_schema.py b/dask_sql/physical/rel/custom/create_catalog_schema.py index 52ed37b55..e55d31a90 100644 --- a/dask_sql/physical/rel/custom/create_catalog_schema.py +++ b/dask_sql/physical/rel/custom/create_catalog_schema.py @@ -5,7 +5,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/create_memory_table.py b/dask_sql/physical/rel/custom/create_memory_table.py index 760857563..3c829fb42 100644 --- a/dask_sql/physical/rel/custom/create_memory_table.py +++ b/dask_sql/physical/rel/custom/create_memory_table.py @@ -6,7 +6,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/create_table.py b/dask_sql/physical/rel/custom/create_table.py index 36b165230..cbe61abf7 100644 --- a/dask_sql/physical/rel/custom/create_table.py +++ b/dask_sql/physical/rel/custom/create_table.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/describe_model.py b/dask_sql/physical/rel/custom/describe_model.py index d915a6b0b..422ac7c3b 100644 --- a/dask_sql/physical/rel/custom/describe_model.py +++ b/dask_sql/physical/rel/custom/describe_model.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class DescribeModelPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/custom/distributeby.py b/dask_sql/physical/rel/custom/distributeby.py index c7ce70610..71ac114f2 100644 --- a/dask_sql/physical/rel/custom/distributeby.py +++ b/dask_sql/physical/rel/custom/distributeby.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/drop_schema.py b/dask_sql/physical/rel/custom/drop_schema.py index 444662e2b..5491fcaa4 100644 --- a/dask_sql/physical/rel/custom/drop_schema.py +++ b/dask_sql/physical/rel/custom/drop_schema.py @@ -5,7 +5,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/export_model.py b/dask_sql/physical/rel/custom/export_model.py index 07cf9979e..08446c43c 100644 --- a/dask_sql/physical/rel/custom/export_model.py +++ b/dask_sql/physical/rel/custom/export_model.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/predict_model.py b/dask_sql/physical/rel/custom/predict_model.py index 917d712c3..0bb5c79b4 100644 --- a/dask_sql/physical/rel/custom/predict_model.py +++ b/dask_sql/physical/rel/custom/predict_model.py @@ -10,7 +10,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/custom/show_columns.py b/dask_sql/physical/rel/custom/show_columns.py index 6b0b94fe9..2da4f4535 100644 --- a/dask_sql/physical/rel/custom/show_columns.py +++ b/dask_sql/physical/rel/custom/show_columns.py @@ -9,7 +9,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class ShowColumnsPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/custom/show_models.py b/dask_sql/physical/rel/custom/show_models.py index 3f879dd38..28e495810 100644 --- a/dask_sql/physical/rel/custom/show_models.py +++ b/dask_sql/physical/rel/custom/show_models.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class ShowModelsPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/custom/show_schemas.py b/dask_sql/physical/rel/custom/show_schemas.py index 98b9f8ab3..fb69c5359 100644 --- a/dask_sql/physical/rel/custom/show_schemas.py +++ b/dask_sql/physical/rel/custom/show_schemas.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class ShowSchemasPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/custom/show_tables.py b/dask_sql/physical/rel/custom/show_tables.py index d79b4052b..05fb8a66c 100644 --- a/dask_sql/physical/rel/custom/show_tables.py +++ b/dask_sql/physical/rel/custom/show_tables.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class ShowTablesPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/custom/use_schema.py b/dask_sql/physical/rel/custom/use_schema.py index 889dd2b1c..f5fc65b7d 100644 --- a/dask_sql/physical/rel/custom/use_schema.py +++ b/dask_sql/physical/rel/custom/use_schema.py @@ -5,7 +5,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class UseSchemaPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/logical/aggregate.py b/dask_sql/physical/rel/logical/aggregate.py index 84c832177..dd2f9f41d 100644 --- a/dask_sql/physical/rel/logical/aggregate.py +++ b/dask_sql/physical/rel/logical/aggregate.py @@ -16,7 +16,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) @@ -127,6 +127,7 @@ class DaskAggregatePlugin(BaseRelPlugin): "avg": AggregationSpecification("mean", AggregationOnPandas("mean")), "stddev": AggregationSpecification("std", AggregationOnPandas("std")), "stddevsamp": AggregationSpecification("std", AggregationOnPandas("std")), + "stddev_samp": AggregationSpecification("std", AggregationOnPandas("std")), "stddevpop": AggregationSpecification( dd.Aggregation( "stddevpop", @@ -142,6 +143,21 @@ class DaskAggregatePlugin(BaseRelPlugin): ** (1 / 2), ) ), + "stddev_pop": AggregationSpecification( + dd.Aggregation( + "stddev_pop", + lambda s: (s.count(), s.sum(), s.agg(lambda x: (x**2).sum())), + lambda count, sum, sum_of_squares: ( + count.sum(), + sum.sum(), + sum_of_squares.sum(), + ), + lambda count, sum, sum_of_squares: ( + (sum_of_squares / count) - (sum / count) ** 2 + ) + ** (1 / 2), + ) + ), "bit_and": AggregationSpecification( ReduceAggregation("bit_and", operator.and_) ), @@ -198,6 +214,20 @@ class DaskAggregatePlugin(BaseRelPlugin): ), ) ), + "variance_pop": AggregationSpecification( + dd.Aggregation( + "variance_pop", + lambda s: (s.count(), s.sum(), s.agg(lambda x: (x**2).sum())), + lambda count, sum, sum_of_squares: ( + count.sum(), + sum.sum(), + sum_of_squares.sum(), + ), + lambda count, sum, sum_of_squares: ( + (sum_of_squares / count) - (sum / count) ** 2 + ), + ) + ), } def convert(self, rel: "LogicalPlan", context: "dask_sql.Context") -> DataContainer: diff --git a/dask_sql/physical/rel/logical/cross_join.py b/dask_sql/physical/rel/logical/cross_join.py index 5f32d3257..d1c74c8cc 100644 --- a/dask_sql/physical/rel/logical/cross_join.py +++ b/dask_sql/physical/rel/logical/cross_join.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/logical/empty.py b/dask_sql/physical/rel/logical/empty.py index 23f8d1cd3..453f63de5 100644 --- a/dask_sql/physical/rel/logical/empty.py +++ b/dask_sql/physical/rel/logical/empty.py @@ -9,7 +9,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/logical/explain.py b/dask_sql/physical/rel/logical/explain.py index 69d20fca3..0e4875d0c 100644 --- a/dask_sql/physical/rel/logical/explain.py +++ b/dask_sql/physical/rel/logical/explain.py @@ -4,7 +4,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class ExplainPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/logical/filter.py b/dask_sql/physical/rel/logical/filter.py index d3c3f5fd3..af3685a11 100644 --- a/dask_sql/physical/rel/logical/filter.py +++ b/dask_sql/physical/rel/logical/filter.py @@ -12,7 +12,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/logical/join.py b/dask_sql/physical/rel/logical/join.py index c1c904af6..1657d2bf4 100644 --- a/dask_sql/physical/rel/logical/join.py +++ b/dask_sql/physical/rel/logical/join.py @@ -18,7 +18,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/logical/limit.py b/dask_sql/physical/rel/logical/limit.py index 3e2fc6434..9bd2be562 100644 --- a/dask_sql/physical/rel/logical/limit.py +++ b/dask_sql/physical/rel/logical/limit.py @@ -12,7 +12,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class DaskLimitPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/logical/project.py b/dask_sql/physical/rel/logical/project.py index b990e21b4..0a7637f59 100644 --- a/dask_sql/physical/rel/logical/project.py +++ b/dask_sql/physical/rel/logical/project.py @@ -1,7 +1,7 @@ import logging from typing import TYPE_CHECKING -from dask_planner.rust import RexType +from dask_sql._datafusion_lib import RexType from dask_sql.datacontainer import DataContainer from dask_sql.physical.rel.base import BaseRelPlugin from dask_sql.physical.rex import RexConverter @@ -9,7 +9,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/logical/sort.py b/dask_sql/physical/rel/logical/sort.py index 2e1376d41..9dfccdc49 100644 --- a/dask_sql/physical/rel/logical/sort.py +++ b/dask_sql/physical/rel/logical/sort.py @@ -6,7 +6,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class DaskSortPlugin(BaseRelPlugin): diff --git a/dask_sql/physical/rel/logical/subquery_alias.py b/dask_sql/physical/rel/logical/subquery_alias.py index 2473167d7..14be8928f 100644 --- a/dask_sql/physical/rel/logical/subquery_alias.py +++ b/dask_sql/physical/rel/logical/subquery_alias.py @@ -5,7 +5,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan class SubqueryAlias(BaseRelPlugin): diff --git a/dask_sql/physical/rel/logical/table_scan.py b/dask_sql/physical/rel/logical/table_scan.py index b4025ec97..53e1d29be 100644 --- a/dask_sql/physical/rel/logical/table_scan.py +++ b/dask_sql/physical/rel/logical/table_scan.py @@ -12,7 +12,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rel/logical/union.py b/dask_sql/physical/rel/logical/union.py index 830f7f981..f31ced797 100644 --- a/dask_sql/physical/rel/logical/union.py +++ b/dask_sql/physical/rel/logical/union.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan def _extract_df(obj_cc, obj_df, output_field_names): diff --git a/dask_sql/physical/rel/logical/window.py b/dask_sql/physical/rel/logical/window.py index 331876c49..aba788bc3 100644 --- a/dask_sql/physical/rel/logical/window.py +++ b/dask_sql/physical/rel/logical/window.py @@ -17,7 +17,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import LogicalPlan + from dask_sql._datafusion_lib import LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rex/base.py b/dask_sql/physical/rex/base.py index 5724a4536..d74ad6309 100644 --- a/dask_sql/physical/rex/base.py +++ b/dask_sql/physical/rex/base.py @@ -7,7 +7,7 @@ from dask_sql.datacontainer import DataContainer if TYPE_CHECKING: - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rex/convert.py b/dask_sql/physical/rex/convert.py index 71431cbb4..1713e496d 100644 --- a/dask_sql/physical/rex/convert.py +++ b/dask_sql/physical/rex/convert.py @@ -9,7 +9,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rex/core/alias.py b/dask_sql/physical/rex/core/alias.py index 40c373766..7486bc9c5 100644 --- a/dask_sql/physical/rex/core/alias.py +++ b/dask_sql/physical/rex/core/alias.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan class RexAliasPlugin(BaseRexPlugin): diff --git a/dask_sql/physical/rex/core/call.py b/dask_sql/physical/rex/core/call.py index 85d083d78..8db8ca048 100644 --- a/dask_sql/physical/rex/core/call.py +++ b/dask_sql/physical/rex/core/call.py @@ -1,11 +1,13 @@ import logging import operator import re +import warnings from datetime import datetime from functools import partial, reduce from typing import TYPE_CHECKING, Any, Callable, Union import dask.array as da +import dask.config as dask_config import dask.dataframe as dd import numpy as np import pandas as pd @@ -14,14 +16,15 @@ from dask.highlevelgraph import HighLevelGraph from dask.utils import random_state_data -from dask_planner.rust import SqlTypeName from dask_sql._compat import DASK_CUDF_TODATETIME_SUPPORT, PANDAS_GT_200 +from dask_sql._datafusion_lib import SqlTypeName from dask_sql.datacontainer import DataContainer from dask_sql.mappings import ( cast_column_to_type, sql_to_python_type, sql_to_python_value, ) +from dask_sql.physical.rel import RelConverter from dask_sql.physical.rex import RexConverter from dask_sql.physical.rex.base import BaseRexPlugin from dask_sql.physical.rex.core.literal import SargPythonImplementation @@ -35,7 +38,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan logger = logging.getLogger(__name__) SeriesOrScalar = Union[dd.Series, Any] @@ -45,7 +48,11 @@ def as_timelike(op): if isinstance(op, np.int64): return np.timedelta64(op, "D") elif isinstance(op, str): - return np.datetime64(op) + try: + return np.datetime64(op) + except ValueError: + op = datetime.strptime(op, "%Y-%m-%d") + return np.datetime64(op.strftime("%Y-%m-%d")) elif pd.api.types.is_datetime64_dtype(op) or isinstance(op, np.timedelta64): return op else: @@ -61,6 +68,12 @@ class Operation: # True, if the operation should also get the REX needs_rex = False + # True, if the operation should also needs the Context, possible subquery Relation expansion + needs_context = False + + # True, if the operation needs the original relation algebra + needs_rel = False + @staticmethod def op_needs_dc(op): return hasattr(op, "needs_dc") and op.needs_dc @@ -69,6 +82,14 @@ def op_needs_dc(op): def op_needs_rex(op): return hasattr(op, "needs_rex") and op.needs_rex + @staticmethod + def op_needs_context(op): + return hasattr(op, "needs_context") and op.needs_context + + @staticmethod + def op_needs_rel(op): + return hasattr(op, "needs_rel") and op.needs_rel + def __init__(self, f: Callable): """Init with the given function""" self.f = f @@ -82,6 +103,8 @@ def of(self, op: "Operation") -> "Operation": new_op = Operation(lambda *x, **kwargs: self(op(*x, **kwargs))) new_op.needs_dc = Operation.op_needs_dc(op) new_op.needs_rex = Operation.op_needs_rex(op) + new_op.needs_context = Operation.op_needs_context(op) + new_op.needs_rel = Operation.op_needs_rel(op) return new_op @@ -987,6 +1010,39 @@ def inList(self, series: dd.Series, *operands, rex=None): return ~result if rex.isNegated() else result +class InSubqueryOperation(Operation): + """ + Returns a boolean of whether an expression is/isn't in a Subquery Expression result + """ + + needs_rex = True + needs_context = True + needs_rel = True + + def __init__(self): + super().__init__(self.inSubquery) + + def inSubquery( + self, series: dd.Series, *operands, rel=None, rex=None, context=None + ): + sub_rel = rex.getSubqueryLogicalPlan() + dc = RelConverter.convert(sub_rel, context=context) + + # Extract the specified column/Series from the Dataframe + fq_column_name = rex.column_name(rel).split(".") + + # FIXME: dask's isin doesn't support dask frames as arguments + # so we need to compute here + col = dc.df[fq_column_name[-1]].compute() + + warnings.warn( + "Dask doesn't support Dask frames as input for .isin, so we must force an early computation", + ResourceWarning, + ) + + return series.isin(col) + + class RexCallPlugin(BaseRexPlugin): """ RexCall is used for expressions, which calculate something. @@ -1036,6 +1092,7 @@ class RexCallPlugin(BaseRexPlugin): "negative": NegativeOperation(), "not": NotOperation(), "in list": InListOperation(), + "in subquery": InSubqueryOperation(), "is null": IsNullOperation(), "is not null": NotOperation().of(IsNullOperation()), "is true": IsTrueOperation(), @@ -1077,6 +1134,9 @@ class RexCallPlugin(BaseRexPlugin): "characterlength": TensorScalarOperation( lambda x: x.str.len(), lambda x: len(x) ), + "character_length": TensorScalarOperation( + lambda x: x.str.len(), lambda x: len(x) + ), "upper": TensorScalarOperation(lambda x: x.str.upper(), lambda x: x.upper()), "lower": TensorScalarOperation(lambda x: x.str.lower(), lambda x: x.lower()), "position": PositionOperation(), @@ -1104,6 +1164,7 @@ class RexCallPlugin(BaseRexPlugin): "dsql_totimestamp": ToTimestampOperation(), # Temporary UDF functions that need to be moved after this POC "datepart": ExtractOperation(), + "date_part": ExtractOperation(), "year": YearOperation(), "timestampadd": TimeStampAddOperation(), "timestampceil": CeilFloorOperation("ceil"), @@ -1125,6 +1186,21 @@ def convert( for o in expr.getOperands() ] + # FIXME: cuDF doesn't support binops between decimal columns and numpy ints / floats + if dask_config.get("sql.mappings.decimal_support") == "cudf" and any( + str(getattr(o, "dtype", None)) == "decimal128" for o in operands + ): + from decimal import Decimal + + operands = [ + Decimal(str(o)) + if isinstance(o, float) + else o.item() + if np.isscalar(o) and pd.api.types.is_integer_dtype(o) + else o + for o in operands + ] + # Now use the operator name in the mapping schema_name = context.schema_name operator_name = expr.getOperatorName().lower() @@ -1135,7 +1211,9 @@ def convert( try: operation = context.schema[schema_name].functions[operator_name] except KeyError: # pragma: no cover - raise NotImplementedError(f"{operator_name} not (yet) implemented") + raise NotImplementedError( + f"RexCall operator '{operator_name}' not (yet) implemented" + ) logger.debug( f"Executing {operator_name} on {[str(LoggableDataFrame(df)) for df in operands]}" @@ -1147,6 +1225,10 @@ def convert( kwargs["dc"] = dc if Operation.op_needs_rex(operation): kwargs["rex"] = expr + if Operation.op_needs_context(operation): + kwargs["context"] = context + if Operation.op_needs_rel(operation): + kwargs["rel"] = rel return operation(*operands, **kwargs) # TODO: We have information on the typing here - we should use it diff --git a/dask_sql/physical/rex/core/input_ref.py b/dask_sql/physical/rex/core/input_ref.py index 4272c832e..4d2c0f929 100644 --- a/dask_sql/physical/rex/core/input_ref.py +++ b/dask_sql/physical/rex/core/input_ref.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan class RexInputRefPlugin(BaseRexPlugin): diff --git a/dask_sql/physical/rex/core/literal.py b/dask_sql/physical/rex/core/literal.py index 73e3b8185..da0eeb128 100644 --- a/dask_sql/physical/rex/core/literal.py +++ b/dask_sql/physical/rex/core/literal.py @@ -5,14 +5,14 @@ import dask.dataframe as dd import numpy as np -from dask_planner.rust import SqlTypeName +from dask_sql._datafusion_lib import SqlTypeName from dask_sql.datacontainer import DataContainer from dask_sql.mappings import sql_to_python_value from dask_sql.physical.rex.base import BaseRexPlugin if TYPE_CHECKING: import dask_sql - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan logger = logging.getLogger(__name__) diff --git a/dask_sql/physical/rex/core/subquery.py b/dask_sql/physical/rex/core/subquery.py index 5e0a33098..60a07c0b9 100644 --- a/dask_sql/physical/rex/core/subquery.py +++ b/dask_sql/physical/rex/core/subquery.py @@ -8,7 +8,7 @@ if TYPE_CHECKING: import dask_sql - from dask_planner.rust import Expression, LogicalPlan + from dask_sql._datafusion_lib import Expression, LogicalPlan class RexScalarSubqueryPlugin(BaseRexPlugin): diff --git a/dask_sql/physical/utils/filter.py b/dask_sql/physical/utils/filter.py index f99934c07..ae564244d 100644 --- a/dask_sql/physical/utils/filter.py +++ b/dask_sql/physical/utils/filter.py @@ -127,6 +127,22 @@ def attempt_predicate_pushdown( return ddf filters = filters.to_list_tuple() + # FIXME: pyarrow doesn't seem to like converting datetime64[D] to scalars + # so we must convert any we encounter to datetime64[ns] + filters = [ + [ + ( + col, + op, + val.astype("datetime64[ns]") + if isinstance(val, np.datetime64) and val.dtype == "datetime64[D]" + else val, + ) + for col, op, val in sublist + ] + for sublist in filters + ] + # Regenerate collection with filtered IO layer try: _regen_cache = {} @@ -388,6 +404,7 @@ def _regenerate_collection( regen_kwargs = self.creation_info.get("kwargs", {}).copy() regen_kwargs = {k: v for k, v in self.creation_info.get("kwargs", {}).items()} regen_kwargs.update((new_kwargs or {}).get(self.layer.output, {})) + result = func(*inputs, *regen_args, **regen_kwargs) _regen_cache[self.layer.output] = result return result diff --git a/dask_sql/utils.py b/dask_sql/utils.py index 39c165597..454eecb7f 100644 --- a/dask_sql/utils.py +++ b/dask_sql/utils.py @@ -9,7 +9,7 @@ import numpy as np import pandas as pd -from dask_planner.rust import SqlTypeName +from dask_sql._datafusion_lib import SqlTypeName from dask_sql.datacontainer import DataContainer from dask_sql.mappings import sql_to_python_value diff --git a/docker/conda.txt b/docker/conda.txt index 83b176843..5083ebd85 100644 --- a/docker/conda.txt +++ b/docker/conda.txt @@ -4,7 +4,7 @@ pandas>=1.4.0 jpype1>=1.0.2 openjdk>=8 maven>=3.6.0 -pytest>=6.0.1 +pytest>=6.0.2 pytest-cov>=2.10.1 pytest-xdist mock>=4.0.3 @@ -13,7 +13,7 @@ tzlocal>=2.1 fastapi>=0.92.0 httpx>=0.24.1 uvicorn>=0.13.4 -pyarrow>=6.0.1 +pyarrow>=6.0.2 prompt_toolkit>=3.0.8 pygments>=2.7.1 scikit-learn>=1.0.0 @@ -21,4 +21,4 @@ intake>=0.6.0 pre-commit>=2.11.1 black=22.10.0 isort=5.12.0 -setuptools-rust>=1.5.2 +maturin>=1.1,<1.2 diff --git a/docker/main.dockerfile b/docker/main.dockerfile index c3dbbf8d2..5b56bb879 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -14,7 +14,7 @@ ENV PATH="/root/.cargo/bin:${PATH}" COPY docker/conda.txt /opt/dask_sql/ RUN mamba install -y \ # build requirements - "setuptools-rust>=1.5.2" \ + "maturin>=1.1,<1.2" \ # core dependencies "dask>=2022.3.0" \ "pandas>=1.4.0" \ @@ -26,17 +26,21 @@ RUN mamba install -y \ "pygments>=2.7.1" \ tabulate \ # additional dependencies - "pyarrow>=6.0.1" \ + "pyarrow>=6.0.2" \ "scikit-learn>=1.0.0" \ "intake>=0.6.0" \ && conda clean -ay # install dask-sql +COPY Cargo.toml /opt/dask_sql/ +COPY Cargo.lock /opt/dask_sql/ +COPY pyproject.toml /opt/dask_sql/ COPY setup.py /opt/dask_sql/ COPY setup.cfg /opt/dask_sql/ COPY versioneer.py /opt/dask_sql/ +COPY README.md /opt/dask_sql/ COPY .git /opt/dask_sql/.git -COPY dask_planner /opt/dask_sql/dask_planner +COPY src /opt/dask_sql/src COPY dask_sql /opt/dask_sql/dask_sql RUN cd /opt/dask_sql/ \ && pip install -e . -vv diff --git a/docs/environment.yml b/docs/environment.yml index e9366eaa4..ca9b23a34 100644 --- a/docs/environment.yml +++ b/docs/environment.yml @@ -17,6 +17,5 @@ dependencies: - prompt_toolkit>=3.0.8 - pygments>=2.7.1 - tabulate - - setuptools-rust>=1.5.2 - ucx-proc=*=cpu - rust>=1.65.0 diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt index c039df54a..cce9cb599 100644 --- a/docs/requirements-docs.txt +++ b/docs/requirements-docs.txt @@ -11,4 +11,4 @@ tzlocal>=2.1 prompt_toolkit>=3.0.8 pygments>=2.7.1 tabulate -setuptools-rust>=1.5.2 +maturin>=1.1,<1.2 diff --git a/docs/source/how_does_it_work.rst b/docs/source/how_does_it_work.rst index 32c736431..67d2eab01 100644 --- a/docs/source/how_does_it_work.rst +++ b/docs/source/how_does_it_work.rst @@ -22,7 +22,7 @@ No matter of via the Python API (:ref:`api`), the command line client (:ref:`cmd This function will first give the SQL string to the dask_planner Rust crate via the ``PyO3`` library. Inside this crate, Apache Arrow DataFusion is used to first parse the SQL string and then turn it into a relational algebra. For this, DataFusion uses the SQL language description specified in the `sqlparser-rs library `_ -We also include `SQL extensions specific to Dask-SQL `_. They specify custom language features, such as the ``CREATE MODEL`` statement. +We also include `SQL extensions specific to Dask-SQL `_. They specify custom language features, such as the ``CREATE MODEL`` statement. 3. SQL is (maybe) optimized --------------------------- diff --git a/docs/source/installation.rst b/docs/source/installation.rst index 71ce17959..a2a3ee895 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -84,12 +84,7 @@ After that, you can install the package in development mode pip install -e ".[dev]" -To compile the Rust code (after changes), run - -.. code-block:: bash - - python setup.py build_ext - +To compile the Rust code (after changes), the above command must be rerun. You can run the tests (after installation) with .. code-block:: bash diff --git a/pyproject.toml b/pyproject.toml index dfed2ba50..3caa92ddb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,86 @@ [build-system] -requires = ["setuptools", "wheel", "setuptools-rust"] +requires = ["maturin>=1.1,<1.2"] +build-backend = "maturin" -[tool.isort] -profile = "black" +[project] +name = "dask_sql" +description = "SQL query layer for Dask" +maintainers = [{name = "Nils Braun", email = "nilslennartbraun@gmail.com"}] +license = {text = "MIT"} +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Rust", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Topic :: Scientific/Engineering", + "Topic :: System :: Distributed Computing", +] +readme = "README.md" +requires-python = ">=3.8" +dependencies = [ + "dask[dataframe]>=2022.3.0", + "distributed>=2022.3.0", + "pandas>=1.4.0", + "fastapi>=0.92.0", + "httpx>=0.24.1", + "uvicorn>=0.13.4", + "tzlocal>=2.1", + "prompt_toolkit>=3.0.8", + "pygments>=2.7.1", + "tabulate", +] +dynamic = ["version"] + +[project.urls] +Homepage = "https://github.com/dask-contrib/dask-sql" +Documentation = "https://dask-sql.readthedocs.io" +Source = "https://github.com/dask-contrib/dask-sql" + +[project.optional-dependencies] +dev = [ + "pytest>=6.0.1", + "pytest-cov>=2.10.1", + "mock>=4.0.3", + "sphinx>=3.2.1", + "pyarrow>=6.0.2", + "scikit-learn>=1.0.0", + "intake>=0.6.0", + "pre-commit", + "black==22.10.0", + "isort==5.12.0", +] +fugue = ["fugue>=0.7.3"] + +[project.entry-points."fugue.plugins"] +dasksql = "dask_sql.integrations.fugue:_register_engines[fugue]" + +[project.scripts] +dask-sql = "dask_sql.cmd:main" +dask-sql-server = "dask_sql.server.app:main" + +[tool.setuptools] +include-package-data = true +zip-safe = false +license-files = ["LICENSE.txt"] + +[tool.setuptools.packages] +find = {namespaces = false} [tool.maturin] +module-name = "dask_sql._datafusion_lib" include = [ { path = "Cargo.lock", format = "sdist" } ] -exclude = [".github/**", "ci/**", ".asf.yaml"] -# Require Cargo.lock is up to date +exclude = [".github/**", "continuous_integration/**"] locked = true + +[tool.isort] +profile = "black" diff --git a/setup.py b/setup.py index 387c93125..fcbb31faf 100644 --- a/setup.py +++ b/setup.py @@ -1,87 +1,8 @@ -import os -import sys - -from setuptools import find_packages, setup -from setuptools_rust import Binding, RustExtension +from setuptools import setup import versioneer -long_description = "" -if os.path.exists("README.md"): - with open("README.md") as f: - long_description = f.read() - -needs_sphinx = "build_sphinx" in sys.argv -sphinx_requirements = ["sphinx>=3.2.1", "sphinx_rtd_theme"] if needs_sphinx else [] -debug_build = "debug" in sys.argv - -cmdclass = versioneer.get_cmdclass() - setup( - name="dask_sql", version=versioneer.get_version(), - description="SQL query layer for Dask", - url="https://github.com/dask-contrib/dask-sql/", - maintainer="Nils Braun", - maintainer_email="nilslennartbraun@gmail.com", - license="MIT", - long_description=long_description, - long_description_content_type="text/markdown", - packages=find_packages( - include=["dask_sql", "dask_sql.*", "dask_planner", "dask_planner.*"] - ), - package_data={"dask_sql": ["sql*.yaml"]}, - rust_extensions=[ - RustExtension( - "dask_planner.rust", - binding=Binding.PyO3, - path="dask_planner/Cargo.toml", - debug=debug_build, - ) - ], - python_requires=">=3.8", - setup_requires=sphinx_requirements, - install_requires=[ - "dask[dataframe]>=2022.3.0", - "distributed>=2022.3.0", - "pandas>=1.4.0", - "fastapi>=0.92.0", - "httpx>=0.24.1", - "uvicorn>=0.13.4", - "tzlocal>=2.1", - "prompt_toolkit>=3.0.8", - "pygments>=2.7.1", - "tabulate", - ], - extras_require={ - "dev": [ - "pytest>=6.0.1", - "pytest-cov>=2.10.1", - "mock>=4.0.3", - "sphinx>=3.2.1", - "pyarrow>=6.0.1", - "scikit-learn>=1.0.0", - "intake>=0.6.0", - "pre-commit", - "black==22.10.0", - "isort==5.12.0", - ], - "fugue": ["fugue>=0.7.3"], - }, - entry_points={ - "console_scripts": [ - "dask-sql-server = dask_sql.server.app:main", - "dask-sql = dask_sql.cmd:main", - ], - "fugue.plugins": [ - "dasksql = dask_sql.integrations.fugue:_register_engines[fugue]" - ], - }, - zip_safe=False, - cmdclass=cmdclass, - command_options={ - "build_sphinx": { - "source_dir": ("setup.py", "docs"), - } - }, + cmdclass=versioneer.get_cmdclass(), ) diff --git a/dask_planner/src/dialect.rs b/src/dialect.rs similarity index 97% rename from dask_planner/src/dialect.rs rename to src/dialect.rs index 24f507dec..da4e213e1 100644 --- a/dask_planner/src/dialect.rs +++ b/src/dialect.rs @@ -77,6 +77,7 @@ impl Dialect for DaskDialect { over: None, distinct: false, special: false, + order_by: vec![], }))) } Token::Word(w) if w.value.to_lowercase() == "floor" => { @@ -108,6 +109,7 @@ impl Dialect for DaskDialect { over: None, distinct: false, special: false, + order_by: vec![], }))) } Token::Word(w) if w.value.to_lowercase() == "timestampadd" => { @@ -136,6 +138,7 @@ impl Dialect for DaskDialect { over: None, distinct: false, special: false, + order_by: vec![], }))) } Token::Word(w) if w.value.to_lowercase() == "timestampdiff" => { @@ -163,6 +166,7 @@ impl Dialect for DaskDialect { over: None, distinct: false, special: false, + order_by: vec![], }))) } Token::Word(w) if w.value.to_lowercase() == "to_timestamp" => { @@ -192,6 +196,7 @@ impl Dialect for DaskDialect { over: None, distinct: false, special: false, + order_by: vec![], }))) } Token::Word(w) if w.value.to_lowercase() == "extract" => { @@ -221,6 +226,7 @@ impl Dialect for DaskDialect { over: None, distinct: false, special: false, + order_by: vec![], }))) } _ => Ok(None), diff --git a/dask_planner/src/error.rs b/src/error.rs similarity index 100% rename from dask_planner/src/error.rs rename to src/error.rs diff --git a/dask_planner/src/expression.rs b/src/expression.rs similarity index 82% rename from dask_planner/src/expression.rs rename to src/expression.rs index aa1a60a9b..fccfa9d87 100644 --- a/dask_planner/src/expression.rs +++ b/src/expression.rs @@ -4,7 +4,21 @@ use datafusion_python::{ datafusion::arrow::datatypes::DataType, datafusion_common::{Column, DFField, DFSchema, ScalarValue}, datafusion_expr::{ - expr::{AggregateFunction, BinaryExpr, Cast, Sort, TryCast, WindowFunction}, + expr::{ + AggregateFunction, + AggregateUDF, + Alias, + BinaryExpr, + Cast, + Exists, + InList, + InSubquery, + ScalarFunction, + ScalarUDF, + Sort, + TryCast, + WindowFunction, + }, lit, utils::exprlist_to_fields, Between, @@ -30,7 +44,7 @@ use crate::{ }; /// An PyExpr that can be used on a DataFrame -#[pyclass(name = "Expression", module = "datafusion", subclass)] +#[pyclass(name = "Expression", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct PyExpr { pub expr: Expr, @@ -44,7 +58,7 @@ impl From for Expr { } } -#[pyclass(name = "ScalarValue", module = "datafusion", subclass)] +#[pyclass(name = "ScalarValue", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct PyScalarValue { pub scalar_value: ScalarValue, @@ -91,9 +105,10 @@ impl PyExpr { fn _rex_type(&self, expr: &Expr) -> RexType { match expr { Expr::Alias(..) => RexType::Alias, - Expr::Column(..) | Expr::QualifiedWildcard { .. } | Expr::GetIndexedField { .. } => { - RexType::Reference - } + Expr::Column(..) + | Expr::QualifiedWildcard { .. } + | Expr::GetIndexedField { .. } + | Expr::Wildcard => RexType::Reference, Expr::ScalarVariable(..) | Expr::Literal(..) => RexType::Literal, Expr::BinaryExpr { .. } | Expr::Not(..) @@ -101,7 +116,6 @@ impl PyExpr { | Expr::Negative(..) | Expr::IsNull(..) | Expr::Like { .. } - | Expr::ILike { .. } | Expr::SimilarTo { .. } | Expr::Between { .. } | Expr::Case { .. } @@ -113,7 +127,6 @@ impl PyExpr { | Expr::WindowFunction { .. } | Expr::AggregateUDF { .. } | Expr::InList { .. } - | Expr::Wildcard | Expr::ScalarUDF { .. } | Expr::Exists { .. } | Expr::InSubquery { .. } @@ -153,6 +166,9 @@ impl PyExpr { pub fn subquery_plan(&self) -> PyResult { match &self.expr { Expr::ScalarSubquery(subquery) => Ok(subquery.subquery.as_ref().clone().into()), + Expr::InSubquery(insubquery) => { + Ok(insubquery.subquery.subquery.as_ref().clone().into()) + } _ => Err(py_type_err(format!( "Attempted to extract a LogicalPlan instance from invalid Expr {:?}. Only Subquery and related variants are supported for this operation.", @@ -184,49 +200,61 @@ impl PyExpr { schema.merge(plan.schema().as_ref()); } let name = get_expr_name(&self.expr).map_err(py_runtime_err)?; - schema - .index_of_column(&Column::from_qualified_name(name.clone())) - .or_else(|_| { - // Handles cases when from_qualified_name doesn't format the Column correctly. - // "name" will always contain the name of the column. Anything in addition to - // that will be separated by a '.' and should be further referenced. - let parts = name.split('.').collect::>(); - let tbl_reference = match parts.len() { - // Single element means name contains just the column name so no TableReference - 1 => None, - // Tablename.column_name - 2 => Some( - TableReference::Bare { - table: Cow::Borrowed(parts[0]), - } - .to_owned_reference(), - ), - // Schema_name.table_name.column_name - 3 => Some( - TableReference::Partial { - schema: Cow::Borrowed(parts[0]), - table: Cow::Borrowed(parts[1]), + if name != "*" { + schema + .index_of_column(&Column::from_qualified_name(name.clone())) + .or_else(|_| { + // Handles cases when from_qualified_name doesn't format the Column correctly. + // "name" will always contain the name of the column. Anything in addition to + // that will be separated by a '.' and should be further referenced. + match &self.expr { + Expr::Column(col) => { + schema.index_of_column(col).map_err(py_runtime_err) } - .to_owned_reference(), - ), - // catalog_name.schema_name.table_name.column_name - 4 => Some( - TableReference::Full { - catalog: Cow::Borrowed(parts[0]), - schema: Cow::Borrowed(parts[1]), - table: Cow::Borrowed(parts[2]), + _ => { + let parts = name.split('.').collect::>(); + let tbl_reference = match parts.len() { + // Single element means name contains just the column name so no TableReference + 1 => None, + // Tablename.column_name + 2 => Some( + TableReference::Bare { + table: Cow::Borrowed(parts[0]), + } + .to_owned_reference(), + ), + // Schema_name.table_name.column_name + 3 => Some( + TableReference::Partial { + schema: Cow::Borrowed(parts[0]), + table: Cow::Borrowed(parts[1]), + } + .to_owned_reference(), + ), + // catalog_name.schema_name.table_name.column_name + 4 => Some( + TableReference::Full { + catalog: Cow::Borrowed(parts[0]), + schema: Cow::Borrowed(parts[1]), + table: Cow::Borrowed(parts[2]), + } + .to_owned_reference(), + ), + _ => None, + }; + + let col = Column { + relation: tbl_reference.clone(), + name: parts[parts.len() - 1].to_string(), + }; + schema.index_of_column(&col).map_err(py_runtime_err) } - .to_owned_reference(), - ), - _ => None, - }; - - let col = Column { - relation: tbl_reference.clone(), - name: parts[parts.len() - 1].to_string(), - }; - schema.index_of_column(&col).map_err(py_runtime_err) - }) + } + }) + } else { + // Since this is wildcard any Column will do, just use first one + Ok(0) + } } _ => Err(py_runtime_err( "We need a valid LogicalPlan instance to get the Expr's index in the schema", @@ -271,7 +299,6 @@ impl PyExpr { | Expr::IsNotTrue(_) | Expr::IsNotFalse(_) | Expr::Like { .. } - | Expr::ILike { .. } | Expr::SimilarTo { .. } | Expr::IsNotUnknown(_) | Expr::Case { .. } @@ -315,8 +342,7 @@ impl PyExpr { } // Expr(s) that house the Expr instance to return in their bounded params - Expr::Alias(expr, ..) - | Expr::Not(expr) + Expr::Not(expr) | Expr::IsNull(expr) | Expr::IsNotNull(expr) | Expr::IsTrue(expr) @@ -330,15 +356,15 @@ impl PyExpr { | Expr::Cast(Cast { expr, .. }) | Expr::TryCast(TryCast { expr, .. }) | Expr::Sort(Sort { expr, .. }) - | Expr::InSubquery { expr, .. } => { + | Expr::InSubquery(InSubquery { expr, .. }) => { Ok(vec![PyExpr::from(*expr.clone(), self.input_plan.clone())]) } // Expr variants containing a collection of Expr(s) for operands Expr::AggregateFunction(AggregateFunction { args, .. }) - | Expr::AggregateUDF { args, .. } - | Expr::ScalarFunction { args, .. } - | Expr::ScalarUDF { args, .. } + | Expr::AggregateUDF(AggregateUDF { args, .. }) + | Expr::ScalarFunction(ScalarFunction { args, .. }) + | Expr::ScalarUDF(ScalarUDF { args, .. }) | Expr::WindowFunction(WindowFunction { args, .. }) => Ok(args .iter() .map(|arg| PyExpr::from(arg.clone(), self.input_plan.clone())) @@ -377,7 +403,10 @@ impl PyExpr { Ok(operands) } - Expr::InList { expr, list, .. } => { + Expr::Alias(Alias { expr, .. }) => { + Ok(vec![PyExpr::from(*expr.clone(), self.input_plan.clone())]) + } + Expr::InList(InList { expr, list, .. }) => { let mut operands: Vec = vec![PyExpr::from(*expr.clone(), self.input_plan.clone())]; for list_elem in list { @@ -394,10 +423,6 @@ impl PyExpr { PyExpr::from(*expr.clone(), self.input_plan.clone()), PyExpr::from(*pattern.clone(), self.input_plan.clone()), ]), - Expr::ILike(Like { expr, pattern, .. }) => Ok(vec![ - PyExpr::from(*expr.clone(), self.input_plan.clone()), - PyExpr::from(*pattern.clone(), self.input_plan.clone()), - ]), Expr::SimilarTo(Like { expr, pattern, .. }) => Ok(vec![ PyExpr::from(*expr.clone(), self.input_plan.clone()), PyExpr::from(*pattern.clone(), self.input_plan.clone()), @@ -412,11 +437,14 @@ impl PyExpr { PyExpr::from(*low.clone(), self.input_plan.clone()), PyExpr::from(*high.clone(), self.input_plan.clone()), ]), + Expr::Wildcard => Ok(vec![PyExpr::from( + self.expr.clone(), + self.input_plan.clone(), + )]), // Currently un-support/implemented Expr types for Rex Call operations Expr::GroupingSet(..) | Expr::OuterReferenceColumn(_, _) - | Expr::Wildcard | Expr::QualifiedWildcard { .. } | Expr::ScalarSubquery(..) | Expr::Placeholder { .. } @@ -435,8 +463,8 @@ impl PyExpr { op, right: _, }) => format!("{op}"), - Expr::ScalarFunction { fun, args: _ } => format!("{fun}"), - Expr::ScalarUDF { fun, .. } => fun.name.clone(), + Expr::ScalarFunction(ScalarFunction { fun, args: _ }) => format!("{fun}"), + Expr::ScalarUDF(ScalarUDF { fun, .. }) => fun.name.clone(), Expr::Cast { .. } => "cast".to_string(), Expr::Between { .. } => "between".to_string(), Expr::Case { .. } => "case".to_string(), @@ -449,21 +477,19 @@ impl PyExpr { Expr::IsNotFalse(_) => "is not false".to_string(), Expr::IsNotUnknown(_) => "is not unknown".to_string(), Expr::InList { .. } => "in list".to_string(), + Expr::InSubquery(..) => "in subquery".to_string(), Expr::Negative(..) => "negative".to_string(), Expr::Not(..) => "not".to_string(), - Expr::Like(Like { negated, .. }) => { - if *negated { - "not like".to_string() - } else { - "like".to_string() - } - } - Expr::ILike(Like { negated, .. }) => { - if *negated { - "not ilike".to_string() - } else { - "ilike".to_string() - } + Expr::Like(Like { + negated, + case_insensitive, + .. + }) => { + format!( + "{}{}like", + if *negated { "not " } else { "" }, + if *case_insensitive { "i" } else { "" } + ) } Expr::SimilarTo(Like { negated, .. }) => { if *negated { @@ -556,8 +582,13 @@ impl PyExpr { ScalarValue::List(..) => "List", ScalarValue::Struct(..) => "Struct", ScalarValue::FixedSizeBinary(_, _) => "FixedSizeBinary", + ScalarValue::Fixedsizelist(..) => "Fixedsizelist", + ScalarValue::DurationSecond(..) => "DurationSecond", + ScalarValue::DurationMillisecond(..) => "DurationMillisecond", + ScalarValue::DurationMicrosecond(..) => "DurationMicrosecond", + ScalarValue::DurationNanosecond(..) => "DurationNanosecond", }, - Expr::ScalarFunction { fun, args: _ } => match fun { + Expr::ScalarFunction(ScalarFunction { fun, args: _ }) => match fun { BuiltinScalarFunction::Abs => "Abs", BuiltinScalarFunction::DatePart => "DatePart", _ => { @@ -637,9 +668,9 @@ impl PyExpr { pub fn get_filter_expr(&self) -> PyResult> { // TODO refactor to avoid duplication match &self.expr { - Expr::Alias(expr, _) => match expr.as_ref() { + Expr::Alias(Alias { expr, .. }) => match expr.as_ref() { Expr::AggregateFunction(AggregateFunction { filter, .. }) - | Expr::AggregateUDF { filter, .. } => match filter { + | Expr::AggregateUDF(AggregateUDF { filter, .. }) => match filter { Some(filter) => { Ok(Some(PyExpr::from(*filter.clone(), self.input_plan.clone()))) } @@ -650,7 +681,7 @@ impl PyExpr { )), }, Expr::AggregateFunction(AggregateFunction { filter, .. }) - | Expr::AggregateUDF { filter, .. } => match filter { + | Expr::AggregateUDF(AggregateUDF { filter, .. }) => match filter { Some(filter) => Ok(Some(PyExpr::from(*filter.clone(), self.input_plan.clone()))), None => Ok(None), }, @@ -739,7 +770,10 @@ impl PyExpr { ScalarValue::TimestampNanosecond(iv, tz) | ScalarValue::TimestampMicrosecond(iv, tz) | ScalarValue::TimestampMillisecond(iv, tz) - | ScalarValue::TimestampSecond(iv, tz) => Ok((*iv, tz.clone())), + | ScalarValue::TimestampSecond(iv, tz) => match tz { + Some(time_zone) => Ok((*iv, Some(time_zone.to_string()))), + None => Ok((*iv, None)), + }, other => Err(unexpected_literal_value(other)), } } @@ -790,9 +824,9 @@ impl PyExpr { pub fn is_negated(&self) -> PyResult { match &self.expr { Expr::Between(Between { negated, .. }) - | Expr::Exists { negated, .. } - | Expr::InList { negated, .. } - | Expr::InSubquery { negated, .. } => Ok(*negated), + | Expr::Exists(Exists { negated, .. }) + | Expr::InList(InList { negated, .. }) + | Expr::InSubquery(InSubquery { negated, .. }) => Ok(*negated), _ => Err(py_type_err(format!( "unknown Expr type {:?} encountered", &self.expr @@ -806,7 +840,7 @@ impl PyExpr { match &self.expr { Expr::AggregateFunction(funct) => Ok(funct.distinct), Expr::AggregateUDF { .. } => Ok(false), - Expr::Alias(expr, _) => match expr.as_ref() { + Expr::Alias(Alias { expr, .. }) => match expr.as_ref() { Expr::AggregateFunction(funct) => Ok(funct.distinct), Expr::AggregateUDF { .. } => Ok(false), _ => Err(py_type_err( @@ -847,9 +881,9 @@ impl PyExpr { #[pyo3(name = "getEscapeChar")] pub fn get_escape_char(&self) -> PyResult> { match &self.expr { - Expr::Like(Like { escape_char, .. }) - | Expr::ILike(Like { escape_char, .. }) - | Expr::SimilarTo(Like { escape_char, .. }) => Ok(*escape_char), + Expr::Like(Like { escape_char, .. }) | Expr::SimilarTo(Like { escape_char, .. }) => { + Ok(*escape_char) + } _ => Err(py_type_err(format!( "Provided Expr {:?} not one of Like/ILike/SimilarTo", &self.expr @@ -877,7 +911,11 @@ fn unexpected_literal_value(value: &ScalarValue) -> PyErr { fn get_expr_name(expr: &Expr) -> Result { match expr { - Expr::Alias(expr, _) => get_expr_name(expr), + Expr::Alias(Alias { expr, .. }) => get_expr_name(expr), + Expr::Wildcard => { + // 'Wildcard' means any and all columns. We get the first valid column name here + Ok("*".to_owned()) + } _ => Ok(expr.canonical_name()), } } @@ -890,6 +928,11 @@ pub fn expr_to_field(expr: &Expr, input_plan: &LogicalPlan) -> Result { // appear in projections) so we just delegate to the contained expression instead expr_to_field(expr, input_plan) } + Expr::Wildcard => { + // Any column will do. We use the first column to keep things consistent + Ok(input_plan.schema().field(0).clone()) + } + Expr::InSubquery(insubquery) => expr_to_field(&insubquery.expr, input_plan), _ => { let fields = exprlist_to_fields(&[expr.clone()], input_plan).map_err(DaskPlannerError::from)?; diff --git a/dask_planner/src/lib.rs b/src/lib.rs similarity index 90% rename from dask_planner/src/lib.rs rename to src/lib.rs index f5305d900..921478973 100644 --- a/dask_planner/src/lib.rs +++ b/src/lib.rs @@ -12,8 +12,7 @@ mod sql; /// The higher-level public API is defined in pure python files under the /// dask_planner directory. #[pymodule] -#[pyo3(name = "rust")] -fn rust(py: Python, m: &PyModule) -> PyResult<()> { +fn _datafusion_lib(py: Python, m: &PyModule) -> PyResult<()> { // Initialize the global Python logger instance pyo3_log::init(); @@ -41,7 +40,7 @@ fn rust(py: Python, m: &PyModule) -> PyResult<()> { py.get_type::(), )?; - debug!("dask_planner Python module loaded"); + debug!("dask_sql native library loaded"); Ok(()) } diff --git a/dask_planner/src/parser.rs b/src/parser.rs similarity index 95% rename from dask_planner/src/parser.rs rename to src/parser.rs index 3147e6309..100f9c137 100644 --- a/dask_planner/src/parser.rs +++ b/src/parser.rs @@ -30,7 +30,7 @@ pub enum CustomExpr { Nested(Vec<(String, PySqlArg)>), } -#[pyclass(name = "SqlArg", module = "datafusion")] +#[pyclass(name = "SqlArg", module = "dask_sql")] #[derive(Debug, Clone, PartialEq, Eq)] pub struct PySqlArg { expr: Option, @@ -1374,14 +1374,7 @@ mod test { let statements = DaskParser::parse_sql(sql).unwrap(); assert_eq!(1, statements.len()); let actual = format!("{:?}", statements[0]); - let expected = "projection: [\ - UnnamedExpr(Function(Function { name: ObjectName([Ident { value: \"timestampadd\", quote_style: None }]), \ - args: [\ - Unnamed(Expr(Value(SingleQuotedString(\"YEAR\")))), \ - Unnamed(Expr(Value(Number(\"2\", false)))), \ - Unnamed(Expr(Identifier(Ident { value: \"d\", quote_style: None })))\ - ], over: None, distinct: false, special: false }))\ - ]"; + let expected = "Statement(Query(Query { with: None, body: Select(Select { distinct: None, top: None, projection: [UnnamedExpr(Function(Function { name: ObjectName([Ident { value: \"timestampadd\", quote_style: None }]), args: [Unnamed(Expr(Value(SingleQuotedString(\"YEAR\")))), Unnamed(Expr(Value(Number(\"2\", false)))), Unnamed(Expr(Identifier(Ident { value: \"d\", quote_style: None })))], over: None, distinct: false, special: false, order_by: [] }))], into: None, from: [TableWithJoins { relation: Table { name: ObjectName([Ident { value: \"t\", quote_style: None }]), alias: None, args: None, with_hints: [] }, joins: [] }], lateral_views: [], selection: None, group_by: [], cluster_by: [], distribute_by: [], sort_by: [], having: None, named_window: [], qualify: None }), order_by: [], limit: None, offset: None, fetch: None, locks: [] }))"; assert!(actual.contains(expected)); } @@ -1391,26 +1384,16 @@ mod test { let statements1 = DaskParser::parse_sql(sql1).unwrap(); assert_eq!(1, statements1.len()); let actual1 = format!("{:?}", statements1[0]); - let expected1 = "projection: [\ - UnnamedExpr(Function(Function { name: ObjectName([Ident { value: \"dsql_totimestamp\", quote_style: None }]), \ - args: [\ - Unnamed(Expr(Identifier(Ident { value: \"d\", quote_style: None }))), \ - Unnamed(Expr(Value(SingleQuotedString(\"%Y-%m-%d %H:%M:%S\"))))\ - ], over: None, distinct: false, special: false }))\ - ]"; + let expected1 = "Statement(Query(Query { with: None, body: Select(Select { distinct: None, top: None, projection: [UnnamedExpr(Function(Function { name: ObjectName([Ident { value: \"dsql_totimestamp\", quote_style: None }]), args: [Unnamed(Expr(Identifier(Ident { value: \"d\", quote_style: None }))), Unnamed(Expr(Value(SingleQuotedString(\"%Y-%m-%d %H:%M:%S\"))))], over: None, distinct: false, special: false, order_by: [] }))], into: None, from: [TableWithJoins { relation: Table { name: ObjectName([Ident { value: \"t\", quote_style: None }]), alias: None, args: None, with_hints: [] }, joins: [] }], lateral_views: [], selection: None, group_by: [], cluster_by: [], distribute_by: [], sort_by: [], having: None, named_window: [], qualify: None }), order_by: [], limit: None, offset: None, fetch: None, locks: [] }))"; + assert!(actual1.contains(expected1)); let sql2 = "SELECT TO_TIMESTAMP(d, \"%d/%m/%Y\") FROM t"; let statements2 = DaskParser::parse_sql(sql2).unwrap(); assert_eq!(1, statements2.len()); let actual2 = format!("{:?}", statements2[0]); - let expected2 = "projection: [\ - UnnamedExpr(Function(Function { name: ObjectName([Ident { value: \"dsql_totimestamp\", quote_style: None }]), \ - args: [\ - Unnamed(Expr(Identifier(Ident { value: \"d\", quote_style: None }))), \ - Unnamed(Expr(Value(SingleQuotedString(\"\\\"%d/%m/%Y\\\"\"))))\ - ], over: None, distinct: false, special: false }))\ - ]"; + let expected2 = "Statement(Query(Query { with: None, body: Select(Select { distinct: None, top: None, projection: [UnnamedExpr(Function(Function { name: ObjectName([Ident { value: \"dsql_totimestamp\", quote_style: None }]), args: [Unnamed(Expr(Identifier(Ident { value: \"d\", quote_style: None }))), Unnamed(Expr(Value(SingleQuotedString(\"\\\"%d/%m/%Y\\\"\"))))], over: None, distinct: false, special: false, order_by: [] }))], into: None, from: [TableWithJoins { relation: Table { name: ObjectName([Ident { value: \"t\", quote_style: None }]), alias: None, args: None, with_hints: [] }, joins: [] }], lateral_views: [], selection: None, group_by: [], cluster_by: [], distribute_by: [], sort_by: [], having: None, named_window: [], qualify: None }), order_by: [], limit: None, offset: None, fetch: None, locks: [] }))"; + assert!(actual2.contains(expected2)); } diff --git a/dask_planner/src/sql.rs b/src/sql.rs similarity index 96% rename from dask_planner/src/sql.rs rename to src/sql.rs index a0e238727..c9a600225 100644 --- a/dask_planner/src/sql.rs +++ b/src/sql.rs @@ -21,7 +21,7 @@ use datafusion_python::{ }, datafusion_expr::{ logical_plan::Extension, - AccumulatorFunctionImplementation, + AccumulatorFactoryFunction, AggregateUDF, LogicalPlan, ReturnTypeFunction, @@ -78,21 +78,7 @@ use crate::{ /// /// The following example demonstrates how to generate an optimized LogicalPlan /// from SQL using DaskSQLContext. -/// -/// ``` -/// use datafusion_python::datafusion::prelude::*; -/// -/// # use datafusion_python::datafusion_common::Result; -/// # #[tokio::main] -/// # async fn main() -> Result<()> { -/// let mut ctx = DaskSQLContext::new(); -/// let parsed_sql = ctx.parse_sql("SELECT COUNT(*) FROM test_table"); -/// let nonOptimizedRelAlgebra = ctx.logical_relational_algebra(parsed_sql); -/// let optmizedRelAlg = ctx.optimizeRelationalAlgebra(nonOptimizedRelAlgebra); -/// # Ok(()) -/// # } -/// ``` -#[pyclass(name = "DaskSQLContext", module = "dask_planner", subclass)] +#[pyclass(name = "DaskSQLContext", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct DaskSQLContext { current_catalog: String, @@ -385,7 +371,7 @@ impl ContextProvider for DaskSQLContext { } fn get_aggregate_meta(&self, name: &str) -> Option> { - let acc: AccumulatorFunctionImplementation = + let acc: AccumulatorFactoryFunction = Arc::new(|_return_type| Err(DataFusionError::NotImplemented("".to_string()))); let st: StateTypeFunction = @@ -478,6 +464,13 @@ impl ContextProvider for DaskSQLContext { fn options(&self) -> &ConfigOptions { &self.options } + + fn get_window_meta( + &self, + _name: &str, + ) -> Option> { + unimplemented!("RUST: get_window_meta is not yet implemented for DaskSQLContext") + } } #[pymethods] @@ -592,14 +585,19 @@ impl DaskSQLContext { current_node: None, }) .map_err(py_optimization_exp); - if self.dynamic_partition_pruning { - optimizer::DaskSqlOptimizer::dynamic_partition_pruner() - .optimize_once(optimized_plan.unwrap().original_plan) - .map(|k| PyLogicalPlan { - original_plan: k, - current_node: None, - }) - .map_err(py_optimization_exp) + + if let Ok(optimized_plan) = optimized_plan { + if self.dynamic_partition_pruning { + optimizer::DaskSqlOptimizer::dynamic_partition_pruner() + .optimize_once(optimized_plan.original_plan) + .map(|k| PyLogicalPlan { + original_plan: k, + current_node: None, + }) + .map_err(py_optimization_exp) + } else { + Ok(optimized_plan) + } } else { optimized_plan } diff --git a/dask_planner/src/sql/column.rs b/src/sql/column.rs similarity index 91% rename from dask_planner/src/sql/column.rs rename to src/sql/column.rs index 63f043901..32250c382 100644 --- a/dask_planner/src/sql/column.rs +++ b/src/sql/column.rs @@ -1,7 +1,7 @@ use datafusion_python::datafusion_common::Column; use pyo3::prelude::*; -#[pyclass(name = "Column", module = "dask_planner", subclass)] +#[pyclass(name = "Column", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct PyColumn { /// Original Column instance diff --git a/dask_planner/src/sql/exceptions.rs b/src/sql/exceptions.rs similarity index 100% rename from dask_planner/src/sql/exceptions.rs rename to src/sql/exceptions.rs diff --git a/dask_planner/src/sql/function.rs b/src/sql/function.rs similarity index 93% rename from dask_planner/src/sql/function.rs rename to src/sql/function.rs index 39fa7635e..4169d386c 100644 --- a/dask_planner/src/sql/function.rs +++ b/src/sql/function.rs @@ -5,7 +5,7 @@ use pyo3::prelude::*; use super::types::PyDataType; -#[pyclass(name = "DaskFunction", module = "dask_planner", subclass)] +#[pyclass(name = "DaskFunction", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct DaskFunction { #[pyo3(get, set)] diff --git a/dask_planner/src/sql/logical.rs b/src/sql/logical.rs similarity index 95% rename from dask_planner/src/sql/logical.rs rename to src/sql/logical.rs index d2096ba9b..e8f5f9f6f 100644 --- a/dask_planner/src/sql/logical.rs +++ b/src/sql/logical.rs @@ -37,7 +37,7 @@ pub mod window; use datafusion_python::{ datafusion_common::{DFSchemaRef, DataFusionError}, - datafusion_expr::LogicalPlan, + datafusion_expr::{DdlStatement, LogicalPlan}, }; use pyo3::prelude::*; @@ -62,7 +62,7 @@ use self::{ }; use crate::{error::Result, sql::exceptions::py_type_err}; -#[pyclass(name = "LogicalPlan", module = "dask_planner", subclass)] +#[pyclass(name = "LogicalPlan", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct PyLogicalPlan { /// The original LogicalPlan that was parsed by DataFusion from the input SQL @@ -315,18 +315,19 @@ impl PyLogicalPlan { LogicalPlan::TableScan(_table_scan) => "TableScan", LogicalPlan::EmptyRelation(_empty_relation) => "EmptyRelation", LogicalPlan::Limit(_limit) => "Limit", - LogicalPlan::CreateExternalTable(_create_external_table) => "CreateExternalTable", - LogicalPlan::CreateMemoryTable(_create_memory_table) => "CreateMemoryTable", - LogicalPlan::DropTable(_drop_table) => "DropTable", - LogicalPlan::DropView(_drop_view) => "DropView", + LogicalPlan::Ddl(DdlStatement::CreateExternalTable { .. }) => "CreateExternalTable", + LogicalPlan::Ddl(DdlStatement::CreateMemoryTable { .. }) => "CreateMemoryTable", + LogicalPlan::Ddl(DdlStatement::DropTable { .. }) => "DropTable", + LogicalPlan::Ddl(DdlStatement::DropView { .. }) => "DropView", LogicalPlan::Values(_values) => "Values", LogicalPlan::Explain(_explain) => "Explain", LogicalPlan::Analyze(_analyze) => "Analyze", LogicalPlan::Subquery(_sub_query) => "Subquery", LogicalPlan::SubqueryAlias(_sqalias) => "SubqueryAlias", - LogicalPlan::CreateCatalogSchema(_create) => "CreateCatalogSchema", - LogicalPlan::CreateCatalog(_create_catalog) => "CreateCatalog", - LogicalPlan::CreateView(_create_view) => "CreateView", + LogicalPlan::Ddl(DdlStatement::CreateCatalogSchema { .. }) => "CreateCatalogSchema", + LogicalPlan::Ddl(DdlStatement::DropCatalogSchema { .. }) => "DropCatalogSchema", + LogicalPlan::Ddl(DdlStatement::CreateCatalog { .. }) => "CreateCatalog", + LogicalPlan::Ddl(DdlStatement::CreateView { .. }) => "CreateView", LogicalPlan::Statement(_) => "Statement", // Further examine and return the name that is a possible Dask-SQL Extension type LogicalPlan::Extension(extension) => { diff --git a/dask_planner/src/sql/logical/aggregate.rs b/src/sql/logical/aggregate.rs similarity index 87% rename from dask_planner/src/sql/logical/aggregate.rs rename to src/sql/logical/aggregate.rs index 0acc8b86e..1c4074239 100644 --- a/dask_planner/src/sql/logical/aggregate.rs +++ b/src/sql/logical/aggregate.rs @@ -1,5 +1,5 @@ use datafusion_python::datafusion_expr::{ - expr::AggregateFunction, + expr::{AggregateFunction, AggregateUDF, Alias}, logical_plan::{Aggregate, Distinct}, Expr, LogicalPlan, @@ -11,7 +11,7 @@ use crate::{ sql::exceptions::py_type_err, }; -#[pyclass(name = "Aggregate", module = "dask_planner", subclass)] +#[pyclass(name = "Aggregate", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyAggregate { aggregate: Option, @@ -73,9 +73,9 @@ impl PyAggregate { impl PyAggregate { fn _aggregation_arguments(&self, expr: &Expr) -> PyResult> { match expr { - Expr::Alias(expr, _) => self._aggregation_arguments(expr.as_ref()), + Expr::Alias(Alias { expr, .. }) => self._aggregation_arguments(expr.as_ref()), Expr::AggregateFunction(AggregateFunction { fun: _, args, .. }) - | Expr::AggregateUDF { fun: _, args, .. } => match &self.aggregate { + | Expr::AggregateUDF(AggregateUDF { fun: _, args, .. }) => match &self.aggregate { Some(e) => py_expr_list(&e.input, args), None => Ok(vec![]), }, @@ -88,9 +88,9 @@ impl PyAggregate { fn _agg_func_name(expr: &Expr) -> PyResult { match expr { - Expr::Alias(expr, _) => _agg_func_name(expr.as_ref()), + Expr::Alias(Alias { expr, .. }) => _agg_func_name(expr.as_ref()), Expr::AggregateFunction(AggregateFunction { fun, .. }) => Ok(fun.to_string()), - Expr::AggregateUDF { fun, .. } => Ok(fun.name.clone()), + Expr::AggregateUDF(AggregateUDF { fun, .. }) => Ok(fun.name.clone()), _ => Err(py_type_err( "Encountered a non Aggregate type in agg_func_name", )), @@ -99,7 +99,7 @@ fn _agg_func_name(expr: &Expr) -> PyResult { fn _distinct_agg_expr(expr: &Expr) -> PyResult { match expr { - Expr::Alias(expr, _) => _distinct_agg_expr(expr.as_ref()), + Expr::Alias(Alias { expr, .. }) => _distinct_agg_expr(expr.as_ref()), Expr::AggregateFunction(AggregateFunction { distinct, .. }) => Ok(*distinct), Expr::AggregateUDF { .. } => { // DataFusion does not support DISTINCT in UDAFs diff --git a/dask_planner/src/sql/logical/alter_schema.rs b/src/sql/logical/alter_schema.rs similarity index 98% rename from dask_planner/src/sql/logical/alter_schema.rs rename to src/sql/logical/alter_schema.rs index 742ae513f..a7a8696b8 100644 --- a/dask_planner/src/sql/logical/alter_schema.rs +++ b/src/sql/logical/alter_schema.rs @@ -96,7 +96,7 @@ impl UserDefinedLogicalNode for AlterSchemaPlanNode { } } -#[pyclass(name = "AlterSchema", module = "dask_planner", subclass)] +#[pyclass(name = "AlterSchema", module = "dask_sql", subclass)] pub struct PyAlterSchema { pub(crate) alter_schema: AlterSchemaPlanNode, } diff --git a/dask_planner/src/sql/logical/alter_table.rs b/src/sql/logical/alter_table.rs similarity index 98% rename from dask_planner/src/sql/logical/alter_table.rs rename to src/sql/logical/alter_table.rs index 7f51a15c3..d6b49315b 100644 --- a/dask_planner/src/sql/logical/alter_table.rs +++ b/src/sql/logical/alter_table.rs @@ -102,7 +102,7 @@ impl UserDefinedLogicalNode for AlterTablePlanNode { } } -#[pyclass(name = "AlterTable", module = "dask_planner", subclass)] +#[pyclass(name = "AlterTable", module = "dask_sql", subclass)] pub struct PyAlterTable { pub(crate) alter_table: AlterTablePlanNode, } diff --git a/dask_planner/src/sql/logical/analyze_table.rs b/src/sql/logical/analyze_table.rs similarity index 98% rename from dask_planner/src/sql/logical/analyze_table.rs rename to src/sql/logical/analyze_table.rs index 9fa7fb219..6876c3704 100644 --- a/dask_planner/src/sql/logical/analyze_table.rs +++ b/src/sql/logical/analyze_table.rs @@ -99,7 +99,7 @@ impl UserDefinedLogicalNode for AnalyzeTablePlanNode { } } -#[pyclass(name = "AnalyzeTable", module = "dask_planner", subclass)] +#[pyclass(name = "AnalyzeTable", module = "dask_sql", subclass)] pub struct PyAnalyzeTable { pub(crate) analyze_table: AnalyzeTablePlanNode, } diff --git a/dask_planner/src/sql/logical/create_catalog_schema.rs b/src/sql/logical/create_catalog_schema.rs similarity index 98% rename from dask_planner/src/sql/logical/create_catalog_schema.rs rename to src/sql/logical/create_catalog_schema.rs index bc89b02ce..82a1426af 100644 --- a/dask_planner/src/sql/logical/create_catalog_schema.rs +++ b/src/sql/logical/create_catalog_schema.rs @@ -95,7 +95,7 @@ impl UserDefinedLogicalNode for CreateCatalogSchemaPlanNode { } } -#[pyclass(name = "CreateCatalogSchema", module = "dask_planner", subclass)] +#[pyclass(name = "CreateCatalogSchema", module = "dask_sql", subclass)] pub struct PyCreateCatalogSchema { pub(crate) create_catalog_schema: CreateCatalogSchemaPlanNode, } diff --git a/dask_planner/src/sql/logical/create_experiment.rs b/src/sql/logical/create_experiment.rs similarity index 98% rename from dask_planner/src/sql/logical/create_experiment.rs rename to src/sql/logical/create_experiment.rs index 313357d75..06fe9d856 100644 --- a/dask_planner/src/sql/logical/create_experiment.rs +++ b/src/sql/logical/create_experiment.rs @@ -105,7 +105,7 @@ impl UserDefinedLogicalNode for CreateExperimentPlanNode { } } -#[pyclass(name = "CreateExperiment", module = "dask_planner", subclass)] +#[pyclass(name = "CreateExperiment", module = "dask_sql", subclass)] pub struct PyCreateExperiment { pub(crate) create_experiment: CreateExperimentPlanNode, } diff --git a/dask_planner/src/sql/logical/create_memory_table.rs b/src/sql/logical/create_memory_table.rs similarity index 89% rename from dask_planner/src/sql/logical/create_memory_table.rs rename to src/sql/logical/create_memory_table.rs index 668295e0f..53ff9432e 100644 --- a/dask_planner/src/sql/logical/create_memory_table.rs +++ b/src/sql/logical/create_memory_table.rs @@ -1,12 +1,13 @@ use datafusion_python::datafusion_expr::{ logical_plan::{CreateMemoryTable, CreateView}, + DdlStatement, LogicalPlan, }; use pyo3::prelude::*; use crate::sql::{exceptions::py_type_err, logical::PyLogicalPlan}; -#[pyclass(name = "CreateMemoryTable", module = "dask_planner", subclass)] +#[pyclass(name = "CreateMemoryTable", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyCreateMemoryTable { create_memory_table: Option, @@ -85,13 +86,13 @@ impl TryFrom for PyCreateMemoryTable { fn try_from(logical_plan: LogicalPlan) -> Result { Ok(match logical_plan { - LogicalPlan::CreateMemoryTable(create_memory_table) => PyCreateMemoryTable { - create_memory_table: Some(create_memory_table), + LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(cmt)) => PyCreateMemoryTable { + create_memory_table: Some(cmt), create_view: None, }, - LogicalPlan::CreateView(create_view) => PyCreateMemoryTable { + LogicalPlan::Ddl(DdlStatement::CreateView(cv)) => PyCreateMemoryTable { create_memory_table: None, - create_view: Some(create_view), + create_view: Some(cv), }, _ => return Err(py_type_err("unexpected plan")), }) diff --git a/dask_planner/src/sql/logical/create_model.rs b/src/sql/logical/create_model.rs similarity index 98% rename from dask_planner/src/sql/logical/create_model.rs rename to src/sql/logical/create_model.rs index 782fe3325..7dbcdff95 100644 --- a/dask_planner/src/sql/logical/create_model.rs +++ b/src/sql/logical/create_model.rs @@ -101,7 +101,7 @@ impl UserDefinedLogicalNode for CreateModelPlanNode { } } -#[pyclass(name = "CreateModel", module = "dask_planner", subclass)] +#[pyclass(name = "CreateModel", module = "dask_sql", subclass)] pub struct PyCreateModel { pub(crate) create_model: CreateModelPlanNode, } diff --git a/dask_planner/src/sql/logical/create_table.rs b/src/sql/logical/create_table.rs similarity index 98% rename from dask_planner/src/sql/logical/create_table.rs rename to src/sql/logical/create_table.rs index 9271130c7..1c423415f 100644 --- a/dask_planner/src/sql/logical/create_table.rs +++ b/src/sql/logical/create_table.rs @@ -100,7 +100,7 @@ impl UserDefinedLogicalNode for CreateTablePlanNode { } } -#[pyclass(name = "CreateTable", module = "dask_planner", subclass)] +#[pyclass(name = "CreateTable", module = "dask_sql", subclass)] pub struct PyCreateTable { pub(crate) create_table: CreateTablePlanNode, } diff --git a/dask_planner/src/sql/logical/describe_model.rs b/src/sql/logical/describe_model.rs similarity index 97% rename from dask_planner/src/sql/logical/describe_model.rs rename to src/sql/logical/describe_model.rs index cb2087376..3e3563fe1 100644 --- a/dask_planner/src/sql/logical/describe_model.rs +++ b/src/sql/logical/describe_model.rs @@ -89,7 +89,7 @@ impl UserDefinedLogicalNode for DescribeModelPlanNode { } } -#[pyclass(name = "DescribeModel", module = "dask_planner", subclass)] +#[pyclass(name = "DescribeModel", module = "dask_sql", subclass)] pub struct PyDescribeModel { pub(crate) describe_model: DescribeModelPlanNode, } diff --git a/dask_planner/src/sql/logical/drop_model.rs b/src/sql/logical/drop_model.rs similarity index 98% rename from dask_planner/src/sql/logical/drop_model.rs rename to src/sql/logical/drop_model.rs index 71074905d..2715cb067 100644 --- a/dask_planner/src/sql/logical/drop_model.rs +++ b/src/sql/logical/drop_model.rs @@ -92,7 +92,7 @@ impl UserDefinedLogicalNode for DropModelPlanNode { } } -#[pyclass(name = "DropModel", module = "dask_planner", subclass)] +#[pyclass(name = "DropModel", module = "dask_sql", subclass)] pub struct PyDropModel { pub(crate) drop_model: DropModelPlanNode, } diff --git a/dask_planner/src/sql/logical/drop_schema.rs b/src/sql/logical/drop_schema.rs similarity index 97% rename from dask_planner/src/sql/logical/drop_schema.rs rename to src/sql/logical/drop_schema.rs index 2022a61c9..78d252d11 100644 --- a/dask_planner/src/sql/logical/drop_schema.rs +++ b/src/sql/logical/drop_schema.rs @@ -88,7 +88,7 @@ impl UserDefinedLogicalNode for DropSchemaPlanNode { } } -#[pyclass(name = "DropSchema", module = "dask_planner", subclass)] +#[pyclass(name = "DropSchema", module = "dask_sql", subclass)] pub struct PyDropSchema { pub(crate) drop_schema: DropSchemaPlanNode, } diff --git a/dask_planner/src/sql/logical/drop_table.rs b/src/sql/logical/drop_table.rs similarity index 71% rename from dask_planner/src/sql/logical/drop_table.rs rename to src/sql/logical/drop_table.rs index 7d58e8a47..504a104c1 100644 --- a/dask_planner/src/sql/logical/drop_table.rs +++ b/src/sql/logical/drop_table.rs @@ -1,9 +1,12 @@ -use datafusion_python::datafusion_expr::logical_plan::{DropTable, LogicalPlan}; +use datafusion_python::datafusion_expr::{ + logical_plan::{DropTable, LogicalPlan}, + DdlStatement, +}; use pyo3::prelude::*; use crate::sql::exceptions::py_type_err; -#[pyclass(name = "DropTable", module = "dask_planner", subclass)] +#[pyclass(name = "DropTable", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyDropTable { drop_table: DropTable, @@ -27,7 +30,7 @@ impl TryFrom for PyDropTable { fn try_from(logical_plan: LogicalPlan) -> Result { match logical_plan { - LogicalPlan::DropTable(drop_table) => Ok(PyDropTable { drop_table }), + LogicalPlan::Ddl(DdlStatement::DropTable(drop_table)) => Ok(PyDropTable { drop_table }), _ => Err(py_type_err("unexpected plan")), } } diff --git a/dask_planner/src/sql/logical/empty_relation.rs b/src/sql/logical/empty_relation.rs similarity index 94% rename from dask_planner/src/sql/logical/empty_relation.rs rename to src/sql/logical/empty_relation.rs index 5bd6659ce..6356f9c85 100644 --- a/dask_planner/src/sql/logical/empty_relation.rs +++ b/src/sql/logical/empty_relation.rs @@ -3,7 +3,7 @@ use pyo3::prelude::*; use crate::sql::exceptions::py_type_err; -#[pyclass(name = "EmptyRelation", module = "dask_planner", subclass)] +#[pyclass(name = "EmptyRelation", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyEmptyRelation { empty_relation: EmptyRelation, diff --git a/dask_planner/src/sql/logical/explain.rs b/src/sql/logical/explain.rs similarity index 93% rename from dask_planner/src/sql/logical/explain.rs rename to src/sql/logical/explain.rs index 17f1e4ee2..839a731d8 100644 --- a/dask_planner/src/sql/logical/explain.rs +++ b/src/sql/logical/explain.rs @@ -3,7 +3,7 @@ use pyo3::prelude::*; use crate::sql::exceptions::py_type_err; -#[pyclass(name = "Explain", module = "dask_planner", subclass)] +#[pyclass(name = "Explain", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyExplain { explain: Explain, diff --git a/dask_planner/src/sql/logical/export_model.rs b/src/sql/logical/export_model.rs similarity index 98% rename from dask_planner/src/sql/logical/export_model.rs rename to src/sql/logical/export_model.rs index e38551b58..58b5f7fad 100644 --- a/dask_planner/src/sql/logical/export_model.rs +++ b/src/sql/logical/export_model.rs @@ -95,7 +95,7 @@ impl UserDefinedLogicalNode for ExportModelPlanNode { } } -#[pyclass(name = "ExportModel", module = "dask_planner", subclass)] +#[pyclass(name = "ExportModel", module = "dask_sql", subclass)] pub struct PyExportModel { pub(crate) export_model: ExportModelPlanNode, } diff --git a/dask_planner/src/sql/logical/filter.rs b/src/sql/logical/filter.rs similarity index 93% rename from dask_planner/src/sql/logical/filter.rs rename to src/sql/logical/filter.rs index a50d508ff..f2dc2e702 100644 --- a/dask_planner/src/sql/logical/filter.rs +++ b/src/sql/logical/filter.rs @@ -3,7 +3,7 @@ use pyo3::prelude::*; use crate::{expression::PyExpr, sql::exceptions::py_type_err}; -#[pyclass(name = "Filter", module = "dask_planner", subclass)] +#[pyclass(name = "Filter", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyFilter { filter: Filter, diff --git a/dask_planner/src/sql/logical/join.rs b/src/sql/logical/join.rs similarity index 98% rename from dask_planner/src/sql/logical/join.rs rename to src/sql/logical/join.rs index d6c31b55b..3261e9217 100644 --- a/dask_planner/src/sql/logical/join.rs +++ b/src/sql/logical/join.rs @@ -15,7 +15,7 @@ use crate::{ sql::{column, exceptions::py_type_err}, }; -#[pyclass(name = "Join", module = "dask_planner", subclass)] +#[pyclass(name = "Join", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyJoin { join: Join, diff --git a/dask_planner/src/sql/logical/limit.rs b/src/sql/logical/limit.rs similarity index 95% rename from dask_planner/src/sql/logical/limit.rs rename to src/sql/logical/limit.rs index 189fdeea0..04d783fdd 100644 --- a/dask_planner/src/sql/logical/limit.rs +++ b/src/sql/logical/limit.rs @@ -6,7 +6,7 @@ use pyo3::prelude::*; use crate::{expression::PyExpr, sql::exceptions::py_type_err}; -#[pyclass(name = "Limit", module = "dask_planner", subclass)] +#[pyclass(name = "Limit", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyLimit { limit: Limit, diff --git a/dask_planner/src/sql/logical/predict_model.rs b/src/sql/logical/predict_model.rs similarity index 98% rename from dask_planner/src/sql/logical/predict_model.rs rename to src/sql/logical/predict_model.rs index e8d723d2c..3f68ffdb4 100644 --- a/dask_planner/src/sql/logical/predict_model.rs +++ b/src/sql/logical/predict_model.rs @@ -89,7 +89,7 @@ impl UserDefinedLogicalNode for PredictModelPlanNode { } } -#[pyclass(name = "PredictModel", module = "dask_planner", subclass)] +#[pyclass(name = "PredictModel", module = "dask_sql", subclass)] pub struct PyPredictModel { pub(crate) predict_model: PredictModelPlanNode, } diff --git a/dask_planner/src/sql/logical/projection.rs b/src/sql/logical/projection.rs similarity index 83% rename from dask_planner/src/sql/logical/projection.rs rename to src/sql/logical/projection.rs index 99ed0d684..56e5e28d8 100644 --- a/dask_planner/src/sql/logical/projection.rs +++ b/src/sql/logical/projection.rs @@ -1,9 +1,14 @@ -use datafusion_python::datafusion_expr::{logical_plan::Projection, Expr, LogicalPlan}; +use datafusion_python::datafusion_expr::{ + expr::Alias, + logical_plan::Projection, + Expr, + LogicalPlan, +}; use pyo3::prelude::*; use crate::{expression::PyExpr, sql::exceptions::py_type_err}; -#[pyclass(name = "Projection", module = "dask_planner", subclass)] +#[pyclass(name = "Projection", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyProjection { pub(crate) projection: Projection, @@ -14,7 +19,7 @@ impl PyProjection { fn projected_expressions(&mut self, local_expr: &PyExpr) -> Vec { let mut projs: Vec = Vec::new(); match &local_expr.expr { - Expr::Alias(expr, _name) => { + Expr::Alias(Alias { expr, .. }) => { let py_expr: PyExpr = PyExpr::from(*expr.clone(), Some(vec![self.projection.input.clone()])); projs.extend_from_slice(self.projected_expressions(&py_expr).as_slice()); @@ -35,9 +40,9 @@ impl PyProjection { PyExpr::from(expression, Some(vec![self.projection.input.clone()])); for expr in self.projected_expressions(&py_expr) { match expr.expr { - Expr::Alias(ex, name) => named.push(( + Expr::Alias(Alias { expr, name }) => named.push(( name.to_string(), - PyExpr::from(*ex, Some(vec![self.projection.input.clone()])), + PyExpr::from(*expr, Some(vec![self.projection.input.clone()])), )), _ => { if let Ok(name) = expr._column_name(&self.projection.input) { diff --git a/dask_planner/src/sql/logical/repartition_by.rs b/src/sql/logical/repartition_by.rs similarity index 96% rename from dask_planner/src/sql/logical/repartition_by.rs rename to src/sql/logical/repartition_by.rs index e931b88e7..687958571 100644 --- a/dask_planner/src/sql/logical/repartition_by.rs +++ b/src/sql/logical/repartition_by.rs @@ -10,7 +10,7 @@ use crate::{ sql::{exceptions::py_type_err, logical}, }; -#[pyclass(name = "RepartitionBy", module = "dask_planner", subclass)] +#[pyclass(name = "RepartitionBy", module = "dask_sql", subclass)] pub struct PyRepartitionBy { pub(crate) repartition: Repartition, } diff --git a/dask_planner/src/sql/logical/show_columns.rs b/src/sql/logical/show_columns.rs similarity index 98% rename from dask_planner/src/sql/logical/show_columns.rs rename to src/sql/logical/show_columns.rs index adfb584ef..cdd844127 100644 --- a/dask_planner/src/sql/logical/show_columns.rs +++ b/src/sql/logical/show_columns.rs @@ -92,7 +92,7 @@ impl UserDefinedLogicalNode for ShowColumnsPlanNode { } } -#[pyclass(name = "ShowColumns", module = "dask_planner", subclass)] +#[pyclass(name = "ShowColumns", module = "dask_sql", subclass)] pub struct PyShowColumns { pub(crate) show_columns: ShowColumnsPlanNode, } diff --git a/dask_planner/src/sql/logical/show_models.rs b/src/sql/logical/show_models.rs similarity index 97% rename from dask_planner/src/sql/logical/show_models.rs rename to src/sql/logical/show_models.rs index 026a179a5..a228769de 100644 --- a/dask_planner/src/sql/logical/show_models.rs +++ b/src/sql/logical/show_models.rs @@ -85,7 +85,7 @@ impl UserDefinedLogicalNode for ShowModelsPlanNode { } } -#[pyclass(name = "ShowModels", module = "dask_planner", subclass)] +#[pyclass(name = "ShowModels", module = "dask_sql", subclass)] pub struct PyShowModels { pub(crate) show_models: ShowModelsPlanNode, } diff --git a/dask_planner/src/sql/logical/show_schemas.rs b/src/sql/logical/show_schemas.rs similarity index 98% rename from dask_planner/src/sql/logical/show_schemas.rs rename to src/sql/logical/show_schemas.rs index 3e3ed4783..454afb51d 100644 --- a/dask_planner/src/sql/logical/show_schemas.rs +++ b/src/sql/logical/show_schemas.rs @@ -91,7 +91,7 @@ impl UserDefinedLogicalNode for ShowSchemasPlanNode { } } -#[pyclass(name = "ShowSchema", module = "dask_planner", subclass)] +#[pyclass(name = "ShowSchema", module = "dask_sql", subclass)] pub struct PyShowSchema { pub(crate) show_schema: ShowSchemasPlanNode, } diff --git a/dask_planner/src/sql/logical/show_tables.rs b/src/sql/logical/show_tables.rs similarity index 98% rename from dask_planner/src/sql/logical/show_tables.rs rename to src/sql/logical/show_tables.rs index 987f2546e..c01022828 100644 --- a/dask_planner/src/sql/logical/show_tables.rs +++ b/src/sql/logical/show_tables.rs @@ -95,7 +95,7 @@ impl UserDefinedLogicalNode for ShowTablesPlanNode { } } -#[pyclass(name = "ShowTables", module = "dask_planner", subclass)] +#[pyclass(name = "ShowTables", module = "dask_sql", subclass)] pub struct PyShowTables { pub(crate) show_tables: ShowTablesPlanNode, } diff --git a/dask_planner/src/sql/logical/sort.rs b/src/sql/logical/sort.rs similarity index 93% rename from dask_planner/src/sql/logical/sort.rs rename to src/sql/logical/sort.rs index 9abcd3906..5a1f862a1 100644 --- a/dask_planner/src/sql/logical/sort.rs +++ b/src/sql/logical/sort.rs @@ -6,7 +6,7 @@ use crate::{ sql::exceptions::py_type_err, }; -#[pyclass(name = "Sort", module = "dask_planner", subclass)] +#[pyclass(name = "Sort", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PySort { sort: Sort, diff --git a/dask_planner/src/sql/logical/subquery_alias.rs b/src/sql/logical/subquery_alias.rs similarity index 85% rename from dask_planner/src/sql/logical/subquery_alias.rs rename to src/sql/logical/subquery_alias.rs index 1b23e5dc4..e98c78203 100644 --- a/dask_planner/src/sql/logical/subquery_alias.rs +++ b/src/sql/logical/subquery_alias.rs @@ -3,7 +3,7 @@ use pyo3::prelude::*; use crate::sql::exceptions::py_type_err; -#[pyclass(name = "SubqueryAlias", module = "dask_planner", subclass)] +#[pyclass(name = "SubqueryAlias", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PySubqueryAlias { subquery_alias: SubqueryAlias, @@ -14,7 +14,7 @@ impl PySubqueryAlias { /// Returns a Vec of the sort expressions #[pyo3(name = "getAlias")] pub fn alias(&self) -> PyResult { - Ok(self.subquery_alias.alias.clone()) + Ok(self.subquery_alias.alias.clone().to_string()) } } diff --git a/dask_planner/src/sql/logical/table_scan.rs b/src/sql/logical/table_scan.rs similarity index 95% rename from dask_planner/src/sql/logical/table_scan.rs rename to src/sql/logical/table_scan.rs index 3b7a89e6e..c9cb92ebd 100644 --- a/dask_planner/src/sql/logical/table_scan.rs +++ b/src/sql/logical/table_scan.rs @@ -2,7 +2,12 @@ use std::{sync::Arc, vec}; use datafusion_python::{ datafusion_common::{DFSchema, ScalarValue}, - datafusion_expr::{logical_plan::TableScan, Expr, LogicalPlan}, + datafusion_expr::{ + expr::{Alias, InList}, + logical_plan::TableScan, + Expr, + LogicalPlan, + }, }; use pyo3::prelude::*; @@ -12,7 +17,7 @@ use crate::{ sql::exceptions::py_type_err, }; -#[pyclass(name = "TableScan", module = "dask_planner", subclass)] +#[pyclass(name = "TableScan", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyTableScan { pub(crate) table_scan: TableScan, @@ -20,7 +25,7 @@ pub struct PyTableScan { } type FilterTuple = (String, String, Option>); -#[pyclass(name = "FilteredResult", module = "dask_planner", subclass)] +#[pyclass(name = "FilteredResult", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct PyFilteredResult { // Certain Expr(s) do not have supporting logic in pyarrow for IO filtering @@ -52,11 +57,11 @@ impl PyTableScan { let mut filter_tuple: Vec<(PyExpr, FilterTuple)> = Vec::new(); match filter { - Expr::InList { + Expr::InList(InList { expr, list, negated, - } => { + }) => { // Only handle simple Expr(s) for InList operations for now if PyTableScan::_valid_expr_type(list) { // While ANSI SQL would not allow for anything other than a Column or Literal @@ -64,7 +69,7 @@ impl PyTableScan { // IF it is something else it is returned to Dask to handle let ident = match *expr.clone() { Expr::Column(col) => Ok(col.name), - Expr::Alias(_, name) => Ok(name), + Expr::Alias(Alias { name, .. }) => Ok(name), Expr::Literal(val) => Ok(format!("{}", val)), _ => Err(DaskPlannerError::InvalidIOFilter(format!( "Invalid InList Expr type `{}`. using in Dask instead", @@ -77,7 +82,7 @@ impl PyTableScan { .iter() .map(|f| match f { Expr::Column(col) => Ok(col.name.clone().into_py(py)), - Expr::Alias(_, name) => Ok(name.clone().into_py(py)), + Expr::Alias(Alias { name, ..}) => Ok(name.clone().into_py(py)), Expr::Literal(val) => match val { ScalarValue::Boolean(val) => Ok(val.unwrap().into_py(py)), ScalarValue::Float32(val) => Ok(val.unwrap().into_py(py)), diff --git a/dask_planner/src/sql/logical/use_schema.rs b/src/sql/logical/use_schema.rs similarity index 97% rename from dask_planner/src/sql/logical/use_schema.rs rename to src/sql/logical/use_schema.rs index 7c2206310..0f804ce7a 100644 --- a/dask_planner/src/sql/logical/use_schema.rs +++ b/src/sql/logical/use_schema.rs @@ -85,7 +85,7 @@ impl UserDefinedLogicalNode for UseSchemaPlanNode { } } -#[pyclass(name = "UseSchema", module = "dask_planner", subclass)] +#[pyclass(name = "UseSchema", module = "dask_sql", subclass)] pub struct PyUseSchema { pub(crate) use_schema: UseSchemaPlanNode, } diff --git a/dask_planner/src/sql/logical/window.rs b/src/sql/logical/window.rs similarity index 96% rename from dask_planner/src/sql/logical/window.rs rename to src/sql/logical/window.rs index e104ccdb3..3dd9d8c0d 100644 --- a/dask_planner/src/sql/logical/window.rs +++ b/src/sql/logical/window.rs @@ -17,19 +17,19 @@ use crate::{ sql::exceptions::py_type_err, }; -#[pyclass(name = "Window", module = "dask_planner", subclass)] +#[pyclass(name = "Window", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyWindow { window: Window, } -#[pyclass(name = "WindowFrame", module = "dask_planner", subclass)] +#[pyclass(name = "WindowFrame", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyWindowFrame { window_frame: WindowFrame, } -#[pyclass(name = "WindowFrameBound", module = "dask_planner", subclass)] +#[pyclass(name = "WindowFrameBound", module = "dask_sql", subclass)] #[derive(Clone)] pub struct PyWindowFrameBound { frame_bound: WindowFrameBound, diff --git a/dask_planner/src/sql/optimizer.rs b/src/sql/optimizer.rs similarity index 92% rename from dask_planner/src/sql/optimizer.rs rename to src/sql/optimizer.rs index bdaa30ea7..85f335572 100644 --- a/dask_planner/src/sql/optimizer.rs +++ b/src/sql/optimizer.rs @@ -1,11 +1,16 @@ +// Declare optimizer modules +pub mod decorrelate_where_exists; +pub mod decorrelate_where_in; +pub mod dynamic_partition_pruning; +pub mod join_reorder; +pub mod utils; + use std::sync::Arc; use datafusion_python::{ datafusion_common::DataFusionError, datafusion_expr::LogicalPlan, datafusion_optimizer::{ - decorrelate_where_exists::DecorrelateWhereExists, - decorrelate_where_in::DecorrelateWhereIn, eliminate_cross_join::EliminateCrossJoin, eliminate_limit::EliminateLimit, eliminate_outer_join::EliminateOuterJoin, @@ -22,13 +27,11 @@ use datafusion_python::{ OptimizerContext, }, }; -use log::{debug, trace}; - -mod dynamic_partition_pruning; +use decorrelate_where_exists::DecorrelateWhereExists; +use decorrelate_where_in::DecorrelateWhereIn; use dynamic_partition_pruning::DynamicPartitionPruning; - -mod join_reorder; use join_reorder::JoinReorder; +use log::{debug, trace}; /// Houses the optimization logic for Dask-SQL. This optimization controls the optimizations /// and their ordering in regards to their impact on the underlying `LogicalPlan` instance @@ -151,17 +154,7 @@ mod tests { AND (cast('2002-05-08' as date) + interval '5 days')\ )"; let plan = test_sql(sql)?; - let expected = r#"Projection: test.col_int32 - Filter: CAST(test.col_int32 AS Float64) > __scalar_sq_1.__value - CrossJoin: - TableScan: test projection=[col_int32] - SubqueryAlias: __scalar_sq_1 - Projection: AVG(test.col_int32) AS __value - Aggregate: groupBy=[[]], aggr=[[AVG(test.col_int32)]] - Projection: test.col_int32 - Filter: test.col_utf8 >= Utf8("2002-05-08") AND test.col_utf8 <= Utf8("2002-05-13") - TableScan: test projection=[col_int32, col_utf8]"#; - assert_eq!(expected, format!("{:?}", plan)); + assert!(format!("{:?}", plan).contains(r#"<= Date32("11820")"#)); Ok(()) } @@ -234,6 +227,13 @@ mod tests { fn get_variable_type(&self, _variable_names: &[String]) -> Option { None } + + fn get_window_meta( + &self, + _name: &str, + ) -> Option> { + None + } } struct MyTableSource { diff --git a/src/sql/optimizer/decorrelate_where_exists.rs b/src/sql/optimizer/decorrelate_where_exists.rs new file mode 100644 index 000000000..5944c83ae --- /dev/null +++ b/src/sql/optimizer/decorrelate_where_exists.rs @@ -0,0 +1,228 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::sync::Arc; + +use datafusion_python::{ + datafusion_common::{Column, DataFusionError, Result}, + datafusion_expr::{ + expr::Exists, + logical_plan::{Distinct, Filter, JoinType, Subquery}, + Expr, + LogicalPlan, + LogicalPlanBuilder, + }, + datafusion_optimizer::optimizer::{ApplyOrder, OptimizerConfig, OptimizerRule}, +}; + +use crate::sql::optimizer::utils::{ + collect_subquery_cols, + conjunction, + extract_join_filters, + split_conjunction, +}; + +/// Optimizer rule for rewriting subquery filters to joins +#[derive(Default)] +pub struct DecorrelateWhereExists {} + +impl DecorrelateWhereExists { + #[allow(missing_docs)] + pub fn new() -> Self { + Self {} + } + + /// Finds expressions that have a where in subquery (and recurse when found) + /// + /// # Arguments + /// + /// * `predicate` - A conjunction to split and search + /// * `optimizer_config` - For generating unique subquery aliases + /// + /// Returns a tuple (subqueries, non-subquery expressions) + fn extract_subquery_exprs( + &self, + predicate: &Expr, + config: &dyn OptimizerConfig, + ) -> Result<(Vec, Vec)> { + let filters = split_conjunction(predicate); + + let mut subqueries = vec![]; + let mut others = vec![]; + for it in filters.iter() { + match it { + Expr::Exists(Exists { subquery, negated }) => { + let subquery_plan = self + .try_optimize(&subquery.subquery, config)? + .map(Arc::new) + .unwrap_or_else(|| subquery.subquery.clone()); + let new_subquery = subquery.with_plan(subquery_plan); + subqueries.push(SubqueryInfo::new(new_subquery, *negated)); + } + _ => others.push((*it).clone()), + } + } + + Ok((subqueries, others)) + } +} + +impl OptimizerRule for DecorrelateWhereExists { + fn try_optimize( + &self, + plan: &LogicalPlan, + config: &dyn OptimizerConfig, + ) -> Result> { + match plan { + LogicalPlan::Filter(filter) => { + let (subqueries, other_exprs) = + self.extract_subquery_exprs(&filter.predicate, config)?; + if subqueries.is_empty() { + // regular filter, no subquery exists clause here + return Ok(None); + } + + // iterate through all exists clauses in predicate, turning each into a join + let mut cur_input = filter.input.as_ref().clone(); + for subquery in subqueries { + if let Some(x) = optimize_exists(&subquery, &cur_input)? { + cur_input = x; + } else { + return Ok(None); + } + } + + let expr = conjunction(other_exprs); + if let Some(expr) = expr { + let new_filter = Filter::try_new(expr, Arc::new(cur_input))?; + cur_input = LogicalPlan::Filter(new_filter); + } + + Ok(Some(cur_input)) + } + _ => Ok(None), + } + } + + fn name(&self) -> &str { + "decorrelate_where_exists" + } + + fn apply_order(&self) -> Option { + Some(ApplyOrder::TopDown) + } +} + +/// Takes a query like: +/// +/// SELECT t1.id +/// FROM t1 +/// WHERE exists +/// ( +/// SELECT t2.id FROM t2 WHERE t1.id = t2.id +/// ) +/// +/// and optimizes it into: +/// +/// SELECT t1.id +/// FROM t1 LEFT SEMI +/// JOIN t2 +/// ON t1.id = t2.id +/// +/// # Arguments +/// +/// * query_info - The subquery and negated(exists/not exists) info. +/// * outer_input - The non-subquery portion (relation t1) +fn optimize_exists( + query_info: &SubqueryInfo, + outer_input: &LogicalPlan, +) -> Result> { + let subquery = query_info.query.subquery.as_ref(); + if let Some((join_filter, optimized_subquery)) = optimize_subquery(subquery)? { + // join our sub query into the main plan + let join_type = match query_info.negated { + true => JoinType::LeftAnti, + false => JoinType::LeftSemi, + }; + + let new_plan = LogicalPlanBuilder::from(outer_input.clone()) + .join( + optimized_subquery, + join_type, + (Vec::::new(), Vec::::new()), + Some(join_filter), + )? + .build()?; + + Ok(Some(new_plan)) + } else { + Ok(None) + } +} +/// Optimize the subquery and extract the possible join filter. +/// This function can't optimize non-correlated subquery, and will return None. +fn optimize_subquery(subquery: &LogicalPlan) -> Result> { + match subquery { + LogicalPlan::Distinct(subqry_distinct) => { + let distinct_input = &subqry_distinct.input; + let optimized_plan = optimize_subquery(distinct_input)?.map(|(filters, right)| { + ( + filters, + LogicalPlan::Distinct(Distinct { + input: Arc::new(right), + }), + ) + }); + Ok(optimized_plan) + } + LogicalPlan::Projection(projection) => { + // extract join filters + let (join_filters, subquery_input) = extract_join_filters(&projection.input)?; + // cannot optimize non-correlated subquery + if join_filters.is_empty() { + return Ok(None); + } + let input_schema = subquery_input.schema(); + let project_exprs: Vec = + collect_subquery_cols(&join_filters, input_schema.clone())? + .into_iter() + .map(Expr::Column) + .collect(); + let right = LogicalPlanBuilder::from(subquery_input) + .project(project_exprs)? + .build()?; + + // join_filters is not empty. + let join_filter = conjunction(join_filters).ok_or_else(|| { + DataFusionError::Internal("join filters should not be empty".to_string()) + })?; + Ok(Some((join_filter, right))) + } + _ => Ok(None), + } +} + +struct SubqueryInfo { + query: Subquery, + negated: bool, +} + +impl SubqueryInfo { + pub fn new(query: Subquery, negated: bool) -> Self { + Self { query, negated } + } +} diff --git a/src/sql/optimizer/decorrelate_where_in.rs b/src/sql/optimizer/decorrelate_where_in.rs new file mode 100644 index 000000000..014f22092 --- /dev/null +++ b/src/sql/optimizer/decorrelate_where_in.rs @@ -0,0 +1,258 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::sync::Arc; + +use datafusion_python::{ + datafusion_common::{alias::AliasGenerator, context, Column, Result}, + datafusion_expr::{ + expr::InSubquery, + expr_rewriter::unnormalize_col, + logical_plan::{JoinType, Projection, Subquery}, + Expr, + Filter, + LogicalPlan, + LogicalPlanBuilder, + }, + datafusion_optimizer::optimizer::{ApplyOrder, OptimizerConfig, OptimizerRule}, +}; +use log::debug; + +use crate::sql::optimizer::utils::{ + collect_subquery_cols, + conjunction, + extract_join_filters, + only_or_err, + replace_qualified_name, + split_conjunction, +}; + +#[derive(Default)] +pub struct DecorrelateWhereIn { + alias: AliasGenerator, +} + +impl DecorrelateWhereIn { + #[allow(missing_docs)] + pub fn new() -> Self { + Self::default() + } + + /// Finds expressions that have a where in subquery (and recurses when found) + /// + /// # Arguments + /// + /// * `predicate` - A conjunction to split and search + /// * `optimizer_config` - For generating unique subquery aliases + /// + /// Returns a tuple (subqueries, non-subquery expressions) + fn extract_subquery_exprs( + &self, + predicate: &Expr, + config: &dyn OptimizerConfig, + ) -> Result<(Vec, Vec)> { + let filters = split_conjunction(predicate); // TODO: disjunctions + + let mut subqueries = vec![]; + let mut others = vec![]; + for it in filters.iter() { + match it { + Expr::InSubquery(InSubquery { + expr, + subquery, + negated, + }) => { + let subquery_plan = self + .try_optimize(&subquery.subquery, config)? + .map(Arc::new) + .unwrap_or_else(|| subquery.subquery.clone()); + let new_subquery = subquery.with_plan(subquery_plan); + subqueries.push(SubqueryInfo::new(new_subquery, (**expr).clone(), *negated)); + // TODO: if subquery doesn't get optimized, optimized children are lost + } + _ => others.push((*it).clone()), + } + } + + Ok((subqueries, others)) + } +} + +impl OptimizerRule for DecorrelateWhereIn { + fn try_optimize( + &self, + plan: &LogicalPlan, + config: &dyn OptimizerConfig, + ) -> Result> { + match plan { + LogicalPlan::Filter(filter) => { + let (subqueries, other_exprs) = + self.extract_subquery_exprs(&filter.predicate, config)?; + if subqueries.is_empty() { + // regular filter, no subquery exists clause here + return Ok(None); + } + + // iterate through all exists clauses in predicate, turning each into a join + let mut cur_input = filter.input.as_ref().clone(); + for subquery in subqueries { + cur_input = optimize_where_in(&subquery, &cur_input, &self.alias)?; + } + + let expr = conjunction(other_exprs); + if let Some(expr) = expr { + let new_filter = Filter::try_new(expr, Arc::new(cur_input))?; + cur_input = LogicalPlan::Filter(new_filter); + } + + Ok(Some(cur_input)) + } + _ => Ok(None), + } + } + + fn name(&self) -> &str { + "decorrelate_where_in" + } + + fn apply_order(&self) -> Option { + Some(ApplyOrder::TopDown) + } +} + +/// Optimize the where in subquery to left-anti/left-semi join. +/// If the subquery is a correlated subquery, we need extract the join predicate from the subquery. +/// +/// For example, given a query like: +/// `select t1.a, t1.b from t1 where t1 in (select t2.a from t2 where t1.b = t2.b and t1.c > t2.c)` +/// +/// The optimized plan will be: +/// +/// ```text +/// Projection: t1.a, t1.b +/// LeftSemi Join: Filter: t1.a = __correlated_sq_1.a AND t1.b = __correlated_sq_1.b AND t1.c > __correlated_sq_1.c +/// TableScan: t1 +/// SubqueryAlias: __correlated_sq_1 +/// Projection: t2.a AS a, t2.b, t2.c +/// TableScan: t2 +/// ``` +fn optimize_where_in( + query_info: &SubqueryInfo, + left: &LogicalPlan, + alias: &AliasGenerator, +) -> Result { + let projection = Projection::try_from_plan(&query_info.query.subquery) + .map_err(|e| context!("a projection is required", e))?; + let subquery_input = projection.input.clone(); + // TODO add the validate logic to Analyzer + let subquery_expr = only_or_err(projection.expr.as_slice()) + .map_err(|e| context!("single expression projection required", e))?; + + // extract join filters + let (join_filters, subquery_input) = extract_join_filters(subquery_input.as_ref())?; + + // in_predicate may be also include in the join filters, remove it from the join filters. + let in_predicate = Expr::eq(query_info.where_in_expr.clone(), subquery_expr.clone()); + let join_filters = remove_duplicated_filter(join_filters, in_predicate); + + // replace qualified name with subquery alias. + let subquery_alias = alias.next("__correlated_sq"); + let input_schema = subquery_input.schema(); + let mut subquery_cols = collect_subquery_cols(&join_filters, input_schema.clone())?; + let join_filter = conjunction(join_filters).map_or(Ok(None), |filter| { + replace_qualified_name(filter, &subquery_cols, &subquery_alias).map(Option::Some) + })?; + + // add projection + if let Expr::Column(col) = subquery_expr { + subquery_cols.remove(col); + } + let subquery_expr_name = format!("{:?}", unnormalize_col(subquery_expr.clone())); + let first_expr = subquery_expr.clone().alias(subquery_expr_name.clone()); + let projection_exprs: Vec = [first_expr] + .into_iter() + .chain(subquery_cols.into_iter().map(Expr::Column)) + .collect(); + + let right = LogicalPlanBuilder::from(subquery_input) + .project(projection_exprs)? + .alias(subquery_alias.clone())? + .build()?; + + // join our sub query into the main plan + let join_type = match query_info.negated { + true => JoinType::LeftAnti, + false => JoinType::LeftSemi, + }; + let right_join_col = Column::new(Some(subquery_alias), subquery_expr_name); + let in_predicate = Expr::eq( + query_info.where_in_expr.clone(), + Expr::Column(right_join_col), + ); + let join_filter = join_filter + .map(|filter| in_predicate.clone().and(filter)) + .unwrap_or_else(|| in_predicate); + + let new_plan = LogicalPlanBuilder::from(left.clone()) + .join( + right, + join_type, + (Vec::::new(), Vec::::new()), + Some(join_filter), + )? + .build()?; + + debug!("where in optimized:\n{}", new_plan.display_indent()); + Ok(new_plan) +} + +fn remove_duplicated_filter(filters: Vec, in_predicate: Expr) -> Vec { + filters + .into_iter() + .filter(|filter| { + if filter == &in_predicate { + return false; + } + + // ignore the binary order + !match (filter, &in_predicate) { + (Expr::BinaryExpr(a_expr), Expr::BinaryExpr(b_expr)) => { + (a_expr.op == b_expr.op) + && (a_expr.left == b_expr.left && a_expr.right == b_expr.right) + || (a_expr.left == b_expr.right && a_expr.right == b_expr.left) + } + _ => false, + } + }) + .collect::>() +} + +struct SubqueryInfo { + query: Subquery, + where_in_expr: Expr, + negated: bool, +} + +impl SubqueryInfo { + pub fn new(query: Subquery, expr: Expr, negated: bool) -> Self { + Self { + query, + where_in_expr: expr, + negated, + } + } +} diff --git a/dask_planner/src/sql/optimizer/dynamic_partition_pruning.rs b/src/sql/optimizer/dynamic_partition_pruning.rs similarity index 98% rename from dask_planner/src/sql/optimizer/dynamic_partition_pruning.rs rename to src/sql/optimizer/dynamic_partition_pruning.rs index 0ff48a682..d7e1a8be5 100644 --- a/dask_planner/src/sql/optimizer/dynamic_partition_pruning.rs +++ b/src/sql/optimizer/dynamic_partition_pruning.rs @@ -22,6 +22,7 @@ use datafusion_python::{ }, datafusion_common::{Column, Result, ScalarValue}, datafusion_expr::{ + expr::InList, logical_plan::LogicalPlan, utils::from_plan, Expr, @@ -433,13 +434,13 @@ fn gather_aliases(plan: &LogicalPlan) -> HashMap { if let LogicalPlan::SubqueryAlias(ref s) = current_plan { match *s.input { LogicalPlan::TableScan(ref t) => { - aliases.insert(s.alias.clone(), t.table_name.to_string().clone()); + aliases.insert(s.alias.to_string(), t.table_name.to_string().clone()); } // Sometimes a TableScan is immediately followed by a Projection, so we can // still use the alias for the table LogicalPlan::Projection(ref p) => { if let LogicalPlan::TableScan(ref t) = *p.input { - aliases.insert(s.alias.clone(), t.table_name.to_string().clone()); + aliases.insert(s.alias.to_string(), t.table_name.to_string().clone()); } } _ => (), @@ -536,7 +537,7 @@ fn read_table( .project(projection.clone()) .ok(); if let Some(row_iter) = row_iter_result { - rows.extend(row_iter); + rows.extend(row_iter.map(|r| r.expect("Parquet error encountered"))); } else { // TODO: Investigate cases when this would happen rows.clear(); @@ -781,6 +782,9 @@ fn satisfies_int64(long_value: Option, filter: Expr) -> bool { Expr::Literal(ScalarValue::Int32(i)) => i64::from(i.unwrap()), Expr::Literal(ScalarValue::Float64(i)) => i.unwrap() as i64, Expr::Literal(ScalarValue::TimestampNanosecond(i, None)) => i.unwrap(), + Expr::Literal(ScalarValue::Date32(i)) => i64::from(i.unwrap()), + // TODO: Add logic to check if the string can be converted to a timestamp + Expr::Literal(ScalarValue::Utf8(_)) => return false, _ => { panic!("Unknown ScalarValue type {filter_value}"); } @@ -1053,11 +1057,11 @@ fn format_inlist_expr( if list.is_empty() { None } else { - Some(Expr::InList { + Some(Expr::InList(InList { expr, list, negated: false, - }) + })) } } diff --git a/dask_planner/src/sql/optimizer/join_reorder.rs b/src/sql/optimizer/join_reorder.rs similarity index 100% rename from dask_planner/src/sql/optimizer/join_reorder.rs rename to src/sql/optimizer/join_reorder.rs diff --git a/src/sql/optimizer/utils.rs b/src/sql/optimizer/utils.rs new file mode 100644 index 000000000..f72bbe5c3 --- /dev/null +++ b/src/sql/optimizer/utils.rs @@ -0,0 +1,516 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Collection of utility functions that are leveraged by the query optimizer rules + +use std::{ + collections::{BTreeSet, HashMap}, + sync::Arc, +}; + +use datafusion_python::{ + datafusion_common::{Column, DFSchema, DFSchemaRef, Result}, + datafusion_expr::{ + and, + expr::{Alias, BinaryExpr}, + expr_rewriter::{replace_col, strip_outer_reference}, + logical_plan::{Filter, LogicalPlan}, + Expr, + LogicalPlanBuilder, + Operator, + }, + datafusion_optimizer::optimizer::{OptimizerConfig, OptimizerRule}, +}; +use log::{debug, trace}; + +#[allow(dead_code)] +/// Convenience rule for writing optimizers: recursively invoke +/// optimize on plan's children and then return a node of the same +/// type. Useful for optimizer rules which want to leave the type +/// of plan unchanged but still apply to the children. +/// This also handles the case when the `plan` is a [`LogicalPlan::Explain`]. +/// +/// Returning `Ok(None)` indicates that the plan can't be optimized by the `optimizer`. +pub fn optimize_children( + optimizer: &impl OptimizerRule, + plan: &LogicalPlan, + config: &dyn OptimizerConfig, +) -> Result> { + let mut new_inputs = Vec::with_capacity(plan.inputs().len()); + let mut plan_is_changed = false; + for input in plan.inputs() { + let new_input = optimizer.try_optimize(input, config)?; + plan_is_changed = plan_is_changed || new_input.is_some(); + new_inputs.push(new_input.unwrap_or_else(|| input.clone())) + } + if plan_is_changed { + Ok(Some(plan.with_new_inputs(&new_inputs)?)) + } else { + Ok(None) + } +} + +/// Splits a conjunctive [`Expr`] such as `A AND B AND C` => `[A, B, C]` +/// +/// See [`split_conjunction_owned`] for more details and an example. +pub fn split_conjunction(expr: &Expr) -> Vec<&Expr> { + split_conjunction_impl(expr, vec![]) +} + +fn split_conjunction_impl<'a>(expr: &'a Expr, mut exprs: Vec<&'a Expr>) -> Vec<&'a Expr> { + match expr { + Expr::BinaryExpr(BinaryExpr { + right, + op: Operator::And, + left, + }) => { + let exprs = split_conjunction_impl(left, exprs); + split_conjunction_impl(right, exprs) + } + Expr::Alias(Alias { expr, .. }) => split_conjunction_impl(expr, exprs), + other => { + exprs.push(other); + exprs + } + } +} + +/// Extract join predicates from the correclated subquery. +/// The join predicate means that the expression references columns +/// from both the subquery and outer table or only from the outer table. +/// +/// Returns join predicates and subquery(extracted). +pub(crate) fn extract_join_filters(maybe_filter: &LogicalPlan) -> Result<(Vec, LogicalPlan)> { + if let LogicalPlan::Filter(plan_filter) = maybe_filter { + let subquery_filter_exprs = split_conjunction(&plan_filter.predicate); + let (join_filters, subquery_filters) = find_join_exprs(subquery_filter_exprs)?; + // if the subquery still has filter expressions, restore them. + let mut plan = LogicalPlanBuilder::from((*plan_filter.input).clone()); + if let Some(expr) = conjunction(subquery_filters) { + plan = plan.filter(expr)? + } + + Ok((join_filters, plan.build()?)) + } else { + Ok((vec![], maybe_filter.clone())) + } +} + +#[allow(dead_code)] +/// Splits an owned conjunctive [`Expr`] such as `A AND B AND C` => `[A, B, C]` +/// +/// This is often used to "split" filter expressions such as `col1 = 5 +/// AND col2 = 10` into [`col1 = 5`, `col2 = 10`]; +/// +/// # Example +/// ``` +/// # use datafusion_python::datafusion_expr::{col, lit}; +/// # use datafusion_python::datafusion_optimizer::utils::split_conjunction_owned; +/// // a=1 AND b=2 +/// let expr = col("a").eq(lit(1)).and(col("b").eq(lit(2))); +/// +/// // [a=1, b=2] +/// let split = vec![ +/// col("a").eq(lit(1)), +/// col("b").eq(lit(2)), +/// ]; +/// +/// // use split_conjunction_owned to split them +/// assert_eq!(split_conjunction_owned(expr), split); +/// ``` +pub fn split_conjunction_owned(expr: Expr) -> Vec { + split_binary_owned(expr, Operator::And) +} + +#[allow(dead_code)] +/// Splits an owned binary operator tree [`Expr`] such as `A B C` => `[A, B, C]` +/// +/// This is often used to "split" expressions such as `col1 = 5 +/// AND col2 = 10` into [`col1 = 5`, `col2 = 10`]; +/// +/// # Example +/// ``` +/// # use datafusion_python::datafusion_expr::{col, lit, Operator}; +/// # use datafusion_python::datafusion_optimizer::utils::split_binary_owned; +/// # use std::ops::Add; +/// // a=1 + b=2 +/// let expr = col("a").eq(lit(1)).add(col("b").eq(lit(2))); +/// +/// // [a=1, b=2] +/// let split = vec![ +/// col("a").eq(lit(1)), +/// col("b").eq(lit(2)), +/// ]; +/// +/// // use split_binary_owned to split them +/// assert_eq!(split_binary_owned(expr, Operator::Plus), split); +/// ``` +pub fn split_binary_owned(expr: Expr, op: Operator) -> Vec { + split_binary_owned_impl(expr, op, vec![]) +} + +#[allow(dead_code)] +fn split_binary_owned_impl(expr: Expr, operator: Operator, mut exprs: Vec) -> Vec { + match expr { + Expr::BinaryExpr(BinaryExpr { right, op, left }) if op == operator => { + let exprs = split_binary_owned_impl(*left, operator, exprs); + split_binary_owned_impl(*right, operator, exprs) + } + Expr::Alias(Alias { expr, .. }) => split_binary_owned_impl(*expr, operator, exprs), + other => { + exprs.push(other); + exprs + } + } +} + +#[allow(dead_code)] +/// Splits an binary operator tree [`Expr`] such as `A B C` => `[A, B, C]` +/// +/// See [`split_binary_owned`] for more details and an example. +pub fn split_binary(expr: &Expr, op: Operator) -> Vec<&Expr> { + split_binary_impl(expr, op, vec![]) +} + +#[allow(dead_code)] +fn split_binary_impl<'a>( + expr: &'a Expr, + operator: Operator, + mut exprs: Vec<&'a Expr>, +) -> Vec<&'a Expr> { + match expr { + Expr::BinaryExpr(BinaryExpr { right, op, left }) if *op == operator => { + let exprs = split_binary_impl(left, operator, exprs); + split_binary_impl(right, operator, exprs) + } + Expr::Alias(Alias { expr, .. }) => split_binary_impl(expr, operator, exprs), + other => { + exprs.push(other); + exprs + } + } +} + +/// Combines an array of filter expressions into a single filter +/// expression consisting of the input filter expressions joined with +/// logical AND. +/// +/// Returns None if the filters array is empty. +/// +/// # Example +/// ``` +/// # use datafusion_python::datafusion_expr::{col, lit}; +/// # use datafusion_python::datafusion_optimizer::utils::conjunction; +/// // a=1 AND b=2 +/// let expr = col("a").eq(lit(1)).and(col("b").eq(lit(2))); +/// +/// // [a=1, b=2] +/// let split = vec![ +/// col("a").eq(lit(1)), +/// col("b").eq(lit(2)), +/// ]; +/// +/// // use conjunction to join them together with `AND` +/// assert_eq!(conjunction(split), Some(expr)); +/// ``` +pub fn conjunction(filters: impl IntoIterator) -> Option { + filters.into_iter().reduce(|accum, expr| accum.and(expr)) +} + +#[allow(dead_code)] +/// Combines an array of filter expressions into a single filter +/// expression consisting of the input filter expressions joined with +/// logical OR. +/// +/// Returns None if the filters array is empty. +pub fn disjunction(filters: impl IntoIterator) -> Option { + filters.into_iter().reduce(|accum, expr| accum.or(expr)) +} + +/// returns a new [LogicalPlan] that wraps `plan` in a [LogicalPlan::Filter] with +/// its predicate be all `predicates` ANDed. +#[allow(dead_code)] +pub fn add_filter(plan: LogicalPlan, predicates: &[&Expr]) -> Result { + // reduce filters to a single filter with an AND + let predicate = predicates + .iter() + .skip(1) + .fold(predicates[0].clone(), |acc, predicate| { + and(acc, (*predicate).to_owned()) + }); + + Ok(LogicalPlan::Filter(Filter::try_new( + predicate, + Arc::new(plan), + )?)) +} + +/// Looks for correlating expressions: for example, a binary expression with one field from the subquery, and +/// one not in the subquery (closed upon from outer scope) +/// +/// # Arguments +/// +/// * `exprs` - List of expressions that may or may not be joins +/// +/// # Return value +/// +/// Tuple of (expressions containing joins, remaining non-join expressions) +pub fn find_join_exprs(exprs: Vec<&Expr>) -> Result<(Vec, Vec)> { + let mut joins = vec![]; + let mut others = vec![]; + for filter in exprs.into_iter() { + // If the expression contains correlated predicates, add it to join filters + if filter.contains_outer() { + if !matches!(filter, Expr::BinaryExpr(BinaryExpr{ left, op: Operator::Eq, right }) if left.eq(right)) + { + joins.push(strip_outer_reference((*filter).clone())); + } + } else { + others.push((*filter).clone()); + } + } + + Ok((joins, others)) +} + +/// Returns the first (and only) element in a slice, or an error +/// +/// # Arguments +/// +/// * `slice` - The slice to extract from +/// +/// # Return value +/// +/// The first element, or an error +pub fn only_or_err(slice: &[T]) -> Result<&T> { + match slice { + [it] => Ok(it), + [] => Err(datafusion_python::datafusion_common::DataFusionError::Plan( + "No items found!".to_owned(), + )), + _ => Err(datafusion_python::datafusion_common::DataFusionError::Plan( + "More than one item found!".to_owned(), + )), + } +} + +/// merge inputs schema into a single schema. +#[allow(dead_code)] +pub fn merge_schema(inputs: Vec<&LogicalPlan>) -> DFSchema { + if inputs.len() == 1 { + inputs[0].schema().clone().as_ref().clone() + } else { + inputs + .iter() + .map(|input| input.schema()) + .fold(DFSchema::empty(), |mut lhs, rhs| { + lhs.merge(rhs); + lhs + }) + } +} + +pub(crate) fn collect_subquery_cols( + exprs: &[Expr], + subquery_schema: DFSchemaRef, +) -> Result> { + exprs.iter().try_fold(BTreeSet::new(), |mut cols, expr| { + let mut using_cols: Vec = vec![]; + for col in expr.to_columns()?.into_iter() { + if subquery_schema.has_column(&col) { + using_cols.push(col); + } + } + + cols.extend(using_cols); + Result::<_>::Ok(cols) + }) +} + +pub(crate) fn replace_qualified_name( + expr: Expr, + cols: &BTreeSet, + subquery_alias: &str, +) -> Result { + let alias_cols: Vec = cols + .iter() + .map(|col| Column::from_qualified_name(format!("{}.{}", subquery_alias, col.name))) + .collect(); + let replace_map: HashMap<&Column, &Column> = cols.iter().zip(alias_cols.iter()).collect(); + + replace_col(expr, &replace_map) +} + +#[allow(dead_code)] +/// Log the plan in debug/tracing mode after some part of the optimizer runs +pub fn log_plan(description: &str, plan: &LogicalPlan) { + debug!("{description}:\n{}\n", plan.display_indent()); + trace!("{description}::\n{}\n", plan.display_indent_schema()); +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use datafusion_python::{ + datafusion::arrow::datatypes::DataType, + datafusion_common::Column, + datafusion_expr::{col, expr::Cast, lit, utils::expr_to_columns}, + }; + + use super::*; + + #[test] + fn test_split_conjunction() { + let expr = col("a"); + let result = split_conjunction(&expr); + assert_eq!(result, vec![&expr]); + } + + #[test] + fn test_split_conjunction_two() { + let expr = col("a").eq(lit(5)).and(col("b")); + let expr1 = col("a").eq(lit(5)); + let expr2 = col("b"); + + let result = split_conjunction(&expr); + assert_eq!(result, vec![&expr1, &expr2]); + } + + #[test] + fn test_split_conjunction_alias() { + let expr = col("a").eq(lit(5)).and(col("b").alias("the_alias")); + let expr1 = col("a").eq(lit(5)); + let expr2 = col("b"); // has no alias + + let result = split_conjunction(&expr); + assert_eq!(result, vec![&expr1, &expr2]); + } + + #[test] + fn test_split_conjunction_or() { + let expr = col("a").eq(lit(5)).or(col("b")); + let result = split_conjunction(&expr); + assert_eq!(result, vec![&expr]); + } + + #[test] + fn test_split_binary_owned() { + let expr = col("a"); + assert_eq!(split_binary_owned(expr.clone(), Operator::And), vec![expr]); + } + + #[test] + fn test_split_binary_owned_two() { + assert_eq!( + split_binary_owned(col("a").eq(lit(5)).and(col("b")), Operator::And), + vec![col("a").eq(lit(5)), col("b")] + ); + } + + #[test] + fn test_split_binary_owned_different_op() { + let expr = col("a").eq(lit(5)).or(col("b")); + assert_eq!( + // expr is connected by OR, but pass in AND + split_binary_owned(expr.clone(), Operator::And), + vec![expr] + ); + } + + #[test] + fn test_split_conjunction_owned() { + let expr = col("a"); + assert_eq!(split_conjunction_owned(expr.clone()), vec![expr]); + } + + #[test] + fn test_split_conjunction_owned_two() { + assert_eq!( + split_conjunction_owned(col("a").eq(lit(5)).and(col("b"))), + vec![col("a").eq(lit(5)), col("b")] + ); + } + + #[test] + fn test_split_conjunction_owned_alias() { + assert_eq!( + split_conjunction_owned(col("a").eq(lit(5)).and(col("b").alias("the_alias"))), + vec![ + col("a").eq(lit(5)), + // no alias on b + col("b"), + ] + ); + } + + #[test] + fn test_conjunction_empty() { + assert_eq!(conjunction(vec![]), None); + } + + #[test] + fn test_conjunction() { + // `[A, B, C]` + let expr = conjunction(vec![col("a"), col("b"), col("c")]); + + // --> `(A AND B) AND C` + assert_eq!(expr, Some(col("a").and(col("b")).and(col("c")))); + + // which is different than `A AND (B AND C)` + assert_ne!(expr, Some(col("a").and(col("b").and(col("c"))))); + } + + #[test] + fn test_disjunction_empty() { + assert_eq!(disjunction(vec![]), None); + } + + #[test] + fn test_disjunction() { + // `[A, B, C]` + let expr = disjunction(vec![col("a"), col("b"), col("c")]); + + // --> `(A OR B) OR C` + assert_eq!(expr, Some(col("a").or(col("b")).or(col("c")))); + + // which is different than `A OR (B OR C)` + assert_ne!(expr, Some(col("a").or(col("b").or(col("c"))))); + } + + #[test] + fn test_split_conjunction_owned_or() { + let expr = col("a").eq(lit(5)).or(col("b")); + assert_eq!(split_conjunction_owned(expr.clone()), vec![expr]); + } + + #[test] + fn test_collect_expr() -> Result<()> { + let mut accum: HashSet = HashSet::new(); + expr_to_columns( + &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64)), + &mut accum, + )?; + expr_to_columns( + &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64)), + &mut accum, + )?; + assert_eq!(1, accum.len()); + assert!(accum.contains(&Column::from_name("a"))); + Ok(()) + } +} diff --git a/dask_planner/src/sql/parser_utils.rs b/src/sql/parser_utils.rs similarity index 100% rename from dask_planner/src/sql/parser_utils.rs rename to src/sql/parser_utils.rs diff --git a/dask_planner/src/sql/schema.rs b/src/sql/schema.rs similarity index 95% rename from dask_planner/src/sql/schema.rs rename to src/sql/schema.rs index 0975391f4..804db700f 100644 --- a/dask_planner/src/sql/schema.rs +++ b/src/sql/schema.rs @@ -6,7 +6,7 @@ use pyo3::prelude::*; use super::types::PyDataType; use crate::sql::{function::DaskFunction, table}; -#[pyclass(name = "DaskSchema", module = "dask_planner", subclass)] +#[pyclass(name = "DaskSchema", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct DaskSchema { #[pyo3(get, set)] diff --git a/dask_planner/src/sql/statement.rs b/src/sql/statement.rs similarity index 88% rename from dask_planner/src/sql/statement.rs rename to src/sql/statement.rs index f8fabc109..40fc9f268 100644 --- a/dask_planner/src/sql/statement.rs +++ b/src/sql/statement.rs @@ -2,7 +2,7 @@ use pyo3::prelude::*; use crate::parser::DaskStatement; -#[pyclass(name = "Statement", module = "dask_planner", subclass)] +#[pyclass(name = "Statement", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct PyStatement { pub statement: DaskStatement, diff --git a/dask_planner/src/sql/table.rs b/src/sql/table.rs similarity index 97% rename from dask_planner/src/sql/table.rs rename to src/sql/table.rs index abe71733a..1c2585bef 100644 --- a/dask_planner/src/sql/table.rs +++ b/src/sql/table.rs @@ -2,7 +2,7 @@ use std::{any::Any, sync::Arc}; use async_trait::async_trait; use datafusion_python::{ - datafusion::arrow::datatypes::{DataType, Field, SchemaRef}, + datafusion::arrow::datatypes::{DataType, Fields, SchemaRef}, datafusion_common::DFField, datafusion_expr::{Expr, LogicalPlan, TableProviderFilterPushDown, TableSource}, datafusion_optimizer::utils::split_conjunction, @@ -90,7 +90,7 @@ fn is_supported_push_down_expr(_expr: &Expr) -> bool { true } -#[pyclass(name = "DaskStatistics", module = "dask_planner", subclass)] +#[pyclass(name = "DaskStatistics", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct DaskStatistics { row_count: f64, @@ -109,7 +109,7 @@ impl DaskStatistics { } } -#[pyclass(name = "DaskTable", module = "dask_planner", subclass)] +#[pyclass(name = "DaskTable", module = "dask_sql", subclass)] #[derive(Debug, Clone)] pub struct DaskTable { pub(crate) schema_name: Option, @@ -194,7 +194,7 @@ pub(crate) fn table_from_logical_plan( // Get the TableProvider for this Table instance let tbl_provider: Arc = table_scan.source.clone(); let tbl_schema: SchemaRef = tbl_provider.schema(); - let fields: &Vec = tbl_schema.fields(); + let fields: &Fields = tbl_schema.fields(); let mut cols: Vec<(String, DaskTypeMap)> = Vec::new(); for field in fields { diff --git a/dask_planner/src/sql/types.rs b/src/sql/types.rs similarity index 95% rename from dask_planner/src/sql/types.rs rename to src/sql/types.rs index ceff904a6..34af22342 100644 --- a/dask_planner/src/sql/types.rs +++ b/src/sql/types.rs @@ -1,6 +1,8 @@ pub mod rel_data_type; pub mod rel_data_type_field; +use std::sync::Arc; + use datafusion_python::{ datafusion::arrow::datatypes::{DataType, IntervalUnit, TimeUnit}, datafusion_sql::sqlparser::{ast::DataType as SQLType, parser::Parser, tokenizer::Tokenizer}, @@ -10,7 +12,7 @@ use pyo3::{prelude::*, types::PyDict}; use crate::{dialect::DaskDialect, error::DaskPlannerError, sql::exceptions::py_type_err}; #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[pyclass(name = "RexType", module = "datafusion")] +#[pyclass(name = "RexType", module = "dask_sql")] pub enum RexType { Alias, Literal, @@ -21,7 +23,7 @@ pub enum RexType { } #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[pyclass(name = "DaskTypeMap", module = "datafusion", subclass)] +#[pyclass(name = "DaskTypeMap", module = "dask_sql", subclass)] /// Represents a Python Data Type. This is needed instead of simple /// Enum instances because PyO3 can only support unit variants as /// of version 0.16 which means Enums like `DataType::TIMESTAMP_WITH_LOCAL_TIME_ZONE` @@ -54,10 +56,12 @@ impl DaskTypeMap { SqlTypeName::TIMESTAMP_WITH_LOCAL_TIME_ZONE => { let (unit, tz) = match py_kwargs { Some(dict) => { - let tz: Option = match dict.get_item("tz") { + let tz: Option> = match dict.get_item("tz") { Some(e) => { let res: PyResult = e.extract(); - Some(res.unwrap()) + Some(Arc::from(>::as_ref( + &res.unwrap(), + ))) } None => None, }; @@ -85,10 +89,12 @@ impl DaskTypeMap { SqlTypeName::TIMESTAMP => { let (unit, tz) = match py_kwargs { Some(dict) => { - let tz: Option = match dict.get_item("tz") { + let tz: Option> = match dict.get_item("tz") { Some(e) => { let res: PyResult = e.extract(); - Some(res.unwrap()) + Some(Arc::from(>::as_ref( + &res.unwrap(), + ))) } None => None, }; @@ -161,7 +167,7 @@ impl DaskTypeMap { } #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[pyclass(name = "PyDataType", module = "datafusion", subclass)] +#[pyclass(name = "PyDataType", module = "dask_sql", subclass)] pub struct PyDataType { data_type: DataType, } @@ -204,7 +210,7 @@ impl From for PyDataType { #[allow(non_camel_case_types)] #[allow(clippy::upper_case_acronyms)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[pyclass(name = "SqlTypeName", module = "datafusion")] +#[pyclass(name = "SqlTypeName", module = "dask_sql")] pub enum SqlTypeName { ANY, ARRAY, diff --git a/dask_planner/src/sql/types/rel_data_type.rs b/src/sql/types/rel_data_type.rs similarity index 98% rename from dask_planner/src/sql/types/rel_data_type.rs rename to src/sql/types/rel_data_type.rs index 1ae3646b0..59cb0fb7c 100644 --- a/dask_planner/src/sql/types/rel_data_type.rs +++ b/src/sql/types/rel_data_type.rs @@ -8,7 +8,7 @@ const PRECISION_NOT_SPECIFIED: i32 = i32::MIN; const SCALE_NOT_SPECIFIED: i32 = -1; /// RelDataType represents the type of a scalar expression or entire row returned from a relational expression. -#[pyclass(name = "RelDataType", module = "dask_planner", subclass)] +#[pyclass(name = "RelDataType", module = "dask_sql", subclass)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RelDataType { nullable: bool, diff --git a/dask_planner/src/sql/types/rel_data_type_field.rs b/src/sql/types/rel_data_type_field.rs similarity index 98% rename from dask_planner/src/sql/types/rel_data_type_field.rs rename to src/sql/types/rel_data_type_field.rs index 13f036d0e..3694d0bce 100644 --- a/dask_planner/src/sql/types/rel_data_type_field.rs +++ b/src/sql/types/rel_data_type_field.rs @@ -12,7 +12,7 @@ use crate::{ }; /// RelDataTypeField represents the definition of a field in a structured RelDataType. -#[pyclass(name = "RelDataTypeField", module = "dask_planner", subclass)] +#[pyclass(name = "RelDataTypeField", module = "dask_sql", subclass)] #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RelDataTypeField { qualifier: Option, diff --git a/tests/integration/test_join.py b/tests/integration/test_join.py index c46cec101..3f19a3211 100644 --- a/tests/integration/test_join.py +++ b/tests/integration/test_join.py @@ -377,7 +377,7 @@ def test_intersect(c): limit 100 """ ) - assert actual_df["COUNT(UInt8(1))"].compute()[0] == 3 + assert actual_df["COUNT(*)"].compute()[0] == 3 # Join df_simple against itself, and then that result against df_wide. Nothing should match so therefore result should be 0 actual_df = c.sql( @@ -392,7 +392,7 @@ def test_intersect(c): limit 100 """ ) - assert len(actual_df["COUNT(UInt8(1))"]) == 0 + assert len(actual_df["COUNT(*)"]) == 0 actual_df = c.sql( """ diff --git a/tests/integration/test_rex.py b/tests/integration/test_rex.py index b49a687d2..e099a3ddb 100644 --- a/tests/integration/test_rex.py +++ b/tests/integration/test_rex.py @@ -407,8 +407,7 @@ def test_coalesce(c, gpu): COALESCE(NULL, 'hi') as c3, COALESCE(NULL, NULL, 'bye', 5/0) as c4, COALESCE(NULL, 3/2, NULL, 'fly') as c5, - COALESCE(SUM(b), 'why', 2.2) as c6, - COALESCE(NULL, MEAN(b), MEAN(a), 4/0) as c7 + COALESCE(NULL, MEAN(b), MEAN(a), 4/0) as c6 FROM df """ ) @@ -419,9 +418,8 @@ def test_coalesce(c, gpu): "c2": [np.nan], "c3": ["hi"], "c4": ["bye"], - "c5": ["1"], - "c6": ["why"], - "c7": [2.0], + "c5": ["1.5"], + "c6": [2.0], } ) diff --git a/tests/integration/test_select.py b/tests/integration/test_select.py index 9c4331d77..53ebdc224 100644 --- a/tests/integration/test_select.py +++ b/tests/integration/test_select.py @@ -272,3 +272,15 @@ def test_multiple_column_projection(c, parquet_ddf, input_cols): "read-parquet", ).columns ) == sorted(input_cols) + + +def test_wildcard_select(c): + result_df = c.sql("SELECT COUNT(*) FROM df") + + expected_df = pd.DataFrame( + { + "COUNT(*)": [700], + } + ) + + assert_eq(result_df, expected_df) diff --git a/tests/unit/test_mapping.py b/tests/unit/test_mapping.py index b49ed1aae..98f065bf8 100644 --- a/tests/unit/test_mapping.py +++ b/tests/unit/test_mapping.py @@ -4,7 +4,7 @@ import pandas as pd import pytest -from dask_planner.rust import SqlTypeName +from dask_sql._datafusion_lib import SqlTypeName from dask_sql.mappings import python_to_sql_type, similar_type, sql_to_python_value diff --git a/tests/unit/test_queries.py b/tests/unit/test_queries.py index 67120df82..bfaedfcee 100644 --- a/tests/unit/test_queries.py +++ b/tests/unit/test_queries.py @@ -4,9 +4,7 @@ XFAIL_QUERIES = ( 5, - 6, 8, - 9, 10, 14, 16, @@ -21,13 +19,10 @@ 39, 41, 44, - 45, 47, 49, 51, - 54, 57, - 58, 62, 67, 69, From 17c1d4ef82862a8aab77fff2212464fa798442b7 Mon Sep 17 00:00:00 2001 From: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Date: Tue, 22 Aug 2023 10:21:33 -0400 Subject: [PATCH 23/25] Use correct path for Rust deps updating script (#1218) --- .github/workflows/rust.yml | 4 ++-- .github/workflows/test-upstream.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a9eeab1ab..9759add1a 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -51,7 +51,7 @@ jobs: - name: Optionally update upstream dependencies if: needs.detect-ci-trigger.outputs.triggered == 'true' run: | - bash update-dependencies.sh + bash continuous_integration/scripts/update-dependencies.sh - name: Install Protoc uses: arduino/setup-protoc@v1 with: @@ -81,7 +81,7 @@ jobs: - name: Optionally update upstream dependencies if: needs.detect-ci-trigger.outputs.triggered == 'true' run: | - bash update-dependencies.sh + bash continuous_integration/scripts/update-dependencies.sh - name: Install Protoc uses: arduino/setup-protoc@v1 with: diff --git a/.github/workflows/test-upstream.yml b/.github/workflows/test-upstream.yml index e6c30bf1a..3c4dce49c 100644 --- a/.github/workflows/test-upstream.yml +++ b/.github/workflows/test-upstream.yml @@ -68,7 +68,7 @@ jobs: - name: Optionally update upstream cargo dependencies if: env.which_upstream == 'DataFusion' run: | - bash update-dependencies.sh + bash continuous_integration/scripts/update-dependencies.sh - name: Build the Rust DataFusion bindings run: | maturin develop @@ -123,7 +123,7 @@ jobs: env: UPDATE_ALL_CARGO_DEPS: false run: | - bash update-dependencies.sh + bash continuous_integration/scripts/update-dependencies.sh - name: Install dependencies and nothing else run: | pip install -e . -vv From d8a4f365fad3e63b8b40067ee0d1ad7abdb05ad8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 22 Aug 2023 15:42:57 -0400 Subject: [PATCH 24/25] Update gpuCI `RAPIDS_VER` to `23.10` (#1204) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> --- continuous_integration/gpuci/axis.yaml | 2 +- continuous_integration/gpuci/environment-3.10.yaml | 10 +++++----- continuous_integration/gpuci/environment-3.9.yaml | 10 +++++----- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/continuous_integration/gpuci/axis.yaml b/continuous_integration/gpuci/axis.yaml index 97a27084e..ea1e6464a 100644 --- a/continuous_integration/gpuci/axis.yaml +++ b/continuous_integration/gpuci/axis.yaml @@ -9,6 +9,6 @@ LINUX_VER: - ubuntu18.04 RAPIDS_VER: -- "23.08" +- "23.10" excludes: diff --git a/continuous_integration/gpuci/environment-3.10.yaml b/continuous_integration/gpuci/environment-3.10.yaml index 6d8372da4..bd572aa56 100644 --- a/continuous_integration/gpuci/environment-3.10.yaml +++ b/continuous_integration/gpuci/environment-3.10.yaml @@ -40,12 +40,12 @@ dependencies: - uvicorn>=0.13.4 # GPU-specific requirements - cudatoolkit=11.5 -- cudf=23.08 -- cuml=23.08 -- dask-cudf=23.08 -- dask-cuda=23.08 +- cudf=23.10 +- cuml=23.10 +- dask-cudf=23.10 +- dask-cuda=23.10 - ucx-proc=*=gpu -- ucx-py=0.33 +- ucx-py=0.34 - xgboost=*=rapidsai_py* - libxgboost=*=rapidsai_h* - zlib diff --git a/continuous_integration/gpuci/environment-3.9.yaml b/continuous_integration/gpuci/environment-3.9.yaml index 52c82a1e2..c9051fda1 100644 --- a/continuous_integration/gpuci/environment-3.9.yaml +++ b/continuous_integration/gpuci/environment-3.9.yaml @@ -40,12 +40,12 @@ dependencies: - uvicorn>=0.13.4 # GPU-specific requirements - cudatoolkit=11.5 -- cudf=23.08 -- cuml=23.08 -- dask-cudf=23.08 -- dask-cuda=23.08 +- cudf=23.10 +- cuml=23.10 +- dask-cudf=23.10 +- dask-cuda=23.10 - ucx-proc=*=gpu -- ucx-py=0.33 +- ucx-py=0.34 - xgboost=*=rapidsai_py* - libxgboost=*=rapidsai_h* - zlib From a71b3eb91485e3e054e57874ad2af07299596a3f Mon Sep 17 00:00:00 2001 From: Charles Blackmon-Luca <20627856+charlesbluca@users.noreply.github.com> Date: Thu, 24 Aug 2023 12:00:08 -0400 Subject: [PATCH 25/25] Fix memory issues in Docker builds (#1219) * Use maturin develop directly from docker builds * Try to recreate OOM errors in CI * Don't load images for now * Split platform builds into separate GHA jobs to reduce memory load * Skip buildx setup for now * Remove QEMU setup for now * Remove QEMU step * Trigger docker builds for changes to setup files --- .github/workflows/docker.yml | 40 +++++++++++++++++++++++++----------- docker/main.dockerfile | 2 +- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index aa2fd6482..cf46ddec0 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,4 +1,4 @@ -name: Upload Docker image +name: Build Docker image on: release: @@ -6,6 +6,14 @@ on: push: branches: - main + pull_request: + paths: + - setup.py + - Cargo.toml + - Cargo.lock + - pyproject.toml + - docker/** + - .github/workflows/docker.yml # When this workflow is queued, automatically cancel any previous running # or pending jobs from the same branch @@ -17,15 +25,16 @@ jobs: push_to_registry: name: Push Docker image to Docker Hub runs-on: ubuntu-latest - if: github.repository == 'dask-contrib/dask-sql' + env: + DOCKER_PUSH: ${{ github.event_name == 'push' && github.repository == 'dask-contrib/dask-sql' }} + strategy: + fail-fast: false + matrix: + platform: ["linux/amd64", "linux/arm64", "linux/386"] steps: - - name: Check out the repo - uses: actions/checkout@v3 - - name: Set up QEMU - uses: docker/setup-qemu-action@v2 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + - uses: actions/checkout@v3 - name: Login to DockerHub + if: ${{ fromJSON(env.DOCKER_PUSH) }} uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_USERNAME }} @@ -41,10 +50,16 @@ jobs: context: . file: ./docker/main.dockerfile build-args: DOCKER_META_VERSION=${{ steps.docker_meta_main.outputs.version }} - platforms: linux/amd64,linux/arm64,linux/386 + platforms: ${{ matrix.platform }} tags: ${{ steps.docker_meta_main.outputs.tags }} labels: ${{ steps.docker_meta_main.outputs.labels }} - push: true + push: ${{ fromJSON(env.DOCKER_PUSH) }} + load: ${{ !fromJSON(env.DOCKER_PUSH) }} + - name: Check images + run: | + df -h + docker image ls + docker image inspect ${{ steps.docker_meta_main.outputs.tags }} - name: Docker meta for cloud image id: docker_meta_cloud uses: crazy-max/ghaction-docker-meta@v4 @@ -56,7 +71,8 @@ jobs: context: . file: ./docker/cloud.dockerfile build-args: DOCKER_META_VERSION=${{ steps.docker_meta_main.outputs.version }} - platforms: linux/amd64,linux/arm64,linux/386 + platforms: ${{ matrix.platform }} tags: ${{ steps.docker_meta_cloud.outputs.tags }} labels: ${{ steps.docker_meta_cloud.outputs.labels }} - push: true + push: ${{ fromJSON(env.DOCKER_PUSH) }} + load: ${{ !fromJSON(env.DOCKER_PUSH) }} diff --git a/docker/main.dockerfile b/docker/main.dockerfile index 5b56bb879..51ac27d8f 100644 --- a/docker/main.dockerfile +++ b/docker/main.dockerfile @@ -43,7 +43,7 @@ COPY .git /opt/dask_sql/.git COPY src /opt/dask_sql/src COPY dask_sql /opt/dask_sql/dask_sql RUN cd /opt/dask_sql/ \ - && pip install -e . -vv + && CONDA_PREFIX="/opt/conda/" maturin develop # Set the script to execute COPY scripts/startup_script.py /opt/dask_sql/startup_script.py