:tickets: 9752
- Generalized the MSSQL :func:`.try_cast` function to any dialect.
+ Generalized the MSSQL :func:`.try_cast` function so that other
+ extension dialects can use it (MSSQL is the only builtin dialect
+ that currently supports it).
+
This implements a cast where
un-castable values are returned as NULL, instead of raising an error.
- Now this function can be taken advantage of by third party dialects
- that also support this function, such as
+ These are a few third party dialects that could implement this:
* ``SAFE_CAST`` in Google BigQuery
* ``TRY_CAST`` in DuckDB
from .expression import text as text
from .expression import true as true
from .expression import True_ as True_
+from .expression import try_cast as try_cast
from .expression import tuple_ as tuple_
from .expression import type_coerce as type_coerce
from .expression import union as union
:func:`.try_cast` - an alternative to CAST that results in
NULLs when the cast fails, instead of raising an error.
+ Only supported by some dialects.
:func:`.type_coerce` - an alternative to CAST that coerces the type
on the Python side only, which is often sufficient to generate the
def try_cast(*arg, **kw):
- """Create a TRY_CAST expression.
+ """Produce a ``TRY_CAST`` expression.
+
+ :func:`.try_cast` returns an instance of :class:`.TryCast`.
+
+ The only builtin dialect that supports :class:`.TryCast` is
+ Microsoft SQL (other third party dialects may support it as well).
:class:`.TryCast` is a subclass of SQLAlchemy's :class:`.Cast`
- construct, and works in the same way, except that the SQL expression
- rendered is "TRY_CAST" rather than "CAST"::
+ construct, and works in the same way, except in regards to error
+ handling. If the function encounters an un-castable value
+ (for instance when trying to convert the string "hi" to an INT)
+ then normal :class:`.Cast` raises an error. :class:`.TryCast`
+ instead returns a NULL value.
+
+ E.g.::
from sqlalchemy import select, try_cast, Numeric
try_cast(product_table.c.unit_price, Numeric(10, 4))
)
- The above would render with mssql as::
+ The above would render with Microsoft SQL as::
SELECT TRY_CAST (product_table.unit_price AS NUMERIC(10, 4))
FROM product_table
- .. versionadded:: 2.1.0
+ .. versionadded:: 2.0.14
"""
return TryCast(*arg, **kw)