Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
97 commits
Select commit Hold shift + click to select a range
72506db
engine bump
JelteF Nov 1, 2026
232080e
engine bump (#734)
evertlammerts Nov 1, 2026
a8c7ee4
Convert object columns appended or given a Spark schema into the decl…
evertlammerts Nov 5, 2026
9e12946
Read numpy scalars and every map key form through the declared types
evertlammerts Nov 5, 2026
287e582
Keep a polars filter that casts a column out of the pushed predicate
evertlammerts Nov 5, 2026
cb4870a
Let a view over a file-like reader own its data, and one object store…
evertlammerts Nov 5, 2026
6aef523
Convert object columns appended or given a Spark schema into the decl…
evertlammerts Nov 5, 2026
ed606d9
Read numpy scalars in the appender as the declared object columns rea…
evertlammerts Nov 5, 2026
b01dc18
Pin the classic S3 client for the staging upload and give the h2oai d…
evertlammerts Nov 5, 2026
9c07d16
Raise a map() function's exception as an engine error and take an all…
evertlammerts Nov 5, 2026
5b36cbd
Stop calling classes in type conversion, refuse lone surrogates in na…
evertlammerts Nov 5, 2026
3bb144a
Prune row groups for zoned and time constants in the column's unit, n…
evertlammerts Nov 5, 2026
f9d0cef
Stop forcing a macOS 10.7 deployment minimum onto the module's objects
evertlammerts Nov 5, 2026
b2e0ea6
Accept Python 3.15's wording of the attribute suggestion in the remov…
evertlammerts Nov 6, 2026
c180214
Make map() keep its column types, ENUMs included
evertlammerts Nov 6, 2026
c0f203b
Raise a map() function's exception as an engine error and take an all…
evertlammerts Nov 6, 2026
891364f
Merge v2.0-cyanoptera into fix-map-types: a column bound NULL takes t…
evertlammerts Nov 6, 2026
e4c2e1d
Push exact widening casts bare and the translatable conjuncts of an A…
evertlammerts Nov 6, 2026
8b44a4a
Stop forcing a macOS 10.7 deployment minimum onto the module's object…
evertlammerts Nov 6, 2026
452d322
Own a view's sources on a subquery, refuse a file-like view in a data…
evertlammerts Nov 6, 2026
d5ddcb0
Decode a dictionary backed string column chunk by chunk, test it with…
evertlammerts Nov 6, 2026
9683cde
Say retry up to 6 times, and remove a download that never opened with…
evertlammerts Nov 6, 2026
3ed9e9f
Read a tuple of paths like a list, check pandas STRUCT keys, run the …
evertlammerts Nov 6, 2026
202992d
Read numpy float, str and bytes scalars as they are, keep the nanosec…
evertlammerts Nov 6, 2026
984af33
Cache only numpy's own scalar classes, name tuples in the empty paths…
evertlammerts Nov 6, 2026
b38c021
Pin that con.append keeps the trailing NUL characters of numpy str an…
evertlammerts Nov 6, 2026
68ea03a
Push only translations that read as polars does: modulus with the div…
evertlammerts Nov 6, 2026
808c19e
Type a Float32 literal as FLOAT and compare UUID and JSON columns as …
evertlammerts Nov 6, 2026
b504c5e
Read a map() cell into an inferred type only when its kind fits, keep…
evertlammerts Nov 6, 2026
24f406a
Run mypy in a child process in the two stub tests so its recursion li…
evertlammerts Nov 6, 2026
2ed45dd
Build the stable ABI, lend no type from a NULL input, shape only cont…
evertlammerts Nov 6, 2026
90776a9
Prune row groups for zoned and time constants in the column's unit, n…
evertlammerts Nov 6, 2026
5f489fb
Read numpy scalars in the appender as the declared object columns rea…
evertlammerts Nov 6, 2026
6746e39
Give the key and value list form of a MAP the entry rules, count a Ti…
evertlammerts Nov 6, 2026
66a35e7
Read an aware datetime once in the TIMESTAMP fast path and detect the…
evertlammerts Nov 6, 2026
0da3cbf
Take a dict as MAP keys and values only for two lists, read a declare…
evertlammerts Nov 7, 2026
ca7f935
Merge v2.0-cyanoptera into fix-map-types: numpy scalars read through …
evertlammerts Nov 7, 2026
fee081e
Stage a MAP column's keys and values once per vector and index a STRU…
evertlammerts Nov 7, 2026
5ee6ecc
Clear the STRUCT field index from the outermost scan only, take exact…
evertlammerts Nov 7, 2026
e4bb2a7
Nest the reentrancy test's scans on one thread and pin the zoned nano…
evertlammerts Nov 7, 2026
b209f2f
Let a view over a file-like reader own its data, and one object store…
evertlammerts Nov 7, 2026
756de11
Push a polars filter to DuckDB only where it reads the same (#740)
evertlammerts Nov 7, 2026
4583a30
Pin the classic S3 client for the staging upload and give the h2oai d…
evertlammerts Nov 7, 2026
50f050d
Bump submodule
duckdblabs-bot Nov 9, 2026
c2556ed
[duckdb-labs bot] Bump DuckDB submodule (#751)
evertlammerts Nov 9, 2026
84f9634
Regenerate the benchmark baseline for v2.0-cyanoptera at engine 29b26…
evertlammerts Nov 9, 2026
9ca5aa3
Regenerate the benchmark baseline for v2.0-cyanoptera at engine 29b26…
evertlammerts Nov 9, 2026
9befd80
Stop calling classes in type conversion, refuse lone surrogates in na…
evertlammerts Nov 10, 2026
da7f1b4
Make map() keep its column types, ENUMs included (#744)
evertlammerts Nov 10, 2026
7fa2cfe
Hold one connection claim from submission to settling in execute, exe…
evertlammerts Nov 10, 2026
8e73d3f
Refuse a submitting call on arrival while another thread's submitting…
evertlammerts Nov 10, 2026
27e7efb
Let the executemany collision test retry past the refusal between par…
evertlammerts Nov 11, 2026
ad67684
Register the DB-API result inside execute's claim, mark the Arrow tes…
evertlammerts Nov 11, 2026
efe893a
Supersede a result the parameter code registered before execute's cla…
evertlammerts Nov 11, 2026
b54a0f1
Pin the unread nested result case and retry the Arrow fetch test by time
evertlammerts Nov 11, 2026
efdbaa5
Bump submodule
duckdblabs-bot Nov 11, 2026
e020ee3
[duckdb-labs bot] Bump DuckDB submodule (#766)
evertlammerts Nov 11, 2026
be4f0b0
Bump submodule
duckdblabs-bot Nov 11, 2026
fd7028f
Follow the engine's text for a folded range with an exclusive bound i…
evertlammerts Nov 12, 2026
32b9950
[duckdb-labs bot] Bump DuckDB submodule (#767)
evertlammerts Nov 12, 2026
2ae8c66
Merge remote-tracking branch 'upstream/v2.0-cyanoptera' into fix-betw…
evertlammerts Nov 12, 2026
dfca0f4
Move the engine pin to 76e6bf79426, which prints an exclusive bound o…
evertlammerts Nov 12, 2026
007b3bc
Move the engine pin to 76e6bf79426 and follow its text for a folded r…
evertlammerts Nov 12, 2026
93e7020
Move the engine pin to cb5673685153 and follow its statement text, wh…
evertlammerts Nov 13, 2026
b3098a6
Move the engine pin to cb5673685153 and follow its statement text (#772)
evertlammerts Nov 13, 2026
f8551ea
Move the engine pin to 0c429a4d and follow its MERGE multi match revert
evertlammerts Nov 17, 2026
66ac141
Move the engine pin to 0c429a4d and follow its MERGE multi match reve…
evertlammerts Nov 17, 2026
4d3b766
Bump submodule
duckdblabs-bot Nov 17, 2026
db70c60
[duckdb-labs bot] Bump DuckDB submodule (#779)
evertlammerts Nov 17, 2026
6819cb7
Bump submodule
duckdblabs-bot Nov 18, 2026
13a4e33
[duckdb-labs bot] Bump DuckDB submodule (#780)
evertlammerts Nov 18, 2026
25d5949
Bump submodule
duckdblabs-bot Nov 18, 2026
169de19
[duckdb-labs bot] Bump DuckDB submodule (#781)
evertlammerts Nov 18, 2026
fd05ced
pin submodule to v2.0.1 release commit
evertlammerts Nov 19, 2026
ac3eb2e
Silence nanobind's exit leak report in builds without assertions
evertlammerts Nov 8, 2026
846a95f
Keep the exit leak checks live through a private switch and give duck…
evertlammerts Nov 10, 2026
de8eed7
Silence nanobind exit leak report (#784)
evertlammerts Nov 19, 2026
96dbebb
Bump release_version to 2.0.2 after releasing 2.0.1
duckdblabs-bot Nov 20, 2026
4e0bc49
[duckdb-labs bot] Bump release_version to 2.0.2 (#785)
evertlammerts Nov 23, 2026
f0bec5b
Let the atexit hook leave open a result whose connection a stuck thre…
evertlammerts Nov 23, 2026
bd223bc
Let the atexit hook leave open a result whose connection a stuck thre…
evertlammerts Nov 24, 2026
e2379b4
Push the comparisons polars 2.2 folds into the lazy frame scan
evertlammerts Nov 25, 2026
f5d8d78
End a result whose streaming fetch fails with the engine's error
evertlammerts Nov 24, 2026
454263f
Read __main__ from sys.modules when detecting an interactive session
evertlammerts Nov 25, 2026
115aebc
Skip the connection checks after a lazy polars join on polars 2.2.0
evertlammerts Nov 26, 2026
ed6e011
Skip the lazy polars join test on polars 2.2.0
evertlammerts Nov 29, 2026
cdaa3c4
Bound the exit tests with a sort on runners where the fetching thread…
evertlammerts Nov 30, 2026
144292e
Push the comparisons polars 2.2 folds into the lazy frame scan (#794)
evertlammerts Nov 30, 2026
72101ad
Merge branch 'v2.0-cyanoptera' into fix-exit-hook-clear-interrupt-last
evertlammerts Nov 30, 2026
c0cf524
Merge branch 'v2.0-cyanoptera' into fix-import-without-main
evertlammerts Nov 30, 2026
ad8c731
End a result whose streaming fetch fails with the engine's error (#793)
evertlammerts Nov 30, 2026
7be886a
Merge branch 'v2.0-cyanoptera' into fix-import-without-main
evertlammerts Nov 30, 2026
8e1aec3
Read __main__ from sys.modules in the interactive check (#801)
evertlammerts Nov 30, 2026
3e0be28
Merge remote-tracking branch 'upstream/v2.0-cyanoptera' into fix-exec…
evertlammerts Nov 30, 2026
a34833c
Hold one connection claim from submit to settle (#802)
evertlammerts Nov 30, 2026
86fc516
Merge branch 'v2.0-cyanoptera' into main
evertlammerts Nov 30, 2026
3cb427c
Follow main's engine in the fixes merged from v2.0-cyanoptera
evertlammerts Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/actions/build-wheel/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ runs:
CIBW_BEFORE_TEST: >
uv sync --active --inexact --only-group test --no-install-project --directory {project}
CIBW_TEST_COMMAND: >
uv run -v pytest --confcutdir=. --rootdir . -c {project}/pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }}
uv run python -c "import _duckdb; assert not _duckdb._assertions, 'the wheel was built with assertions'"
&& uv run -v pytest --confcutdir=. --rootdir . -c {project}/pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }}

# The stable ABI wheel must import nothing outside the stable ABI, which compiling with Py_LIMITED_API does
# not prove for symbols pulled in by inline functions or dependencies.
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/assert_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ jobs:
import _duckdb
print(_duckdb.__file__)
assert "abi3" not in _duckdb.__file__, "expected a full-API module, got " + _duckdb.__file__
assert _duckdb._assertions, "expected a build with assertions, which keeps nanobind's exit leak report"
EOF

- name: Run the tests
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/packaging_sdist.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ jobs:
cd ${{ runner.temp }}
uv venv
uv pip install ${{ github.workspace }}/dist/duckdb-*.tar.gz
# an sdist install is a build without assertions, which keeps nanobind's exit leak report off
uv run python -c "import _duckdb; assert not _duckdb._assertions, 'the sdist was built with assertions'"

- name: Test sdist
if: ${{ inputs.testsuite != 'none' }}
Expand Down
54 changes: 53 additions & 1 deletion .github/workflows/packaging_wheels.yml
Original file line number Diff line number Diff line change
Expand Up @@ -251,5 +251,57 @@ jobs:
testrun=$(uv run --no-project --python "$venv" python -c 'import tempfile; print(tempfile.mkdtemp(prefix="duckdb-testrun-"))')
cp -r tests pyproject.toml "$testrun"
cd "$testrun"
uv run --no-project --python "$venv" python -c "import duckdb, sys, os; print(duckdb.__version__, sys.version, os.getcwd())"
# A wheel built with assertions would print nanobind's exit leak report to every user.
uv run --no-project --python "$venv" python - <<'EOF'
import os
import sys

import _duckdb
import duckdb

print(duckdb.__version__, sys.version, os.getcwd())
assert not _duckdb._assertions, "the wheel was built with assertions"
EOF
uv run --no-project --python "$venv" pytest --confcutdir=. --rootdir . -c pyproject.toml ${{ inputs.testsuite == 'fast' && './tests/fast' || './tests' }}

test_pandas_2:
name: 'Test pandas 2: py3.12-manylinux_x86_64'
# The test dependency group installs pandas 3, which decodes a dictionary when it builds a string column, so the
# dictionary backed string columns of pandas 2 are read only here. The package itself accepts any pandas.
if: ${{ !cancelled() && inputs.testsuite != 'none' }}
needs: seed_wheels
runs-on: ubuntu-24.04
steps:
- name: Checkout DuckDB Python
uses: actions/checkout@v4
with:
ref: ${{ inputs.duckdb-python-sha }}

- name: Fetch the wheel
uses: actions/download-artifact@v4
with:
name: wheel-cp312-manylinux_x86_64
path: wheelhouse

- uses: actions/setup-python@v5
with:
python-version: '3.12'

- uses: astral-sh/setup-uv@v10.3.0
with:
version: "0.12.23"
enable-cache: false

# pandas 2.2 converts a dictionary backed string column with to_numpy only from pyarrow 25 on.
- name: Install the wheel with pandas 2.2 and run the pandas string tests
shell: bash
run: |
set -eo pipefail
uv venv --python 3.12 .venv-pandas-2
uv pip install --python .venv-pandas-2 wheelhouse/*.whl "pandas==2.2.3" "pyarrow==18.1.0" pytest pytest-timeout packaging
venv="$PWD/.venv-pandas-2"
testrun=$(uv run --no-project --python "$venv" python -c 'import tempfile; print(tempfile.mkdtemp(prefix="duckdb-testrun-"))')
cp -r tests pyproject.toml "$testrun"
cd "$testrun"
uv run --no-project --python "$venv" python -c "import duckdb, pandas, pyarrow; print(duckdb.__version__, pandas.__version__, pyarrow.__version__)"
uv run --no-project --python "$venv" pytest --confcutdir=. --rootdir . -c pyproject.toml ./tests/fast/pandas/test_pandas_string.py
13 changes: 9 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,15 +310,20 @@ touches the GIL against all five.
4. **A Python error never leaves an engine task as a Python object.** Convert it under the GIL with `AsDuckDBError`
(map, UDFs, the numpy scans, the Python file system do). The engine stores and formats errors later on any thread
without the GIL; a `nb::python_error` there needs the GIL at a moment nobody can give it.
5. **Shutdown has an order.** The atexit hook (`OnInterpreterExit`) calls `engine::BeginExit`, then ends every live
result (`engine::Result::Live`, `EndIfRunning`) with the GIL released so their tasks can finish. From then on only
5. **Shutdown has an order.** The atexit hook (`OnInterpreterExit`) calls `engine::BeginExit`, then ends the live
results (`engine::Result::Live`, `engine::Result::EndAtExit`) with the GIL released so their tasks can finish: it
interrupts the query of every running result, retries the claims of their connections without blocking until
none is refused or one second has passed, closes each result still running once its claim is taken and clears
that connection's interrupt, and leaves the others open. From then on only
the exit thread's own queries may enter Python; a query another thread starts late fails at the gate with "the
Python interpreter is shutting down". Once `Py_IsInitialized()` is false, CPython still lets the exit thread in and so
does the gate, but what that thread opens then admits no other thread; every other thread is refused. Results join
the registry through `Result::Register` at submit and leave in their destructor.

Known gaps: five destructors reach Python through nanobind's cleanup guard during finalization; before Python 3.13 a
daemon thread woken after finalization aborts through the engine's frames (tests skip those cases on 3.12).
Known gaps: five destructors reach Python through nanobind's cleanup guard during finalization; the close of a
running result waits for every task of its query, so an engine worker stuck in a read no interrupt reaches holds
up the exit until the read returns; before Python 3.13 a daemon thread woken after finalization aborts through the
engine's frames (tests skip those cases on 3.12).

## Project structure

Expand Down
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,13 @@ target_include_directories(
# link time. No-op on non-Windows.
target_compile_definitions(_duckdb_dependencies INTERFACE DUCKDB_STATIC_BUILD)

# NB_DOMAIN gives the module nanobind state of its own: the exit leak report
# flag, the type registry and the exception translators are otherwise shared
# with every nanobind extension in the process that has the same ABI key. It
# must reach the object library that expands NB_MODULE, so it sits here and not
# on nanobind_add_module.
target_compile_definitions(_duckdb_dependencies INTERFACE NB_DOMAIN=duckdb)

foreach(flag IN LISTS DUCKDB_PY_ARCHITECTURE_FLAGS)
target_compile_options(_duckdb_dependencies
INTERFACE "$<$<CONFIG:Release>:${flag}>")
Expand Down
37 changes: 33 additions & 4 deletions _duckdb-stubs/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,13 @@ class DuckDBPyConnection:
def from_arrow(self, arrow_object: object) -> DuckDBPyRelation: ...
def from_csv_auto(
self,
path_or_buffer: str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str],
path_or_buffer: str
| bytes
| os.PathLike[str]
| os.PathLike[bytes]
| typing.IO[bytes]
| typing.IO[str]
| Sequence[str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str]],
header: bool | int | None = None,
compression: CsvCompression | None = None,
sep: str | None = None,
Expand Down Expand Up @@ -326,7 +332,13 @@ class DuckDBPyConnection:
def query_progress(self) -> float: ...
def read_csv(
self,
path_or_buffer: str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str],
path_or_buffer: str
| bytes
| os.PathLike[str]
| os.PathLike[bytes]
| typing.IO[bytes]
| typing.IO[str]
| Sequence[str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str]],
header: bool | int | None = None,
compression: CsvCompression | None = None,
sep: str | None = None,
Expand Down Expand Up @@ -371,7 +383,13 @@ class DuckDBPyConnection:
) -> DuckDBPyRelation: ...
def read_json(
self,
path_or_buffer: str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str],
path_or_buffer: str
| bytes
| os.PathLike[str]
| os.PathLike[bytes]
| typing.IO[bytes]
| typing.IO[str]
| Sequence[str | bytes | os.PathLike[str] | os.PathLike[bytes] | typing.IO[bytes] | typing.IO[str]],
*,
columns: ColumnsTypes | None = None,
sample_size: int | None = None,
Expand Down Expand Up @@ -412,6 +430,9 @@ class DuckDBPyConnection:
) -> DuckDBPyRelation: ...
def register(self, view_name: str, python_object: object) -> DuckDBPyConnection: ...
def _register_arrow_source(self, view_name: str, source: object) -> DuckDBPyConnection: ...
def _register_declared(
self, view_name: str, df: object, types: list[sqltypes.DuckDBPyType | None]
) -> DuckDBPyConnection: ...
@typing.overload
def _bind(
self,
Expand Down Expand Up @@ -490,7 +511,13 @@ class DuckDBPyConnection:
def _own_sources(self, name: str, handles: lst[SourceHandle]) -> None: ...
def _catalog_version(self) -> int: ...
def _create_view(
self, name: str | tuple[str, ...] | lst[str], sql: str, *, temporary: bool = False, replace: bool = False
self,
name: str | tuple[str, ...] | lst[str],
sql: str,
*,
temporary: bool = False,
replace: bool = False,
sources: lst[SourceHandle] = ...,
) -> None: ...
def _table_kind(self, name: str | tuple[str, ...] | lst[str]) -> str: ...
def _name_scope(self, name: str) -> str: ...
Expand Down Expand Up @@ -746,6 +773,7 @@ def string_type(collation: str = "", *, connection: DuckDBPyConnection | None =
def struct_type(fields: IntoFields, *, connection: DuckDBPyConnection | None = None) -> sqltypes.DuckDBPyType: ...
def tf(*, connection: DuckDBPyConnection | None = None) -> dict[str, typing.Any]: ...
def _set_arrow_sources(sources: object) -> None: ...
def _set_leak_report(enabled: bool) -> None: ...
def _literal_type(value: object) -> str: ...
def _value_literal(value: object) -> str: ...
def _collation(type: sqltypes.DuckDBPyType) -> str | None: ...
Expand Down Expand Up @@ -776,6 +804,7 @@ __interactive__: bool
__jupyter__: bool
__standard_vector_size__: int
__version__: str
_assertions: bool
_clean_default_connection: typing.Any # value = <capsule object>
apilevel: str
paramstyle: str
Expand Down
3 changes: 0 additions & 3 deletions cmake/duckdb_loader.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,6 @@ function(_duckdb_create_interface_target target_name)
# functions
/utf-8 # treat source files as UTF-8 encoded
)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
# libc++ rather than the older libstdc++
target_compile_options(${target_name} INTERFACE -stdlib=libc++)
endif()

# Link to the DuckDB static library
Expand Down
17 changes: 11 additions & 6 deletions duckdb/_relation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1822,7 +1822,7 @@ def _column(self, name: str) -> DuckDBPyRelation:
if replacement is not None:
msg = (
f"Relations no longer have {name}(): a relation keeps no result between calls, so every call "
f"runs it again. Use {replacement} instead."
f"runs it again. Use {replacement} instead"
)
raise AttributeError(msg)
msg = f"This relation does not contain a column by the name of '{name}'"
Expand Down Expand Up @@ -2859,9 +2859,10 @@ def create_view(self, view_name: str | tuple[str, ...], replace: bool = True) ->
"""
path = _name_path(self._con, view_name)
body, _ = _render(self, literals=True, wrap_text=True)
# The view holds the table reference of every registry name it reads, so its catalog entry owns its sources
# and its transaction decides when they go; a Python object in a database file is refused there.
_seam.create_view(self._con, path, body, replace=replace)
# The view holds the table reference of every registry name it reads and the handles of every source the
# relation reads, so its catalog entry owns its sources and its transaction decides when they go; a Python
# object in a database file is refused there.
_seam.create_view(self._con, path, body, replace=replace, sources=self._sources())
return self

to_view = create_view
Expand Down Expand Up @@ -3589,6 +3590,8 @@ def _catalog_relation(
otherwise; a tuple is the parts of the name.
"""
_ensure_open(con)
if isinstance(name, str):
_encodable(name)
parts = _name_parts(name)
if isinstance(name, str) and len(parts) > 1 and _seam.name_scope(con, parts[0]) == "none":
relation = _catalog_source(con, (name,), step_class, qualified=False)
Expand Down Expand Up @@ -3697,9 +3700,11 @@ def one(item: object) -> str:
handles.append(handle)
return handle.name

if isinstance(source, list):
if isinstance(source, (list, tuple)):
if not source:
raise _error(_duckdb.InvalidInputException, "Please provide a non-empty list of paths or file-like objects")
raise _error(
_duckdb.InvalidInputException, "Please provide a non-empty list or tuple of paths or file-like objects"
)
paths = [one(item) for item in source]
return _option_literal(paths), tuple(handles)
return _option_literal(one(source)), tuple(handles)
Expand Down
17 changes: 14 additions & 3 deletions duckdb/_seam.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,20 @@ def register_filelike(con: _duckdb.DuckDBPyConnection, obj: object) -> SourceHan
return con._register_filelike(obj)


def create_view(con: _duckdb.DuckDBPyConnection, name: tuple[str, ...], sql: str, *, replace: bool) -> None:
"""Create the persistent view at the path `name` over the SELECT in `sql`; it owns the Python objects it reads."""
con._create_view(name, sql, replace=replace)
def create_view(
con: _duckdb.DuckDBPyConnection,
name: tuple[str, ...],
sql: str,
*,
replace: bool,
sources: Sequence[SourceHandle] = (),
) -> None:
"""Create the persistent view at the path `name` over the SELECT in `sql`.

The view owns what the registry names it reads and the `sources` handles of the relation it was made from, among
them the file-like objects the SELECT reads by their object store path, for as long as it exists.
"""
con._create_view(name, sql, replace=replace, sources=list(sources))


def check_text(con: _duckdb.DuckDBPyConnection, text: str, shape: str) -> int:
Expand Down
49 changes: 37 additions & 12 deletions duckdb/_sources/to_arrow.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""A predicate tree as a pyarrow compute expression that a Dataset scanner evaluates exactly as the engine would.

A constant becomes a scalar of its own engine type, never of the column's Arrow type, so a value between two points
of a coarser column keeps its meaning; a zoned scalar is labelled with the column's zone, since pyarrow compares
across units but not across zones.
A constant becomes a scalar of its own engine type, except a zoned timestamp or time constant, which is compared as a
scalar of the column's own type, the form pyarrow tests against Parquet row group statistics; one between two points
of a coarser column is compared with the point below it, under the operator that keeps its meaning, since no row of
the column equals it.
"""

from __future__ import annotations
Expand Down Expand Up @@ -76,7 +77,7 @@ def _translate(node: Node, schema: pa.Schema) -> pc.Expression:
return _column(schema, parts)[0].is_valid()
case Binary(op=op, left=Col(parts=parts), right=Lit() as constant) if op in _COMPARISONS:
field, kind = _column(schema, parts)
compared = _COMPARISONS[op](field, _scalar(constant, kind))
compared = _compare(op, field, kind, _scalar(constant, kind))
if op in (">", ">=") and pa.types.is_floating(kind):
# The engine orders NaN above every number; NaN alone is unequal to itself, also in a dictionary,
# where pyarrow has no is_nan kernel.
Expand Down Expand Up @@ -236,6 +237,24 @@ def _scalar(constant: Lit, kind: pa.DataType) -> pa.Scalar:
return pa.scalar(constant.value, own)


def _compare(op: str, field: pc.Expression, kind: pa.DataType, scalar: pa.Scalar) -> pc.Expression:
"""`field op scalar`, with a zoned timestamp or time constant in the column's own unit."""
import pyarrow as pa
import pyarrow.compute as pc

if not _in_column_unit(kind):
return _COMPARISONS[op](field, scalar)
point, exact = _point_below(scalar.value, kind.unit)
below = pa.scalar(point, kind)
if exact:
return _COMPARISONS[op](field, below)
if op in (">", ">="):
return field > below
if op in ("<", "<="):
return field <= below
return pc.if_else(field.is_valid(), pa.scalar(op == "!="), pa.scalar(None, pa.bool_()))


def _membership(field: pc.Expression, kind: pa.DataType, values: Sequence[Node]) -> pc.Expression:
"""Membership of `field` in the constants, each converted exactly to the column's own type."""
import pyarrow as pa
Expand Down Expand Up @@ -264,17 +283,23 @@ def _held(scalar: pa.Scalar, kind: pa.DataType) -> object:
"""The scalar's value as a value of the column's type, or None when no row of the column can hold it."""
import pyarrow as pa

if pa.types.is_timestamp(kind) and kind.tz is not None:
return _on_grid(scalar.value, kind.unit)
if pa.types.is_time(kind):
return _on_grid(scalar.value, kind.unit)
if _in_column_unit(kind):
point, exact = _point_below(scalar.value, kind.unit)
return point if exact else None
value = scalar.as_py()
if pa.types.is_fixed_size_binary(kind) and len(value) != kind.byte_width:
return None
return value


def _on_grid(count: int, unit: str) -> int | None:
"""A count of microseconds as a count of `unit`, or None when it lies between two of them."""
step = 1_000_000 // _PER_SECOND[unit]
return count // step if count % step == 0 else None
def _in_column_unit(kind: pa.DataType) -> bool:
"""Whether a constant arrives in microseconds and is converted into the column's unit: a zoned timestamp or time."""
import pyarrow as pa

return pa.types.is_time(kind) or (pa.types.is_timestamp(kind) and kind.tz is not None)


def _point_below(count: int, unit: str) -> tuple[int, bool]:
"""A count of microseconds as the count of `unit` at or below it, and whether it is exactly that point."""
point, rest = divmod(count, 1_000_000 // _PER_SECOND[unit])
return point, rest == 0
Loading
Loading