opensafely-core / ehrql

ehrQL: the electronic health record query language for OpenSAFELY
https://docs.opensafely.org/ehrql/
Other
6 stars 3 forks source link

Better error messages for `case()`, `when()`, `then()` misuse #2031

Closed evansd closed 3 months ago

evansd commented 3 months ago

This doesn't add any new invalid constructs (apart from the edge case of duplicated conditions) but it does raise what are hopefully much more helpful errors for already invalid constructs.

For example, compare the before and after errors for missing .otherwise():

Expecting an ehrQL series, got type 'WhenThen'

---

Missing `.otherwise(...)` condition on a `when(...).then(...)` expression

For using the otherwise() method where you should use the keyword argument:

AttributeError: 'StrPatientSeries' object has no attribute '_condition'

---

TypeError: invalid syntax for `otherwise` in `case()` expression, instead of:

    case(
        when(...).then(...).otherwise(...)
    )

You should write:

    case(
        when(...).then(...),
        otherwise=...
    )

And for not providing a non-null value:

AssertionError: Could not match TypeVar ~T in Case(cases={Function.EQ(lhs=SelectColumn(source=
SelectPatientTable(name='patients', schema=TableSchema(date_of_birth=Column(datetime.date, constraints=()), 
i=Column(int, constraints=()), f=Column(float, constraints=()))), name='i'), rhs=Value(value=0)): None}, 
default=None)

---

TypeError: `case()` expression cannot have all `None` values

Closes #1440

cloudflare-pages[bot] commented 3 months ago

Deploying databuilder-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: d779455
Status: ✅  Deploy successful!
Preview URL: https://bd919569.databuilder.pages.dev
Branch Preview URL: https://evansd-better-case-errors.databuilder.pages.dev

View logs