Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/sql/test_functions.py
6939 views
1
from __future__ import annotations
2
3
from pathlib import Path
4
5
import pytest
6
7
import polars as pl
8
from polars.exceptions import SQLInterfaceError
9
from polars.testing import assert_frame_equal
10
11
12
@pytest.fixture
13
def foods_ipc_path() -> Path:
14
return Path(__file__).parent.parent / "io" / "files" / "foods1.ipc"
15
16
17
def test_sql_expr() -> None:
18
df = pl.DataFrame({"a": [1, 2, 3], "b": ["xyz", "abcde", None]})
19
sql_exprs = pl.sql_expr(
20
[
21
"MIN(a)",
22
"POWER(a,a) AS aa",
23
"SUBSTR(b,2,2) AS b2",
24
]
25
)
26
result = df.select(*sql_exprs)
27
expected = pl.DataFrame(
28
{"a": [1, 1, 1], "aa": [1, 4, 27], "b2": ["yz", "bc", None]}
29
)
30
assert_frame_equal(result, expected)
31
32
# expect expressions that can't reasonably be parsed as expressions to raise
33
# (for example: those that explicitly reference tables and/or use wildcards)
34
with pytest.raises(
35
SQLInterfaceError,
36
match=r"unable to parse 'xyz\.\*' as Expr",
37
):
38
pl.sql_expr("xyz.*")
39
40