Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add class-based schema definitions #663

Merged
merged 6 commits into from
Aug 9, 2022
Merged

Conversation

evansd
Copy link
Contributor

@evansd evansd commented Aug 8, 2022

This PR replaces the old syntax for defining ehrQL schemas e.g.

patients = build_patient_table(
    "patients",
    {
        "sex": str,
        "date_of_birth": datetime.date,
    }
)

with a class-based one that looks like this:

@construct
class patients(PatientFrame):
    sex = Series(str)
    date_of_birth = Series(datetime.date)

There are some obvious peculiarities here (the decorator and the lowercase class name) which we'll come to later, but the primary motivation for this change is to make it possible to have full autocomplete for ehrQL when writing dataset definitions in VSCode. As far as I can see, this is only possible if we use classes to define the schema because no other syntax makes the column names available.

This change gives us autocomplete on table and column names, and also on frame methods like exists_for_patient, take and drop. It doesn't yet give us autocomplete on series methods but I have a proof-of-concept which shows that this ought to be possible.

The @construct decorator, and the lowercase class name are to avoid having to write something like this:

class Patients(PatientFrame):
    __tablename__ = "patients"
    sex = Series(str)
    date_of_birth = Series(datetime.date)

patients = Patients()

Not only would that be more verbose and error prone, but it would leave the Patients class in the namespace where it would show as a (misleading) autocomplete option.

@evansd evansd force-pushed the evansd/schema-definitions branch from fd415a7 to 759902e Compare August 9, 2022 09:45
databuilder/query_language.py Outdated Show resolved Hide resolved
Comment on lines +6 to +10
@construct
class patients(PatientFrame):
date_of_birth = Series(datetime.date)
date_of_death = Series(datetime.date)
sex = Series(str)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks much nicer 🙂

@evansd evansd force-pushed the evansd/schema-definitions branch from 759902e to c05df39 Compare August 9, 2022 10:16
@evansd evansd merged commit 4e387e5 into main Aug 9, 2022
@evansd evansd deleted the evansd/schema-definitions branch August 9, 2022 14:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants