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_bitwise.py
8375 views
1
from __future__ import annotations
2
3
import pytest
4
5
import polars as pl
6
7
8
@pytest.fixture
9
def df() -> pl.DataFrame:
10
return pl.DataFrame(
11
{
12
"x": [20, 32, 50, 88, 128],
13
"y": [-128, 0, 10, -1, None],
14
}
15
)
16
17
18
def test_bitwise_and(df: pl.DataFrame) -> None:
19
res = df.sql(
20
"""
21
SELECT
22
x & y AS x_bitand_op_y,
23
BITAND(y, x) AS y_bitand_x,
24
BIT_AND(x, y) AS x_bitand_y,
25
FROM self
26
"""
27
)
28
assert res.to_dict(as_series=False) == {
29
"x_bitand_op_y": [0, 0, 2, 88, None],
30
"y_bitand_x": [0, 0, 2, 88, None],
31
"x_bitand_y": [0, 0, 2, 88, None],
32
}
33
34
35
def test_bitwise_count(df: pl.DataFrame) -> None:
36
res = df.sql(
37
"""
38
SELECT
39
BITCOUNT(x) AS x_bits_set,
40
BIT_COUNT(y) AS y_bits_set,
41
FROM self
42
"""
43
)
44
assert res.to_dict(as_series=False) == {
45
"x_bits_set": [2, 1, 3, 3, 1],
46
"y_bits_set": [57, 0, 2, 64, None],
47
}
48
49
50
def test_bitwise_not(df: pl.DataFrame) -> None:
51
res = df.sql(
52
"""
53
SELECT
54
-- note: operator support pending...
55
-- https://github.com/apache/datafusion-sqlparser-rs/pull/2081
56
-- ~x AS bit_not_op_x,
57
BIT_NOT(-x) AS bit_not_minus_x,
58
BITNOT(y) AS bitnot_y,
59
FROM self
60
"""
61
)
62
assert res.to_dict(as_series=False) == {
63
"bit_not_minus_x": [19, 31, 49, 87, 127],
64
"bitnot_y": [127, -1, -11, 0, None],
65
}
66
67
68
def test_bitwise_or(df: pl.DataFrame) -> None:
69
res = df.sql(
70
"""
71
SELECT
72
x | y AS x_bitor_op_y,
73
BITOR(y, x) AS y_bitor_x,
74
BIT_OR(x, y) AS x_bitor_y,
75
FROM self
76
"""
77
)
78
assert res.to_dict(as_series=False) == {
79
"x_bitor_op_y": [-108, 32, 58, -1, None],
80
"y_bitor_x": [-108, 32, 58, -1, None],
81
"x_bitor_y": [-108, 32, 58, -1, None],
82
}
83
84
85
def test_bitwise_xor(df: pl.DataFrame) -> None:
86
res = df.sql(
87
"""
88
SELECT
89
x XOR y AS x_bitxor_op_y,
90
BITXOR(y, x) AS y_bitxor_x,
91
BIT_XOR(x, y) AS x_bitxor_y,
92
FROM self
93
"""
94
)
95
assert res.to_dict(as_series=False) == {
96
"x_bitxor_op_y": [-108, 32, 56, -89, None],
97
"y_bitxor_x": [-108, 32, 56, -89, None],
98
"x_bitxor_y": [-108, 32, 56, -89, None],
99
}
100
101