Represent a ``CAST`` expression. :class:`.Cast` is produced using the :func:`.cast` factory function, as in:: from sqlalchemy import cast, Numeric stmt = select(cast(product_table.c.unit_price, Numeric(10, 4))) Details on :class:`.Cast` usage is at :func:`.cast`.
| 3395 | |
| 3396 | |
| 3397 | class Cast(WrapsColumnExpression[_T]): |
| 3398 | """Represent a ``CAST`` expression. |
| 3399 | |
| 3400 | :class:`.Cast` is produced using the :func:`.cast` factory function, |
| 3401 | as in:: |
| 3402 | |
| 3403 | from sqlalchemy import cast, Numeric |
| 3404 | |
| 3405 | stmt = select(cast(product_table.c.unit_price, Numeric(10, 4))) |
| 3406 | |
| 3407 | Details on :class:`.Cast` usage is at :func:`.cast`. |
| 3408 | |
| 3409 | .. seealso:: |
| 3410 | |
| 3411 | :ref:`tutorial_casts` |
| 3412 | |
| 3413 | :func:`.cast` |
| 3414 | |
| 3415 | :func:`.try_cast` |
| 3416 | |
| 3417 | :func:`.type_coerce` - an alternative to CAST that coerces the type |
| 3418 | on the Python side only, which is often sufficient to generate the |
| 3419 | correct SQL and data coercion. |
| 3420 | |
| 3421 | """ |
| 3422 | |
| 3423 | __visit_name__ = "cast" |
| 3424 | |
| 3425 | _traverse_internals: _TraverseInternalsType = [ |
| 3426 | ("clause", InternalTraversal.dp_clauseelement), |
| 3427 | ("type", InternalTraversal.dp_type), |
| 3428 | ] |
| 3429 | |
| 3430 | clause: ColumnElement[Any] |
| 3431 | type: TypeEngine[_T] |
| 3432 | typeclause: TypeClause |
| 3433 | |
| 3434 | def __init__( |
| 3435 | self, |
| 3436 | expression: _ColumnExpressionArgument[Any], |
| 3437 | type_: _TypeEngineArgument[_T], |
| 3438 | ): |
| 3439 | self.type = type_api.to_instance(type_) |
| 3440 | self.clause = coercions.expect( |
| 3441 | roles.ExpressionElementRole, |
| 3442 | expression, |
| 3443 | type_=self.type, |
| 3444 | apply_propagate_attrs=self, |
| 3445 | ) |
| 3446 | self.typeclause = TypeClause(self.type) |
| 3447 | |
| 3448 | @util.ro_non_memoized_property |
| 3449 | def _from_objects(self) -> List[FromClause]: |
| 3450 | return self.clause._from_objects |
| 3451 | |
| 3452 | @property |
| 3453 | def wrapped_column_expression(self): |
| 3454 | return self.clause |