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],
)
| 911 | |
| 912 | |
| 913 | def cast( |
| 914 | expression: _ColumnExpressionOrLiteralArgument[Any], |
| 915 | type_: _TypeEngineArgument[_T], |
| 916 | ) -> Cast[_T]: |
| 917 | r"""Produce a ``CAST`` expression. |
| 918 | |
| 919 | :func:`.cast` returns an instance of :class:`.Cast`. |
| 920 | |
| 921 | E.g.:: |
| 922 | |
| 923 | from sqlalchemy import cast, Numeric |
| 924 | |
| 925 | stmt = select(cast(product_table.c.unit_price, Numeric(10, 4))) |
| 926 | |
| 927 | The above statement will produce SQL resembling: |
| 928 | |
| 929 | .. sourcecode:: sql |
| 930 | |
| 931 | SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product |
| 932 | |
| 933 | The :func:`.cast` function performs two distinct functions when |
| 934 | used. The first is that it renders the ``CAST`` expression within |
| 935 | the resulting SQL string. The second is that it associates the given |
| 936 | type (e.g. :class:`.TypeEngine` class or instance) with the column |
| 937 | expression on the Python side, which means the expression will take |
| 938 | on the expression operator behavior associated with that type, |
| 939 | as well as the bound-value handling and result-row-handling behavior |
| 940 | of the type. |
| 941 | |
| 942 | An alternative to :func:`.cast` is the :func:`.type_coerce` function. |
| 943 | This function performs the second task of associating an expression |
| 944 | with a specific type, but does not render the ``CAST`` expression |
| 945 | in SQL. |
| 946 | |
| 947 | :param expression: A SQL expression, such as a |
| 948 | :class:`_expression.ColumnElement` |
| 949 | expression or a Python string which will be coerced into a bound |
| 950 | literal value. |
| 951 | |
| 952 | :param type\_: A :class:`.TypeEngine` class or instance indicating |
| 953 | the type to which the ``CAST`` should apply. |
| 954 | |
| 955 | .. seealso:: |
| 956 | |
| 957 | :ref:`tutorial_casts` |
| 958 | |
| 959 | :func:`.try_cast` - an alternative to CAST that results in |
| 960 | NULLs when the cast fails, instead of raising an error. |
| 961 | Only supported by some dialects. |
| 962 | |
| 963 | :func:`.type_coerce` - an alternative to CAST that coerces the type |
| 964 | on the Python side only, which is often sufficient to generate the |
| 965 | correct SQL and data coercion. |
| 966 | |
| 967 | |
| 968 | """ |
| 969 | return Cast(expression, type_) |
| 970 |
no test coverage detected