1010from sqlspec .exceptions import SQLBuilderError
1111
1212if TYPE_CHECKING :
13+ from sqlspec .builder ._column import Column
14+ from sqlspec .builder ._expression_wrappers import ExpressionWrapper
15+ from sqlspec .builder .mixins ._select_operations import Case
1316 from sqlspec .protocols import SQLBuilderProtocol
1417
1518__all__ = ("LimitOffsetClauseMixin" , "OrderByClauseMixin" , "ReturningClauseMixin" )
@@ -24,7 +27,7 @@ class OrderByClauseMixin:
2427 # Type annotation for PyRight - this will be provided by the base class
2528 _expression : Optional [exp .Expression ]
2629
27- def order_by (self , * items : Union [str , exp .Ordered ], desc : bool = False ) -> Self :
30+ def order_by (self , * items : Union [str , exp .Ordered , "Column" ], desc : bool = False ) -> Self :
2831 """Add ORDER BY clause.
2932
3033 Args:
@@ -49,7 +52,13 @@ def order_by(self, *items: Union[str, exp.Ordered], desc: bool = False) -> Self:
4952 if desc :
5053 order_item = order_item .desc ()
5154 else :
52- order_item = item
55+ # Extract expression from Column objects or use as-is for sqlglot expressions
56+ from sqlspec ._sql import SQLFactory
57+
58+ extracted_item = SQLFactory ._extract_expression (item )
59+ order_item = extracted_item
60+ if desc and not isinstance (item , exp .Ordered ):
61+ order_item = order_item .desc ()
5362 current_expr = current_expr .order_by (order_item , copy = False )
5463 builder ._expression = current_expr
5564 return cast ("Self" , builder )
@@ -111,7 +120,7 @@ class ReturningClauseMixin:
111120 # Type annotation for PyRight - this will be provided by the base class
112121 _expression : Optional [exp .Expression ]
113122
114- def returning (self , * columns : Union [str , exp .Expression ]) -> Self :
123+ def returning (self , * columns : Union [str , exp .Expression , "Column" , "ExpressionWrapper" , "Case" ]) -> Self :
115124 """Add RETURNING clause to the statement.
116125
117126 Args:
@@ -130,6 +139,9 @@ def returning(self, *columns: Union[str, exp.Expression]) -> Self:
130139 if not isinstance (self ._expression , valid_types ):
131140 msg = "RETURNING is only supported for INSERT, UPDATE, and DELETE statements."
132141 raise SQLBuilderError (msg )
133- returning_exprs = [exp .column (c ) if isinstance (c , str ) else c for c in columns ]
142+ # Extract expressions from various wrapper types
143+ from sqlspec ._sql import SQLFactory
144+
145+ returning_exprs = [SQLFactory ._extract_expression (c ) for c in columns ]
134146 self ._expression .set ("returning" , exp .Returning (expressions = returning_exprs ))
135147 return self
0 commit comments