Skip to content
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

feat: Control Teradata decimal format when cast to string #1138

Merged
merged 3 commits into from
May 21, 2024
Merged
Changes from all commits
Commits
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
24 changes: 24 additions & 0 deletions third_party/ibis/ibis_teradata/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,30 @@ def teradata_cast_string_to_binary(compiled_arg, from_, to):
return "TO_BYTES({}, 'base16')".format(compiled_arg)


@teradata_cast.register(str, dt.Decimal, dt.String)
def teradata_cast_decimal_to_string(compiled_arg, from_, to):
"""Specialize cast from decimal to string.

Teradata has two behaviours we need to avoid:
1) SELECT CAST(CAST(7 AS DECIMAL(5,2)) AS VARCHAR(64));
7.00
2) SELECT CAST(CAST(-0.7 AS DECIMAL(5,2)) AS VARCHAR(64));
-.70

This function uses a format mask to give these results from above examples:
1) 7
2) -0.7
"""
precision = from_.precision or 38
if from_.scale and from_.scale > 0:
fmt = "FM" + ("9" * (precision - from_.scale)) + "." + ("9" * from_.scale)
return f"RTRIM(TO_CHAR({compiled_arg},'{fmt}'),'.')"
elif from_.scale is not None and from_.scale == 0:
fmt = "FM" + ("9" * (precision - from_.scale))
return f"TO_CHAR({compiled_arg},'{fmt}')"
return "TO_CHAR({},'TM9')".format(compiled_arg)


@teradata_cast.register(str, dt.DataType, dt.DataType)
def teradata_cast_generate(compiled_arg, from_, to):
sql_type = ibis_type_to_teradata_type(to)
Expand Down