r"""Produce a ``CAST`` expression. :func:`.cast` returns an instance of :class:`.Cast`. E.g.:: from sqlalchemy import cast, Numeric stmt = select(cast(product_table.c.unit_price, Numeric(10, 4))) The above statement will produce SQL resembling: .. sourcecode:: s
(
expression: _ColumnExpressionOrLiteralArgument[Any],
type_: _TypeEngineArgument[_T],
)
| 866 | |
| 867 | |
| 868 | def cast( |
| 869 | expression: _ColumnExpressionOrLiteralArgument[Any], |
| 870 | type_: _TypeEngineArgument[_T], |
| 871 | ) -> Cast[_T]: |
| 872 | r"""Produce a ``CAST`` expression. |
| 873 | |
| 874 | :func:`.cast` returns an instance of :class:`.Cast`. |
| 875 | |
| 876 | E.g.:: |
| 877 | |
| 878 | from sqlalchemy import cast, Numeric |
| 879 | |
| 880 | stmt = select(cast(product_table.c.unit_price, Numeric(10, 4))) |
| 881 | |
| 882 | The above statement will produce SQL resembling: |
| 883 | |
| 884 | .. sourcecode:: sql |
| 885 | |
| 886 | SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product |
| 887 | |
| 888 | The :func:`.cast` function performs two distinct functions when |
| 889 | used. The first is that it renders the ``CAST`` expression within |
| 890 | the resulting SQL string. The second is that it associates the given |
| 891 | type (e.g. :class:`.TypeEngine` class or instance) with the column |
| 892 | expression on the Python side, which means the expression will take |
| 893 | on the expression operator behavior associated with that type, |
| 894 | as well as the bound-value handling and result-row-handling behavior |
| 895 | of the type. |
| 896 | |
| 897 | An alternative to :func:`.cast` is the :func:`.type_coerce` function. |
| 898 | This function performs the second task of associating an expression |
| 899 | with a specific type, but does not render the ``CAST`` expression |
| 900 | in SQL. |
| 901 | |
| 902 | :param expression: A SQL expression, such as a |
| 903 | :class:`_expression.ColumnElement` |
| 904 | expression or a Python string which will be coerced into a bound |
| 905 | literal value. |
| 906 | |
| 907 | :param type\_: A :class:`.TypeEngine` class or instance indicating |
| 908 | the type to which the ``CAST`` should apply. |
| 909 | |
| 910 | .. seealso:: |
| 911 | |
| 912 | :ref:`tutorial_casts` |
| 913 | |
| 914 | :func:`.try_cast` - an alternative to CAST that results in |
| 915 | NULLs when the cast fails, instead of raising an error. |
| 916 | Only supported by some dialects. |
| 917 | |
| 918 | :func:`.type_coerce` - an alternative to CAST that coerces the type |
| 919 | on the Python side only, which is often sufficient to generate the |
| 920 | correct SQL and data coercion. |
| 921 | |
| 922 | |
| 923 | """ |
| 924 | return Cast(expression, type_) |
| 925 |