From 54a9ebf13725312e3cbf849cefe101631386e8fc Mon Sep 17 00:00:00 2001 From: Alex Merose Date: Mon, 16 Nov 2026 23:24:17 -0800 Subject: [PATCH 1/5] Make Context's records of its tables and functions public The datafusion-accelerated package reads four of Context's private names. This makes them public, with what each can't see in its docstring: - Context.datasets: the Dataset each table reads, read-only. - Context.write(tables): new values into registered Datasets, all or none, with the checks a prepared query's call makes. - Context.replacements: how often each table or view has been replaced or dropped. - Context.registered_functions: the function last registered under each name through Context, without DataFusion's built-ins. - Context.tables_read(plan): the tables and views a plan reads, in its subqueries too. It looks views up in the catalog, so a name given with AS no longer counts as one. PreparedQuery uses them. Since tables_read leaves out the default catalog and schema, a query of public.a can now write a. Closes #322 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NyN7idACeDMh94qrnFMu6h --- tests/test_context.py | 169 +++++++++++++++++++++++++ tests/test_prepare.py | 6 + xarray_sql/sql.py | 284 ++++++++++++++++++++++++++++++++---------- 3 files changed, 395 insertions(+), 64 deletions(-) create mode 100644 tests/test_context.py diff --git a/tests/test_context.py b/tests/test_context.py new file mode 100644 index 00000000..318a19e3 --- /dev/null +++ b/tests/test_context.py @@ -0,0 +1,169 @@ +"""Tests for what a Context records about its tables and functions: +`datasets`, `write`, `replacements`, `registered_functions` and +`tables_read`.""" + +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import pytest +import xarray as xr +from datafusion import udaf, udf, udwf +from datafusion.user_defined import Accumulator, WindowEvaluator + +from xarray_sql import Context + + +def _table(v): + return xr.Dataset({"v": ("i", v)}, coords={"i": np.arange(len(v))}) + + +@pytest.fixture +def ctx(): + ctx = Context() + ctx.from_dataset("a", _table(np.arange(3.0))) + ctx.from_dataset("b", _table(np.arange(3.0))) + return ctx + + +def _values(ctx, table): + rows = ctx.sql(f"SELECT v FROM {table} ORDER BY i").to_arrow_table() + return rows["v"].to_pylist() + + +def test_datasets_are_the_registered_datasets_and_read_only(): + ctx = Context() + a = _table(np.arange(3.0)) + ctx.from_dataset("a", a) + assert ctx.datasets["a"] is a + with pytest.raises(TypeError): + ctx.datasets["b"] = a + + +def test_a_write_reaches_queries_and_datasets_but_not_replacements(ctx): + ctx.write({"a": _table(np.array([7.0, 8.0, 9.0]))}) + assert _values(ctx, "a") == [7.0, 8.0, 9.0] + assert ctx.datasets["a"]["v"].values.tolist() == [7.0, 8.0, 9.0] + assert dict(ctx.replacements) == {} + + +def test_a_write_that_fails_a_check_writes_no_table(ctx): + with pytest.raises(ValueError, match="int64"): + ctx.write( + { + "a": _table(np.array([7.0, 8.0, 9.0])), + "b": _table(np.array([7, 8, 9])), + } + ) + assert _values(ctx, "a") == [0.0, 1.0, 2.0] + + +def test_a_write_needs_a_registered_dataset(ctx): + ctx.from_pydict({"v": [1.0]}, "c") + with pytest.raises(ValueError, match="no Dataset is registered as 'c'"): + ctx.write({"c": _table(np.array([2.0]))}) + + +@pytest.mark.parametrize( + "change, name", + [ + (lambda ctx: ctx.deregister_table("a"), "a"), + (lambda ctx: ctx.sql("CREATE OR REPLACE TABLE a AS SELECT 1"), "a"), + (lambda ctx: ctx.sql("DROP TABLE public.a"), "a"), + (lambda ctx: ctx.sql("CREATE OR REPLACE VIEW v AS SELECT 2"), "v"), + (lambda ctx: ctx.sql('DROP VIEW "v"'), "v"), + ], +) +def test_replacements_count_each_table_or_view_replaced(ctx, change, name): + ctx.sql("CREATE VIEW v AS SELECT v FROM b") + change(ctx) + assert dict(ctx.replacements) == {name: 1} + + +def test_creating_a_table_or_view_replaces_nothing(ctx): + ctx.sql("CREATE OR REPLACE VIEW v AS SELECT v FROM b") + ctx.sql("CREATE TABLE c AS SELECT 1") + assert dict(ctx.replacements) == {} + + +def _identity(): + return udf(lambda x: x, [pa.float64()], pa.float64(), "immutable", "Ident") + + +class _Sum(Accumulator): + def __init__(self): + self._sum = 0.0 + + def update(self, values): + self._sum += pc.sum(values).as_py() or 0.0 + + def merge(self, sums): + self._sum += pc.sum(sums).as_py() or 0.0 + + def state(self): + return [pa.scalar(self._sum)] + + def evaluate(self): + return pa.scalar(self._sum) + + +class _Same(WindowEvaluator): + def evaluate_all(self, values, num_rows): + return values[0] + + +def test_registered_functions_holds_each_function_registered(ctx): + ident = _identity() + total = udaf( + _Sum, pa.float64(), pa.float64(), [pa.float64()], "immutable", "sum" + ) + same = udwf(_Same, pa.float64(), pa.float64(), "immutable", "same") + ctx.register_udf(ident) + ctx.register_udaf(total) + ctx.register_udwf(same) + assert { + name: ctx.registered_functions[name] + for name in ("Ident", "sum", "same") + } == {"Ident": ident, "sum": total, "same": same} + assert ctx.registered_functions.keys().isdisjoint({"avg", "abs"}) + assert ctx.sql('SELECT "Ident"(v) AS v FROM a ORDER BY i').to_arrow_table()[ + "v" + ].to_pylist() == [0.0, 1.0, 2.0] + + +def test_registering_a_name_again_replaces_its_function(ctx): + ctx.register_udf(_identity()) + again = _identity() + ctx.register_udf(again) + assert ctx.registered_functions["Ident"] is again + ctx.deregister_udf("Ident") + assert "Ident" not in ctx.registered_functions + + +def test_an_extension_handle_shares_what_the_context_records(ctx): + handle = ctx.with_extensions() + handle.register_udf(_identity()) + handle.deregister_table("b") + assert "Ident" in ctx.registered_functions + assert dict(ctx.replacements) == {"b": 1} + assert set(ctx.datasets) == {"a"} + + +@pytest.mark.parametrize( + "query, read", + [ + ("SELECT v FROM public.a", {"a"}), + ("SELECT x.v FROM a AS x JOIN b AS y ON x.i = y.i", {"a", "b"}), + ("SELECT v FROM a WHERE v IN (SELECT v FROM b)", {"a", "b"}), + ("SELECT v, (SELECT max(v) FROM b) AS m FROM a", {"a", "b"}), + ( + "SELECT v FROM a WHERE EXISTS (SELECT 1 FROM b WHERE b.i = a.i)", + {"a", "b"}, + ), + ("SELECT v FROM w", {"w", "v", "b"}), + ("SELECT x.v FROM datafusion.public.v AS x", {"v", "b"}), + ], +) +def test_tables_read_lists_tables_and_views_in_subqueries_too(ctx, query, read): + ctx.sql("CREATE VIEW v AS SELECT v FROM b") + ctx.sql("CREATE VIEW w AS SELECT v FROM v") + assert ctx.tables_read(ctx.sql(query).logical_plan()) == read diff --git a/tests/test_prepare.py b/tests/test_prepare.py index 90b5e86e..5d419ec0 100644 --- a/tests/test_prepare.py +++ b/tests/test_prepare.py @@ -202,6 +202,12 @@ def test_a_table_replaced_by_datafusion_counts_as_registered_again(ctx): query() +def test_a_table_named_with_its_schema_takes_writes(ctx): + query = ctx.prepare("SELECT i, j, v FROM datafusion.public.a ORDER BY i, j") + new = _a(np.ones((4, 3))) + assert query(a=new)["v"].to_pylist() == [1.0] * 12 + + def test_a_table_the_query_doesnt_read_can_be_registered_again(ctx): query = ctx.prepare("SELECT SUM(v) AS s FROM a") want = query() diff --git a/xarray_sql/sql.py b/xarray_sql/sql.py index d3b38b4f..65cf7751 100644 --- a/xarray_sql/sql.py +++ b/xarray_sql/sql.py @@ -2,13 +2,19 @@ import re import time import uuid -from collections.abc import Callable -from types import ModuleType +from collections.abc import Callable, Mapping +from types import MappingProxyType, ModuleType import numpy as np import pyarrow as pa import xarray as xr -from datafusion import SessionConfig, SessionContext +from datafusion import ( + AggregateUDF, + ScalarUDF, + SessionConfig, + SessionContext, + WindowUDF, +) from datafusion.catalog import Schema from datafusion.plan import ExecutionPlan, LogicalPlan @@ -91,11 +97,14 @@ def __init__( # in SQL (e.g. ``"air"`` for a uniform-dim Dataset, or # ``"era5.surface"`` for one entry from a multi-dim-group split). self._registered_datasets: dict[str, xr.Dataset] = {} - # How many times each name's table has been removed or replaced. - # DataFusion refuses to register a name that's taken, so a table - # registered again from Python was deregistered first; SQL that - # replaces or drops a table counts too (see sql()). - self._deregistrations: dict[str, int] = {} + # How many times each name's table or view has been removed or + # replaced. DataFusion refuses to register a name that's taken, so a + # table registered again from Python was deregistered first; SQL + # that replaces or drops a table or a view counts too (see sql()). + self._replacements: dict[str, int] = {} + # The function last registered under each name through this + # Context's register_ methods, which pyproj's reproject() below is. + self._functions: dict[str, ScalarUDF | AggregateUDF | WindowUDF] = {} # With pyproj installed, every context speaks CRS out of the box: # reproject(x, y, src_crs, dst_crs), à la PostGIS ST_Transform. if _proj is not None: @@ -119,6 +128,163 @@ def with_extensions(self, *extensions) -> "Context": derived.ctx = session.ctx return derived + @property + def datasets(self) -> Mapping[str, xr.Dataset]: + """The Dataset registered under each table's name, read-only. + + Each value is the very Dataset the table reads, not a copy: + [write][xarray_sql.Context.write] updates it in place, so it holds + the new values as soon as ``write`` returns. Changing its arrays + any other way skips ``write``'s checks. A Dataset split into a + table per group of dims is listed under each table's qualified + name, such as ``"era5.surface"``. Tables registered any other way, + such as with ``SessionContext.register_record_batches``, aren't + listed. + """ + return MappingProxyType(self._registered_datasets) + + @property + def replacements(self) -> Mapping[str, int]: + """How many times each table or view has been replaced or dropped, + by name, read-only. + + It counts [deregister_table][xarray_sql.Context.deregister_table], + which registering a name again needs first, and a statement run + with [sql][xarray_sql.Context.sql] that replaces or drops a table + or a view: ``CREATE OR REPLACE TABLE``, ``CREATE OR REPLACE VIEW``, + ``DROP TABLE`` or ``DROP VIEW``. A name never replaced isn't in it. + Names leave out DataFusion's default catalog and schema, as + [tables_read][xarray_sql.Context.tables_read] does. Writing new + values with [write][xarray_sql.Context.write] doesn't count. + + A change made through ``SessionContext``'s own methods, such as + ``SessionContext.sql(ctx, ...)``, or from Rust, isn't counted. + """ + return MappingProxyType(self._replacements) + + @property + def registered_functions( + self, + ) -> Mapping[str, ScalarUDF | AggregateUDF | WindowUDF]: + """The function last registered under each name through this + Context, read-only. + + It holds each ``ScalarUDF``, ``AggregateUDF`` and ``WindowUDF`` + registered with [register_udf][xarray_sql.Context.register_udf], + [register_udaf][xarray_sql.Context.register_udaf] or + [register_udwf][xarray_sql.Context.register_udwf], less those + deregistered since. Registering a name again replaces its value + with the new object, so comparing objects shows whether a name was + registered again. Unlike DataFusion's ``udfs()``, it leaves out the + built-in functions, so it shows when a name such as ``sum`` means a + function of the user's. + + Keys are each function's name as it was registered. SQL lowers an + unquoted name before looking it up, so compare lowered names to + match what a query calls. + + It doesn't see a function registered from Rust: by an extension + bundle in [with_extensions][xarray_sql.Context.with_extensions], + by ``enable_spark_functions``, or by ddx, the package that + differentiates SQL, whose ``ddx_stop_gradient`` every Context has + with ``pip install "xarray-sql[ml]"``. Nor does it see one + registered through + ``SessionContext``'s own methods. + """ + return MappingProxyType(self._functions) + + def register_udf(self, udf: ScalarUDF) -> None: + """Register a scalar function, as ``SessionContext.register_udf`` + does, and record it in + [registered_functions][xarray_sql.Context.registered_functions].""" + super().register_udf(udf) + self._functions[udf.name] = udf + + def register_udaf(self, udaf: AggregateUDF) -> None: + """Register an aggregate function, as + ``SessionContext.register_udaf`` does, and record it in + [registered_functions][xarray_sql.Context.registered_functions].""" + super().register_udaf(udaf) + self._functions[udaf.name] = udaf + + def register_udwf(self, udwf: WindowUDF) -> None: + """Register a window function, as ``SessionContext.register_udwf`` + does, and record it in + [registered_functions][xarray_sql.Context.registered_functions].""" + super().register_udwf(udwf) + self._functions[udwf.name] = udwf + + def deregister_udf(self, name: str) -> None: + """Remove a scalar function, and forget it in + [registered_functions][xarray_sql.Context.registered_functions].""" + super().deregister_udf(name) + self._forget_function(name, ScalarUDF) + + def deregister_udaf(self, name: str) -> None: + """Remove an aggregate function, and forget it in + [registered_functions][xarray_sql.Context.registered_functions].""" + super().deregister_udaf(name) + self._forget_function(name, AggregateUDF) + + def deregister_udwf(self, name: str) -> None: + """Remove a window function, and forget it in + [registered_functions][xarray_sql.Context.registered_functions].""" + super().deregister_udwf(name) + self._forget_function(name, WindowUDF) + + def _forget_function(self, name: str, kind: type) -> None: + """Forget the function of ``kind`` recorded as ``name``, which a + function of another kind of the same name leaves alone.""" + if isinstance(self._functions.get(name), kind): + del self._functions[name] + + def tables_read(self, plan: LogicalPlan) -> set[str]: + """The names of the tables and views a query's plan reads. + + It finds them in the plan's subqueries too (``IN``, ``EXISTS`` and + scalar subqueries), and lists both a view's own name and the tables + under it. Names leave out DataFusion's default catalog and schema, + so a query of ``public.air`` reads ``"air"``, the key it has in + [datasets][xarray_sql.Context.datasets]. + + Views are told apart from names given with ``AS`` by looking them + up in this Context's catalog as it is now, so call this before a + view the plan reads is dropped. A name given with ``AS`` that's + also a view's is listed too. + + Args: + plan: A query's logical plan, such as + ``ctx.sql(query).logical_plan()``. + + Returns: + The names of the tables and views ``plan`` reads. + """ + return { + _unqualified(name) for name in _SCAN.findall(plan.display_indent()) + } | self._views_read(plan) + + def _views_read(self, plan: LogicalPlan) -> set[str]: + """The names of the views ``plan`` reads, in its subqueries too, + without DataFusion's default catalog and schema.""" + # DataFusion plans a view as its query, under its name, as it plans + # ``FROM t AS x`` under ``x``; only the catalog tells them apart. + return { + _unqualified(name) + for name in _ALIAS.findall(plan.display_indent()) + if self._is_view(name) + } + + def _is_view(self, name: str) -> bool: + """Whether ``name``, as a plan's display prints it, is a view in + this Context's catalog.""" + *path, table = name.split(".") + try: + catalog = self.catalog(*path[:-1]) + schema = catalog.schema(*path[-1:]) + return schema.table(table).kind == "view" + except Exception: # noqa: BLE001 - DataFusion raises a bare Exception + return False + def from_dataset( self, name: str, @@ -328,7 +494,7 @@ def _forget(self, name: str) -> None: removed or replaced.""" name = _unqualified(name) self._registered_datasets.pop(name, None) - self._deregistrations[name] = self._deregistrations.get(name, 0) + 1 + self._replacements[name] = self._replacements.get(name, 0) + 1 def prepare(self, query: str) -> "PreparedQuery": """Plan a query once, to run it many times. @@ -362,12 +528,37 @@ def prepare(self, query: str) -> "PreparedQuery": """ return PreparedQuery(self, query) - def _write(self, writes: dict[str, xr.Dataset]) -> None: - """Write each Dataset's values into the arrays of the Dataset - registered under its name, all or none of them.""" + def write(self, tables: Mapping[str, xr.Dataset]) -> None: + """Write new values into registered Datasets' arrays, in place. + + ``ctx.write({"w": ds})`` writes ``ds``'s values into the Dataset + registered as ``w``, as ``w_ds["v"][...] = ds["v"]`` would, so every + query of ``w`` reads them from then on, and so does + ``ctx.datasets["w"]``. It checks every table before it writes any, + and writes all of them or none. A Dataset must match the one it's + written into in all but its values: the same data variables, dtypes, + dims and coordinates, and NaN or NaT in the same places, since + xarray-sql reads them as NULL. The registered arrays must be + writable NumPy arrays. To change anything else, register the new + Dataset instead. + + Writing doesn't count in + [replacements][xarray_sql.Context.replacements], and + ``write({})`` does nothing. + + Args: + tables: A Dataset of new values for each table, by the name it + has in [datasets][xarray_sql.Context.datasets]. + + Raises: + ValueError: If no Dataset is registered under a name, or a + Dataset doesn't match the one registered under its name. + """ copies = [] - for name, ds in writes.items(): - registered = self._registered_datasets[name] + for name, ds in tables.items(): + registered = self._registered_datasets.get(name) + if registered is None: + raise ValueError(f"no Dataset is registered as {name!r}") if set(ds.data_vars) != set(registered.data_vars): raise ValueError( f"{name!r} has the data variables " @@ -432,10 +623,8 @@ class PreparedQuery: ``query()`` runs it on the values its tables hold now, and returns its rows as a ``pyarrow.Table``. ``query(w=ds)`` first writes ``ds``'s values into the Dataset registered as ``w``, as - ``w_ds["v"][...] = ds["v"]`` would, so other queries of ``w`` see them - too. ``ds`` must match ``w_ds`` in all but its values: the same data - variables, dtypes, dims and coordinates, and NaN or NaT in the same - places, since xarray-sql reads them as NULL. + ``ctx.write({"w": ds})`` does, so other queries of ``w`` see them too. + [Context.write][xarray_sql.Context.write] says what ``ds`` must match. To change anything else, register the new Dataset and prepare the query again. A call raises if a table the query reads, in a subquery @@ -458,15 +647,13 @@ def __init__(self, ctx: Context, query: str): # A call may write any Dataset the query reads, which leaves out # the tables ddx wrote. It finds each by name, so one registered # again is written too. - self._writable = set().union(*map(_tables_read, plans)) & set( - ctx._registered_datasets + self._writable = set().union(*map(ctx.tables_read, plans)) & set( + ctx.datasets ) # ddx built its programs from each view's SQL as it was then. self._read = { - name: ctx._deregistrations.get(name, 0) - for name in map( - _unqualified, set().union(*map(_views_read, plans)) - ) + name: ctx.replacements.get(name, 0) + for name in set().union(*map(ctx._views_read, plans)) } return start = time.perf_counter() @@ -479,19 +666,10 @@ def __init__(self, ctx: Context, query: str): # they were folded into. self._optimized = df.optimized_logical_plan() # Each table and view the query reads, by how often its name had - # been deregistered; and of the tables, the Datasets a call may - # write into. - logical = df.logical_plan() - tables = _tables_read(logical) - self._read = { - name: ctx._deregistrations.get(name, 0) - for name in map(_unqualified, tables | _views_read(logical)) - } - self._registered = { - name: ctx._registered_datasets[name] - for name in tables - if name in ctx._registered_datasets - } + # been replaced; and of those, the Datasets a call may write into. + read = ctx.tables_read(df.logical_plan()) + self._read = {name: ctx.replacements.get(name, 0) for name in read} + self._writable = read & set(ctx.datasets) # A plan keeps state from a run (a hash join keeps the table it # built), so each call runs a fresh copy of it, decoded from its # serialized form. Copying a plan copies its in-memory tables, so @@ -519,25 +697,22 @@ def __call__(self, **tables: xr.Dataset) -> pa.Table: Returns: The query's rows. """ - writable = ( - self._registered if self._gradient is None else self._writable - ) for name in tables: - if name not in writable: + if name not in self._writable: raise ValueError( f"the query reads no Dataset registered as {name!r} " "when it was prepared" ) - for name, deregistrations in self._read.items(): - if self._ctx._deregistrations.get(name, 0) != deregistrations: + for name, replacements in self._read.items(): + if self._ctx.replacements.get(name, 0) != replacements: raise ValueError( f"{name!r} has been registered again, replaced or " "dropped since the query was prepared; prepare the " "query again" ) if self._gradient is not None: - return self._gradient(lambda: self._ctx._write(tables)) - self._ctx._write(tables) + return self._gradient(lambda: self._ctx.write(tables)) + self._ctx.write(tables) if self._plan is None: df = self._ctx.create_dataframe_from_logical_plan(self._optimized) return df.to_arrow_table() @@ -575,25 +750,6 @@ def _copy(ctx: SessionContext, plan: ExecutionPlan) -> ExecutionPlan: _ALIAS = re.compile(r"^ *SubqueryAlias: (.+)$", re.MULTILINE) -def _tables_read(plan: LogicalPlan) -> set[str]: - """The names of the tables ``plan`` scans, in its subqueries too, and - through any views.""" - return set(_SCAN.findall(plan.display_indent())) - - -def _views_read(plan: LogicalPlan) -> set[str]: - """The names of the views ``plan`` reads, in its subqueries too. - - DataFusion plans a view as its query, under its name, as it plans - ``FROM t AS x`` under ``x``, so these include the names a query gives - with ``AS``, less those of the tables it scans. One that's also the - name of a table the query doesn't read makes a prepared query raise - once that table is registered again, but never read anything wrongly. - """ - text = plan.display_indent() - return set(_ALIAS.findall(text)) - set(_SCAN.findall(text)) - - # Whitespace or comments, which SQL reads between any two words. _GAP = r"(?:\s|--[^\n]*|/\*.*?\*/)" # A name's part: quoted, which keeps its case, or not, which DataFusion From 9c0b9950196af580a055bb04ee4b0d8705bf625d Mon Sep 17 00:00:00 2001 From: Alex Merose Date: Mon, 16 Nov 2026 23:42:20 -0800 Subject: [PATCH 2/5] Keep datasets and replacements true to the tables - mypy: _is_view returns a bool, not DataFusion's untyped value. - from_dataset records a Dataset only after its table is registered, so a rejected registration leaves the old one in datasets. - Registering a split Dataset again counts each table of the schema it replaces, so a prepared query of one raises instead of reading the old table. - write checks each dim's size before it writes anything, so a wrong size no longer writes the tables before it. - The placeholder an in-memory table is registered under isn't counted in replacements. Closes #324 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NyN7idACeDMh94qrnFMu6h --- tests/test_context.py | 35 ++++++++++++++++++++++++++++++----- xarray_sql/sql.py | 27 +++++++++++++++++++-------- 2 files changed, 49 insertions(+), 13 deletions(-) diff --git a/tests/test_context.py b/tests/test_context.py index 318a19e3..c260957f 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -37,6 +37,9 @@ def test_datasets_are_the_registered_datasets_and_read_only(): assert ctx.datasets["a"] is a with pytest.raises(TypeError): ctx.datasets["b"] = a + with pytest.raises(Exception, match="already exists"): + ctx.from_dataset("a", _table(np.zeros(3))) + assert ctx.datasets["a"] is a def test_a_write_reaches_queries_and_datasets_but_not_replacements(ctx): @@ -46,15 +49,21 @@ def test_a_write_reaches_queries_and_datasets_but_not_replacements(ctx): assert dict(ctx.replacements) == {} -def test_a_write_that_fails_a_check_writes_no_table(ctx): - with pytest.raises(ValueError, match="int64"): +@pytest.mark.parametrize( + "bad, match", [(np.arange(3.0), "float64"), (np.arange(5), "'k': 5")] +) +def test_a_write_that_fails_a_check_writes_no_table(bad, match): + ctx = Context() + ctx.from_dataset("a", xr.Dataset({"v": ("i", np.arange(3))})) + ctx.from_dataset("b", xr.Dataset({"v": ("k", np.arange(3))})) + with pytest.raises(ValueError, match=match): ctx.write( { - "a": _table(np.array([7.0, 8.0, 9.0])), - "b": _table(np.array([7, 8, 9])), + "a": xr.Dataset({"v": ("i", np.arange(7, 10))}), + "b": xr.Dataset({"v": ("k", bad)}), } ) - assert _values(ctx, "a") == [0.0, 1.0, 2.0] + assert _values(ctx, "a") == [0, 1, 2] def test_a_write_needs_a_registered_dataset(ctx): @@ -79,6 +88,22 @@ def test_replacements_count_each_table_or_view_replaced(ctx, change, name): assert dict(ctx.replacements) == {name: 1} +def _split(v): + return xr.Dataset( + {"v": ("i", v), "t": (("i", "j"), np.ones((len(v), 2)))}, + coords={"i": np.arange(len(v)), "j": np.arange(2)}, + ) + + +def test_registering_a_split_dataset_again_replaces_each_table(): + ctx = Context() + ctx.from_dataset("g", _split(np.arange(3.0))) + assert dict(ctx.replacements) == {} + ctx.from_dataset("g", _split(np.array([7.0, 8.0, 9.0]))) + assert dict(ctx.replacements) == {"g.i": 1, "g.i_j": 1} + assert _values(ctx, "g.i") == [7.0, 8.0, 9.0] + + def test_creating_a_table_or_view_replaces_nothing(ctx): ctx.sql("CREATE OR REPLACE VIEW v AS SELECT v FROM b") ctx.sql("CREATE TABLE c AS SELECT 1") diff --git a/xarray_sql/sql.py b/xarray_sql/sql.py index 65cf7751..988be120 100644 --- a/xarray_sql/sql.py +++ b/xarray_sql/sql.py @@ -281,7 +281,7 @@ def _is_view(self, name: str) -> bool: try: catalog = self.catalog(*path[:-1]) schema = catalog.schema(*path[-1:]) - return schema.table(table).kind == "view" + return bool(schema.table(table).kind == "view") except Exception: # noqa: BLE001 - DataFusion raises a bare Exception return False @@ -367,13 +367,22 @@ def from_dataset( coord_arrays = shared_coord_arrays(input_table) if len(groups) <= 1: - self._registered_datasets[name] = input_table - return self._from_dataset( + self._from_dataset( name, input_table, chunks, coord_arrays=coord_arrays ) + # Recorded once DataFusion has registered the table, which it + # refuses to do under a name that's taken. + self._registered_datasets[name] = input_table + return self schema = Schema.memory_schema(self) - self.catalog().register_schema(name, schema) + # register_schema replaces a schema of the same name, tables and + # all, so each of its tables counts as replaced. + catalog = self.catalog() + if name in catalog.schema_names(): + for table in catalog.schema(name).table_names(): + self._forget(f"{name}.{table}") + catalog.register_schema(name, schema) for dims, var_names in groups.items(): sub_name = names[dims] @@ -432,7 +441,8 @@ def _in_memory_table(self, partitions: list[list[pa.RecordBatch]]): placeholder = f"_xarray_sql_{uuid.uuid4().hex}" self.register_record_batches(placeholder, partitions) table = self.catalog().schema().table(placeholder) - self.deregister_table(placeholder) + # A placeholder isn't a table anyone replaced. + SessionContext.deregister_table(self, placeholder) return table def _maybe_register_cftime_udf(self, ds: xr.Dataset) -> None: @@ -577,10 +587,11 @@ def write(self, tables: Mapping[str, xr.Dataset]) -> None: for var in registered.data_vars: old, new = registered[var].variable, ds[var].variable # Dims are matched by name, as xarray matches them. - if set(new.dims) != set(old.dims) or new.dtype != old.dtype: + if new.sizes != old.sizes or new.dtype != old.dtype: raise ValueError( - f"{name}.{var} is {old.dtype} over {old.dims}, and " - f"the new values are {new.dtype} over {new.dims}" + f"{name}.{var} is {old.dtype} over " + f"{dict(old.sizes)}, and the new values are " + f"{new.dtype} over {dict(new.sizes)}" ) target = old.data # A table reads a NumPy array's memory, shared or on every From bc7a33e92420b237222bd8fe64db3b0ff95908c2 Mon Sep 17 00:00:00 2001 From: Alex Merose Date: Tue, 17 Nov 2026 19:19:13 -0800 Subject: [PATCH 3/5] Find views with dots in their names, and names in the default catalog - tables_read now finds a view whose quoted name holds a dot, such as "x.y". A plan prints it as x.y, which the lookup read as the view y in the schema x. So a prepared query of it missed its replacement. Every reading of the name is now tried. - Names in the default catalog lose it in any schema, so datafusion.era5.i is era5.i. Before, a prepared query of datafusion.era5.i missed a replacement of era5.i, and couldn't write it. Closes #325 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NyN7idACeDMh94qrnFMu6h --- tests/test_context.py | 4 ++++ xarray_sql/sql.py | 35 ++++++++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/tests/test_context.py b/tests/test_context.py index c260957f..b9ad512a 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -186,9 +186,13 @@ def test_an_extension_handle_shares_what_the_context_records(ctx): ), ("SELECT v FROM w", {"w", "v", "b"}), ("SELECT x.v FROM datafusion.public.v AS x", {"v", "b"}), + ('SELECT v FROM "x.y"', {"x.y", "b"}), + ("SELECT v FROM datafusion.g.i", {"g.i"}), ], ) def test_tables_read_lists_tables_and_views_in_subqueries_too(ctx, query, read): ctx.sql("CREATE VIEW v AS SELECT v FROM b") ctx.sql("CREATE VIEW w AS SELECT v FROM v") + ctx.sql('CREATE VIEW "x.y" AS SELECT v FROM b') + ctx.from_dataset("g", _split(np.arange(3.0))) assert ctx.tables_read(ctx.sql(query).logical_plan()) == read diff --git a/xarray_sql/sql.py b/xarray_sql/sql.py index 988be120..de939789 100644 --- a/xarray_sql/sql.py +++ b/xarray_sql/sql.py @@ -277,13 +277,30 @@ def _views_read(self, plan: LogicalPlan) -> set[str]: def _is_view(self, name: str) -> bool: """Whether ``name``, as a plan's display prints it, is a view in this Context's catalog.""" - *path, table = name.split(".") + # The display joins a name's parts with dots, and a quoted part + # may hold dots of its own, so ``x.y`` is the view "x.y" or the + # view y in the schema x. Any reading that is a view counts. + parts = name.split(".") + readings: list[tuple[tuple[str, ...], str]] = [((), name)] + for t in range(1, len(parts)): + table = ".".join(parts[t:]) + readings.append(((".".join(parts[:t]),), table)) + readings += [ + ((".".join(parts[:c]), ".".join(parts[c:t])), table) + for c in range(1, t) + ] + return any(self._kind(*reading) == "view" for reading in readings) + + def _kind(self, path: tuple[str, ...], table: str) -> str | None: + """The kind of ``table`` in the schema ``path`` names, a schema of + the default catalog or a catalog and a schema, or ``None`` if + there's no such table.""" try: catalog = self.catalog(*path[:-1]) - schema = catalog.schema(*path[-1:]) - return bool(schema.table(table).kind == "view") + kind = catalog.schema(*path[-1:]).table(table).kind except Exception: # noqa: BLE001 - DataFusion raises a bare Exception - return False + return None + return str(kind) def from_dataset( self, @@ -794,11 +811,11 @@ def _resolved(name: str) -> str: def _unqualified(name: str) -> str: """``name`` without DataFusion's default catalog and schema, which a query may name or leave out: ``datafusion.public.v`` and ``public.v`` - are both ``v``.""" - for prefix in ("datafusion.public.", "public."): - if name.startswith(prefix): - return name[len(prefix) :] - return name + are both ``v``, and ``datafusion.era5.v`` is ``era5.v``.""" + # Two dots or more make the first part a catalog's name. + if name.startswith("datafusion.") and name.count(".") > 1: + name = name[len("datafusion.") :] + return name.removeprefix("public.") def _missing(values: np.ndarray) -> np.ndarray | None: From b4356f97e45f0a7f81642bf21952c5f5d691de6c Mon Sep 17 00:00:00 2001 From: Alex Merose Date: Tue, 17 Nov 2026 19:31:13 -0800 Subject: [PATCH 4/5] Key a table or view by its name's parts on both sides A plan prints a name with its parts joined by dots and unquoted, so a view named "datafusion.x.y" printed as datafusion.x.y, and was keyed as x.y in the schema datafusion.x. Replacing it with public."datafusion.x.y" counted under datafusion.x.y, so a prepared query of it ran the old view. Each key is now made from a name's parts: from SQL, as DataFusion parses them; from a plan, from each reading of the name that the catalog has. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NyN7idACeDMh94qrnFMu6h --- tests/test_context.py | 9 ++++ xarray_sql/sql.py | 96 ++++++++++++++++++++++++------------------- 2 files changed, 63 insertions(+), 42 deletions(-) diff --git a/tests/test_context.py b/tests/test_context.py index b9ad512a..4757b588 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -80,10 +80,17 @@ def test_a_write_needs_a_registered_dataset(ctx): (lambda ctx: ctx.sql("DROP TABLE public.a"), "a"), (lambda ctx: ctx.sql("CREATE OR REPLACE VIEW v AS SELECT 2"), "v"), (lambda ctx: ctx.sql('DROP VIEW "v"'), "v"), + ( + lambda ctx: ctx.sql( + 'CREATE OR REPLACE VIEW public."datafusion.x.y" AS SELECT 2' + ), + "datafusion.x.y", + ), ], ) def test_replacements_count_each_table_or_view_replaced(ctx, change, name): ctx.sql("CREATE VIEW v AS SELECT v FROM b") + ctx.sql('CREATE VIEW "datafusion.x.y" AS SELECT 1') change(ctx) assert dict(ctx.replacements) == {name: 1} @@ -188,11 +195,13 @@ def test_an_extension_handle_shares_what_the_context_records(ctx): ("SELECT x.v FROM datafusion.public.v AS x", {"v", "b"}), ('SELECT v FROM "x.y"', {"x.y", "b"}), ("SELECT v FROM datafusion.g.i", {"g.i"}), + ('SELECT v FROM "datafusion.x.y"', {"datafusion.x.y", "b"}), ], ) def test_tables_read_lists_tables_and_views_in_subqueries_too(ctx, query, read): ctx.sql("CREATE VIEW v AS SELECT v FROM b") ctx.sql("CREATE VIEW w AS SELECT v FROM v") ctx.sql('CREATE VIEW "x.y" AS SELECT v FROM b') + ctx.sql('CREATE VIEW "datafusion.x.y" AS SELECT v FROM b') ctx.from_dataset("g", _split(np.arange(3.0))) assert ctx.tables_read(ctx.sql(query).logical_plan()) == read diff --git a/xarray_sql/sql.py b/xarray_sql/sql.py index de939789..08143703 100644 --- a/xarray_sql/sql.py +++ b/xarray_sql/sql.py @@ -2,7 +2,7 @@ import re import time import uuid -from collections.abc import Callable, Mapping +from collections.abc import Callable, Mapping, Sequence from types import MappingProxyType, ModuleType import numpy as np @@ -259,42 +259,52 @@ def tables_read(self, plan: LogicalPlan) -> set[str]: Returns: The names of the tables and views ``plan`` reads. """ - return { - _unqualified(name) for name in _SCAN.findall(plan.display_indent()) - } | self._views_read(plan) + read = set() + for name in _SCAN.findall(plan.display_indent()): + # A table dropped since the plan was made is in no reading. + read |= self._keys(name) or {_key(name.split("."))} + return read | self._views_read(plan) def _views_read(self, plan: LogicalPlan) -> set[str]: """The names of the views ``plan`` reads, in its subqueries too, without DataFusion's default catalog and schema.""" # DataFusion plans a view as its query, under its name, as it plans # ``FROM t AS x`` under ``x``; only the catalog tells them apart. - return { - _unqualified(name) - for name in _ALIAS.findall(plan.display_indent()) - if self._is_view(name) - } + return set().union( + *( + self._keys(name, kind="view") + for name in _ALIAS.findall(plan.display_indent()) + ) + ) - def _is_view(self, name: str) -> bool: - """Whether ``name``, as a plan's display prints it, is a view in - this Context's catalog.""" + def _keys(self, name: str, kind: str | None = None) -> set[str]: + """The keys of each table or view (of ``kind``, if given) that + ``name``, as a plan's display prints it, may be in this Context's + catalog.""" # The display joins a name's parts with dots, and a quoted part # may hold dots of its own, so ``x.y`` is the view "x.y" or the - # view y in the schema x. Any reading that is a view counts. + # view y in the schema x. Each reading in the catalog counts. parts = name.split(".") - readings: list[tuple[tuple[str, ...], str]] = [((), name)] + readings: list[tuple[str, ...]] = [(name,)] for t in range(1, len(parts)): table = ".".join(parts[t:]) - readings.append(((".".join(parts[:t]),), table)) + readings.append((".".join(parts[:t]), table)) readings += [ - ((".".join(parts[:c]), ".".join(parts[c:t])), table) + (".".join(parts[:c]), ".".join(parts[c:t]), table) for c in range(1, t) ] - return any(self._kind(*reading) == "view" for reading in readings) + return { + _key(reading) + for reading in readings + if (found := self._kind(reading)) is not None + and kind in (None, found) + } - def _kind(self, path: tuple[str, ...], table: str) -> str | None: - """The kind of ``table`` in the schema ``path`` names, a schema of - the default catalog or a catalog and a schema, or ``None`` if - there's no such table.""" + def _kind(self, parts: tuple[str, ...]) -> str | None: + """The kind of the table or view whose name has ``parts`` (its + table; schema and table; or catalog, schema and table), or + ``None`` if there's no such table.""" + *path, table = parts try: catalog = self.catalog(*path[:-1]) kind = catalog.schema(*path[-1:]).table(table).kind @@ -398,7 +408,7 @@ def from_dataset( catalog = self.catalog() if name in catalog.schema_names(): for table in catalog.schema(name).table_names(): - self._forget(f"{name}.{table}") + self._forget(_key((name, table))) catalog.register_schema(name, schema) for dims, var_names in groups.items(): @@ -507,19 +517,18 @@ def sql(self, query: str, *args, **kwargs) -> XarrayDataFrame: else: df = super().sql(query, *args, **kwargs) if replaced is not None and existed: - self._forget(_resolved(replaced)) + self._forget(_key(_parts(replaced))) return self._wrap(df) def deregister_table(self, name: str) -> None: """Remove a table from the session, and forget the Dataset registered under its name.""" super().deregister_table(name) - self._forget(name) + self._forget(_key(name.split("."))) def _forget(self, name: str) -> None: - """Forget the Dataset registered as ``name``, whose table has been - removed or replaced.""" - name = _unqualified(name) + """Forget the Dataset registered as ``name``, a key ``_key`` + made, whose table has been removed or replaced.""" self._registered_datasets.pop(name, None) self._replacements[name] = self._replacements.get(name, 0) + 1 @@ -799,23 +808,26 @@ def _table_replaced(query: str) -> str | None: return None if match is None else match.group(1) -def _resolved(name: str) -> str: - """``name``, written in SQL, as a plan's display prints it: each part - unquoted, or lowered if it wasn't quoted, joined by dots.""" - return ".".join( +def _parts(name: str) -> list[str]: + """The parts of ``name``, written in SQL, as DataFusion reads them: + each unquoted, or lowered if it wasn't quoted.""" + return [ part[1:-1] if part.startswith('"') else part.lower() for part in re.findall(_PART, name) - ) - - -def _unqualified(name: str) -> str: - """``name`` without DataFusion's default catalog and schema, which a - query may name or leave out: ``datafusion.public.v`` and ``public.v`` - are both ``v``, and ``datafusion.era5.v`` is ``era5.v``.""" - # Two dots or more make the first part a catalog's name. - if name.startswith("datafusion.") and name.count(".") > 1: - name = name[len("datafusion.") :] - return name.removeprefix("public.") + ] + + +def _key(parts: Sequence[str]) -> str: + """The key of the table or view whose name has ``parts``: the parts + joined by dots, without DataFusion's default catalog and schema, which + a query may name or leave out. ``datafusion.public.v`` and + ``public.v`` are both ``v``, and ``datafusion.era5.v`` is ``era5.v``.""" + parts = list(parts) + if len(parts) == 3 and parts[0] == "datafusion": + parts = parts[1:] + if len(parts) == 2 and parts[0] == "public": + parts = parts[1:] + return ".".join(parts) def _missing(values: np.ndarray) -> np.ndarray | None: From 567f6c0e3ba60d09b1dfbeb7b992ac04fd2e352d Mon Sep 17 00:00:00 2001 From: Alex Merose Date: Tue, 17 Nov 2026 19:48:51 -0800 Subject: [PATCH 5/5] Count a failed CREATE OR REPLACE, and DROP SCHEMA - DataFusion drops the old table before it runs a CREATE OR REPLACE's query, so one that fails while it runs leaves no table. It now counts as a replacement when the table is gone. - DROP SCHEMA counts each table and view the schema had. Before, a prepared query of such a table kept returning its old rows. Closes #326 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NyN7idACeDMh94qrnFMu6h --- tests/test_context.py | 25 +++++++++++++++ xarray_sql/sql.py | 74 +++++++++++++++++++++++++++++++------------ 2 files changed, 78 insertions(+), 21 deletions(-) diff --git a/tests/test_context.py b/tests/test_context.py index 4757b588..dd7d27ca 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -111,6 +111,31 @@ def test_registering_a_split_dataset_again_replaces_each_table(): assert _values(ctx, "g.i") == [7.0, 8.0, 9.0] +def test_dropping_a_schema_replaces_each_of_its_tables(ctx): + ctx.from_dataset("g", _split(np.arange(3.0))) + ctx.sql("DROP SCHEMA g CASCADE") + assert dict(ctx.replacements) == {"g.i": 1, "g.i_j": 1} + assert set(ctx.datasets) == {"a", "b"} + + +@pytest.mark.parametrize( + "query, replaced", + [ + # Fails while it runs, after the old table is dropped. + ("SELECT 1 / (v - v) AS v FROM (VALUES (CAST(1 AS INT))) t(v)", True), + # Fails while it's planned, before. + ("SELECT v FROM missing", False), + ], +) +def test_a_replacement_that_fails_counts_if_it_dropped_the_table( + ctx, query, replaced +): + with pytest.raises(Exception): # noqa: B017 - DataFusion's bare Exception + ctx.sql(f"CREATE OR REPLACE TABLE a AS {query}") + assert dict(ctx.replacements) == ({"a": 1} if replaced else {}) + assert ("a" in ctx.datasets) is not replaced + + def test_creating_a_table_or_view_replaces_nothing(ctx): ctx.sql("CREATE OR REPLACE VIEW v AS SELECT v FROM b") ctx.sql("CREATE TABLE c AS SELECT 1") diff --git a/xarray_sql/sql.py b/xarray_sql/sql.py index 08143703..bd4e8cdf 100644 --- a/xarray_sql/sql.py +++ b/xarray_sql/sql.py @@ -152,7 +152,10 @@ def replacements(self) -> Mapping[str, int]: which registering a name again needs first, and a statement run with [sql][xarray_sql.Context.sql] that replaces or drops a table or a view: ``CREATE OR REPLACE TABLE``, ``CREATE OR REPLACE VIEW``, - ``DROP TABLE`` or ``DROP VIEW``. A name never replaced isn't in it. + ``DROP TABLE`` or ``DROP VIEW``, and ``DROP SCHEMA`` for each table + and view in the schema. A ``CREATE OR REPLACE`` that fails counts + if it dropped the old table first. A name never replaced isn't in + it. Names leave out DataFusion's default catalog and schema, as [tables_read][xarray_sql.Context.tables_read] does. Writing new values with [write][xarray_sql.Context.write] doesn't count. @@ -503,23 +506,52 @@ def sql(self, query: str, *args, **kwargs) -> XarrayDataFrame: Returns: An [XarrayDataFrame][xarray_sql.ds.XarrayDataFrame] wrapping the DataFusion DataFrame. """ - # DataFusion runs a statement that replaces or drops a table or a - # view as it plans it, without deregistering it. - replaced = _table_replaced(query) - existed = replaced is not None and self.table_exist(replaced) - if _ad is not None and _ad.calls_ad(query): - if args or kwargs: - raise TypeError( - "a query that calls grad, vjp or jvp takes no other " - "arguments" - ) - df = _ad.sql(self, query) - else: - df = super().sql(query, *args, **kwargs) - if replaced is not None and existed: - self._forget(_key(_parts(replaced))) + # DataFusion runs a statement that replaces or drops a table, a + # view or a schema as it plans it, without deregistering them. + replaced = self._replaced_by(query) + try: + if _ad is not None and _ad.calls_ad(query): + if args or kwargs: + raise TypeError( + "a query that calls grad, vjp or jvp takes no other " + "arguments" + ) + df = _ad.sql(self, query) + else: + df = super().sql(query, *args, **kwargs) + except Exception: + # CREATE OR REPLACE drops the old table before it runs the + # query for the new one, which may then fail. + for key, parts in replaced.items(): + if self._kind(parts) is None: + self._forget(key) + raise + for key in replaced: + self._forget(key) return self._wrap(df) + def _replaced_by(self, query: str) -> dict[str, tuple[str, ...]]: + """The parts of the name of each table and view ``query`` would + replace or drop, by its key.""" + match = _TABLE_DDL.match(query) + if match is not None: + parts = tuple(_parts(match.group(1))) + if self._kind(parts) is None: + return {} + return {_key(parts): parts} + match = _SCHEMA_DROP.match(query) + if match is None: + return {} + *catalog, schema = _parts(match.group(1)) + try: + tables = self.catalog(*catalog).schema(schema).table_names() + except Exception: # noqa: BLE001 - DataFusion raises a bare Exception + return {} + return { + _key((*catalog, schema, table)): (*catalog, schema, table) + for table in tables + } + def deregister_table(self, name: str) -> None: """Remove a table from the session, and forget the Dataset registered under its name.""" @@ -801,11 +833,11 @@ def _copy(ctx: SessionContext, plan: ExecutionPlan) -> ExecutionPlan: ) -def _table_replaced(query: str) -> str | None: - """The name of the table or view ``query`` replaces or drops, as it's - written, or ``None`` for any other statement.""" - match = _TABLE_DDL.match(query) - return None if match is None else match.group(1) +_SCHEMA_DROP = re.compile( + rf"{_GAP}*DROP{_GAP}+SCHEMA{_GAP}+(?:IF{_GAP}+EXISTS{_GAP}+)?" + rf"((?:{_PART})(?:\.(?:{_PART}))?)", + re.IGNORECASE | re.DOTALL, +) def _parts(name: str) -> list[str]: