Skip to content

Commit

Permalink
feat: allow construction of decimal literals
Browse files Browse the repository at this point in the history
  • Loading branch information
cpcloud committed Jan 19, 2022
1 parent 65885ab commit 3d9e865
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ibis/expr/datatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import builtins
import collections
import datetime
import decimal
import enum
import functools
import itertools
Expand Down Expand Up @@ -1571,3 +1572,8 @@ def _str_to_uuid(typ: UUID, value: str) -> _uuid.UUID:
@_normalize.register(String, _uuid.UUID)
def _uuid_to_str(typ: String, value: _uuid.UUID) -> str:
return str(value)


@_normalize.register(Decimal, int)
def _int_to_decimal(typ: Decimal, value: int) -> decimal.Decimal:
return decimal.Decimal(value).scaleb(-typ.scale)
2 changes: 2 additions & 0 deletions ibis/expr/operations/generic.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
import decimal
import enum
import functools
import itertools
Expand Down Expand Up @@ -242,6 +243,7 @@ class Literal(ValueOp):
tuple,
type(None),
uuid.UUID,
decimal.Decimal,
)
),
rlz.is_computable_input,
Expand Down
22 changes: 22 additions & 0 deletions ibis/tests/expr/test_value_exprs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import uuid
from collections import OrderedDict
from datetime import date, datetime, time
from decimal import Decimal
from operator import methodcaller

import numpy as np
Expand Down Expand Up @@ -112,13 +113,34 @@ def test_literal_with_implicit_type(value, expected_type):
(tuple(multipolygon1), 'multipolygon'),
pytest.param(uuid.uuid4(), 'uuid', id='uuid'),
pytest.param(str(uuid.uuid4()), 'uuid', id='uuid_str'),
pytest.param(Decimal("234.234"), "decimal(6, 3)", id="decimal_native"),
pytest.param(234234, "decimal(6, 3)", id="decimal_int"),
],
)
def test_literal_with_explicit_type(value, expected_type):
expr = ibis.literal(value, type=expected_type)
assert expr.type().equals(dt.validate_type(expected_type))


@pytest.mark.parametrize(
("value", "expected", "dtype"),
[
# precision > scale
(Decimal("234.234"), Decimal("234.234"), "decimal(6, 3)"),
(234234, Decimal("234.234"), "decimal(6, 3)"),
# scale == 0
(Decimal("234"), Decimal("234"), "decimal(6, 0)"),
(234, Decimal("234"), "decimal(6, 0)"),
# precision == scale
(Decimal(".234"), Decimal(".234"), "decimal(3, 3)"),
(234, Decimal(".234"), "decimal(3, 3)"),
],
)
def test_normalize_decimal_literal(value, expected, dtype):
expr = ibis.literal(value, type=dtype)
assert expr.op().value == expected


@pytest.mark.parametrize(
['value', 'expected_type', 'expected_class'],
[
Expand Down

0 comments on commit 3d9e865

Please sign in to comment.