-
Notifications
You must be signed in to change notification settings - Fork 172
enh: Introduce narwhals.sql
#3254
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MarcoGorelli
wants to merge
12
commits into
narwhals-dev:main
Choose a base branch
from
MarcoGorelli:narwhals-sql
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
de3edcf
document sql
MarcoGorelli 703fcb5
doctest
MarcoGorelli f045a7c
fix test and typing
MarcoGorelli 785c64e
typing in test
MarcoGorelli 5225fe8
type completeness
MarcoGorelli 8deb0a0
wip
MarcoGorelli 7384add
wip
MarcoGorelli beb27bd
Merge remote-tracking branch 'upstream/main' into narwhals-sql
MarcoGorelli 836424a
update docs
MarcoGorelli 651dbe3
update
MarcoGorelli a12842b
skip if no sqlparse
MarcoGorelli 07c4447
add sqlglot note
MarcoGorelli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # `narwhals.sql` | ||
|
|
||
| ::: narwhals.sql | ||
| handler: python | ||
| options: | ||
| members: | ||
| - table |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| from narwhals._duckdb.utils import DeferredTimeZone, narwhals_to_native_dtype | ||
| from narwhals.translate import from_native | ||
| from narwhals.utils import Version | ||
|
|
||
| if TYPE_CHECKING: | ||
| from duckdb import DuckDBPyRelation | ||
|
|
||
| from narwhals.dataframe import LazyFrame | ||
| from narwhals.typing import IntoSchema | ||
|
|
||
| try: | ||
| import duckdb # ignore-banned-import | ||
| except ImportError as _exc: # pragma: no cover | ||
| msg = ( | ||
| "`narwhals.sql` requires DuckDB to be installed.\n\n" | ||
| "Hint: run `pip install -U narwhals[sql]`" | ||
| ) | ||
| raise ModuleNotFoundError(msg) from _exc | ||
|
|
||
| CONN = duckdb.connect() | ||
| TZ = DeferredTimeZone( | ||
| CONN.sql("select value from duckdb_settings() where name = 'TimeZone'") | ||
| ) | ||
|
|
||
|
|
||
| def table(name: str, schema: IntoSchema) -> LazyFrame[DuckDBPyRelation]: | ||
| """Generate standalone LazyFrame which you can use to generate SQL. | ||
|
|
||
| Note that this requires DuckDB to be installed. | ||
|
|
||
| Parameters: | ||
| name: Table name. | ||
| schema: Table schema. | ||
|
|
||
| Returns: | ||
| A LazyFrame. | ||
|
|
||
| Examples: | ||
| >>> import narwhals as nw | ||
| >>> from narwhals.sql import table | ||
| >>> schema = {"date": nw.Date, "price": nw.Int64, "symbol": nw.String} | ||
| >>> assets = table("assets", schema) | ||
| >>> result = assets.filter(nw.col("price") > 100) | ||
| >>> print(result.to_native().sql_query()) | ||
| SELECT * FROM main.assets WHERE (price > 100) | ||
| """ | ||
| column_mapping = { | ||
| col: narwhals_to_native_dtype(dtype, Version.MAIN, TZ) | ||
| for col, dtype in schema.items() | ||
| } | ||
| dtypes = ", ".join(f"{col} {dtype}" for col, dtype in column_mapping.items()) | ||
| CONN.sql(f""" | ||
| CREATE TABLE "{name}" | ||
| ({dtypes}); | ||
| """) | ||
| return from_native(CONN.table(name)) | ||
|
||
|
|
||
|
|
||
| __all__ = ["table"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import pytest | ||
|
|
||
| import narwhals as nw | ||
| from tests.utils import DUCKDB_VERSION | ||
|
|
||
|
|
||
| def test_sql() -> None: | ||
| pytest.importorskip("duckdb") | ||
| if DUCKDB_VERSION < (1, 3): | ||
| pytest.skip() | ||
| from narwhals.sql import table | ||
|
|
||
| schema = {"date": nw.Date(), "price": nw.Int64(), "symbol": nw.String()} | ||
| assets = table("assets", schema) | ||
| result = ( | ||
| assets.with_columns( | ||
| returns=(nw.col("price") / nw.col("price").shift(1)).over( | ||
| "symbol", order_by="date" | ||
| ) | ||
| ) | ||
| .to_native() | ||
| .sql_query() | ||
| ) | ||
| expected = """SELECT date, price, symbol, (price / lag(price, 1) OVER (PARTITION BY symbol ORDER BY date ASC NULLS FIRST)) AS "returns" FROM main.assets""" | ||
| assert result == expected |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think (hope?) that in the future we could make a
narwhals-sqlglotornarwhals-substraitplugin and use that here. But for now, I think using DuckDB for this is quite nice