@@ -78,3 +78,45 @@ def __init__(
7878 placeholders = ", " .join ("{}" for _ in args )
7979
8080 super ().__init__ (f"COALESCE({ placeholders } )" , * args , alias = alias )
81+
82+
83+ class NullIf (QueryString ):
84+ def __init__ (
85+ self ,
86+ identifier : Union [Column , QueryString ],
87+ value : Union [BasicTypes , QueryString ],
88+ alias : Optional [str ] = None ,
89+ ):
90+ """
91+ Returns null if the value in the database equals ``value``.
92+
93+ An example is where a ``Varchar`` or ``Text`` column contains a mix of
94+ empty strings and null. We might want to standardise the response so
95+ it's just null.
96+
97+ For example::
98+
99+ class Venue(Table):
100+ name = Varchar()
101+ address = Text(null=True)
102+
103+ >>> await Venue.select(Venue.name, NullIf(Venue.address, ''))
104+ [{'name': 'Amazing venue', 'address': None}]
105+
106+ """
107+ # Preserve the original alias from the column.
108+
109+ from piccolo .columns import Column
110+
111+ if isinstance (identifier , Column ):
112+ alias = (
113+ alias
114+ or identifier ._alias
115+ or identifier ._meta .get_default_alias ()
116+ )
117+ elif isinstance (identifier , QueryString ):
118+ alias = alias or identifier ._alias
119+
120+ #######################################################################
121+
122+ super ().__init__ ("NULLIF({}, {})" , identifier , value , alias = alias )
0 commit comments