11from __future__ import annotations
22from abc import ABCMeta , abstractmethod
3+ import copy
34from dataclasses import dataclass , field
45import datetime
56import decimal
@@ -226,6 +227,8 @@ def __init__(
226227 required = required ,
227228 )
228229
230+ self .alias : t .Optional [str ] = None
231+
229232 def _validate_default (
230233 self ,
231234 default : t .Any ,
@@ -306,6 +309,20 @@ def __ne__(self, value) -> Where: # type: ignore
306309 def __hash__ (self ):
307310 return hash (self ._meta .name )
308311
312+ def as_alias (self , name : str ) -> Column :
313+ """
314+ Allows column names to be changed in the result of a select.
315+
316+ For example:
317+
318+ >>> await Band.select(Band.name.as_alias('title')).run()
319+ {'title': 'Pythonistas'}
320+
321+ """
322+ column = copy .deepcopy (self )
323+ column .alias = name
324+ return column
325+
309326 def get_default_value (self ) -> t .Any :
310327 """
311328 If the column has a default attribute, return it. If it's callable,
@@ -323,9 +340,16 @@ def get_select_string(self, engine_type: str, just_alias=False) -> str:
323340 """
324341 How to refer to this column in a SQL query.
325342 """
326- return self ._meta .get_full_name (just_alias = just_alias )
343+ if self .alias is None :
344+ return self ._meta .get_full_name (just_alias = just_alias )
345+ else :
346+ original_name = self ._meta .get_full_name (just_alias = True )
347+ return f"{ original_name } AS { self .alias } "
327348
328- def get_sql_value (self , value : t .Any ) -> str :
349+ def get_where_string (self , engine_type : str ) -> str :
350+ return self .get_select_string (engine_type = engine_type , just_alias = True )
351+
352+ def get_sql_value (self , value : t .Any ) -> t .Any :
329353 """
330354 When using DDL statements, we can't parameterise the values. An example
331355 is when setting the default for a column. So we have to convert from
@@ -390,6 +414,13 @@ def querystring(self) -> QueryString:
390414 if not self ._meta .primary :
391415 default = self .get_default_value ()
392416 sql_value = self .get_sql_value (value = default )
417+ # Escape the value if it contains a pair of curly braces, otherwise
418+ # an empty value will appear in the compiled querystring.
419+ sql_value = (
420+ sql_value .replace ("{}" , "{{}}" )
421+ if isinstance (sql_value , str )
422+ else sql_value
423+ )
393424 query += f" DEFAULT { sql_value } "
394425
395426 return QueryString (query )
0 commit comments