MCPcopy
hub / github.com/sqlalchemy/sqlalchemy / case

Function case

lib/sqlalchemy/sql/_elements_constructors.py:794–910  ·  view source on GitHub ↗

r"""Produce a ``CASE`` expression. The ``CASE`` construct in SQL is a conditional object that acts somewhat analogously to an "if/then" construct in other languages. It returns an instance of :class:`.Case`. :func:`.case` in its usual form is passed a series of "when" construc

(
    *whens: Union[
        typing_Tuple[_ColumnExpressionArgument[bool], Any], Mapping[Any, Any]
    ],
    value: Optional[Any] = None,
    else_: Optional[Any] = None,
)

Source from the content-addressed store, hash-verified

792
793
794def case(
795 *whens: Union[
796 typing_Tuple[_ColumnExpressionArgument[bool], Any], Mapping[Any, Any]
797 ],
798 value: Optional[Any] = None,
799 else_: Optional[Any] = None,
800) -> Case[Any]:
801 r"""Produce a ``CASE`` expression.
802
803 The ``CASE`` construct in SQL is a conditional object that
804 acts somewhat analogously to an "if/then" construct in other
805 languages. It returns an instance of :class:`.Case`.
806
807 :func:`.case` in its usual form is passed a series of "when"
808 constructs, that is, a list of conditions and results as tuples::
809
810 from sqlalchemy import case
811
812 stmt = select(users_table).where(
813 case(
814 (users_table.c.name == "wendy", "W"),
815 (users_table.c.name == "jack", "J"),
816 else_="E",
817 )
818 )
819
820 The above statement will produce SQL resembling:
821
822 .. sourcecode:: sql
823
824 SELECT id, name FROM user
825 WHERE CASE
826 WHEN (name = :name_1) THEN :param_1
827 WHEN (name = :name_2) THEN :param_2
828 ELSE :param_3
829 END
830
831 When simple equality expressions of several values against a single
832 parent column are needed, :func:`.case` also has a "shorthand" format
833 used via the
834 :paramref:`.case.value` parameter, which is passed a column
835 expression to be compared. In this form, the :paramref:`.case.whens`
836 parameter is passed as a dictionary containing expressions to be
837 compared against keyed to result expressions. The statement below is
838 equivalent to the preceding statement::
839
840 stmt = select(users_table).where(
841 case({"wendy": "W", "jack": "J"}, value=users_table.c.name, else_="E")
842 )
843
844 The values which are accepted as result values in
845 :paramref:`.case.whens` as well as with :paramref:`.case.else_` are
846 coerced from Python literals into :func:`.bindparam` constructs.
847 SQL expressions, e.g. :class:`_expression.ColumnElement` constructs,
848 are accepted
849 as well. To coerce a literal string expression into a constant
850 expression rendered inline, use the :func:`_expression.literal_column`
851 construct,

Calls 1

CaseClass · 0.70