|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, Optional, Union |
| 4 | + |
| 5 | +from piccolo.custom_types import BasicTypes |
| 6 | +from piccolo.querystring import QueryString |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from piccolo.columns import Column |
| 10 | + |
| 11 | + |
| 12 | +class Coalesce(QueryString): |
| 13 | + def __init__( |
| 14 | + self, |
| 15 | + *args: Union[Column, QueryString, BasicTypes], |
| 16 | + alias: Optional[str] = None, |
| 17 | + ): |
| 18 | + """ |
| 19 | + Returns the first non-null value. |
| 20 | +
|
| 21 | + Here's an example to try in the playground:: |
| 22 | +
|
| 23 | + >>> await Album.select(Album.release_date) |
| 24 | + [ |
| 25 | + {'release_date': datetime.date(2021, 1, 1)}, |
| 26 | + {'release_date': datetime.date(2025, 1, 1)}, |
| 27 | + {'release_date': datetime.date(2022, 2, 2)}, |
| 28 | + {'release_date': None} |
| 29 | + ] |
| 30 | +
|
| 31 | + One of the values is null - we can specify a fallback value:: |
| 32 | +
|
| 33 | + >>> from piccolo.functions.conditional import Coalesce |
| 34 | + >>> await Album.select( |
| 35 | + ... Coalesce(Album.release_date, datetime.date(2050, 1, 1)) |
| 36 | + ... ) |
| 37 | + [ |
| 38 | + {'release_date': datetime.date(2021, 1, 1)}, |
| 39 | + {'release_date': datetime.date(2025, 1, 1)}, |
| 40 | + {'release_date': datetime.date(2022, 2, 2)}, |
| 41 | + {'release_date': datetime.date(2050, 1, 1)} |
| 42 | + ] |
| 43 | +
|
| 44 | + Or us this abbreviated syntax:: |
| 45 | +
|
| 46 | + >>> await Album.select( |
| 47 | + ... Album.release_date | datetime.date(2050, 1, 1) |
| 48 | + ... ) |
| 49 | + [ |
| 50 | + {'release_date': datetime.date(2021, 1, 1)}, |
| 51 | + {'release_date': datetime.date(2025, 1, 1)}, |
| 52 | + {'release_date': datetime.date(2022, 2, 2)}, |
| 53 | + {'release_date': datetime.date(2050, 1, 1)} |
| 54 | + ] |
| 55 | +
|
| 56 | + """ |
| 57 | + if len(args) < 2: |
| 58 | + raise ValueError("At least two values must be passed in.") |
| 59 | + |
| 60 | + ####################################################################### |
| 61 | + # Preserve the original alias from the column. |
| 62 | + |
| 63 | + from piccolo.columns import Column |
| 64 | + |
| 65 | + first_arg = args[0] |
| 66 | + |
| 67 | + if isinstance(first_arg, Column): |
| 68 | + alias = ( |
| 69 | + alias |
| 70 | + or first_arg._alias |
| 71 | + or first_arg._meta.get_default_alias() |
| 72 | + ) |
| 73 | + elif isinstance(first_arg, QueryString): |
| 74 | + alias = alias or first_arg._alias |
| 75 | + |
| 76 | + ####################################################################### |
| 77 | + |
| 78 | + placeholders = ", ".join("{}" for _ in args) |
| 79 | + |
| 80 | + super().__init__(f"COALESCE({placeholders})", *args, alias=alias) |
0 commit comments