diff options
author | Mike Bayer <mike_mp@zzzcomputing.com> | 2021-02-22 09:55:21 -0500 |
---|---|---|
committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2021-02-22 09:56:16 -0500 |
commit | 521af2bffa1b6900b77d6f5c107726bd85414d14 (patch) | |
tree | 0cb1f6d0dc233d8a6a6237b554164185acbc8b7a | |
parent | 47e64c690c4ebde3f0885f5c69419d3c3303818b (diff) | |
download | sqlalchemy-521af2bffa1b6900b77d6f5c107726bd85414d14.tar.gz |
document TypeDecorator schemes for MONEY
this type apparently returns strings so document
cast/processing options.
Change-Id: Idc19527dcf76e1c2d966425716c0fcf60cbba5dc
References: #5965
(cherry picked from commit fcf539d090a95fb179ca03beffd10122e97aa002)
-rw-r--r-- | lib/sqlalchemy/dialects/postgresql/base.py | 36 |
1 files changed, 35 insertions, 1 deletions
diff --git a/lib/sqlalchemy/dialects/postgresql/base.py b/lib/sqlalchemy/dialects/postgresql/base.py index 7dec6d818..a33435216 100644 --- a/lib/sqlalchemy/dialects/postgresql/base.py +++ b/lib/sqlalchemy/dialects/postgresql/base.py @@ -1196,7 +1196,41 @@ PGMacAddr = MACADDR class MONEY(sqltypes.TypeEngine): - """Provide the PostgreSQL MONEY type. + r"""Provide the PostgreSQL MONEY type. + + Depending on driver, result rows using this type may return a + string value which includes currency symbols. + + For this reason, it may be preferable to provide conversion to a + numerically-based currency datatype using :class:`_types.TypeDecorator`:: + + import re + import decimal + from sqlalchemy import TypeDecorator + + class NumericMoney(TypeDecorator): + impl = MONEY + + def process_result_value(self, value: Any, dialect: Any) -> None: + if value is not None: + # adjust this for the currency and numeric + m = re.match(r"\$([\d.]+)", value) + if m: + value = decimal.Decimal(m.group(1)) + return value + + Alternatively, the conversion may be applied as a CAST using + the :meth:`_types.TypeDecorator.column_expression` method as follows:: + + import decimal + from sqlalchemy import cast + from sqlalchemy import TypeDecorator + + class NumericMoney(TypeDecorator): + impl = MONEY + + def column_expression(self, column: Any): + return cast(column, Numeric()) .. versionadded:: 1.2 |