argilla
argilla copied to clipboard
[IMPROVE] Improve how database models associations are loaded
Right now we have in our API handlers functions that load an entity using an id like the following:
# We load field's dataset association because it's used by authorize function
field = await Field.get_or_raise(db, field_id, options=[selectinload(Field.dataset)])
# This function is accessing previously loaded field.dataset to check for the authorization
await authorize(current_user, FieldPolicyV1.update(field))
Instead of loading associations before hand every function should load the associations that they need to work. In this case the authorize
function should load the field.dataset
because it's needed to check for the authorization:
# We load only the field without any association
field = await Field.get_or_raise(db, field_id)
# This function should internally load the field's dataset before needed.
await authorize(current_user, FieldPolicyV1.update(field))
In order to do this we need to investigate SQLAlchemy relationships loading styles and see for a possible solution to this.
We should check that loading an association that has been already loaded is not executing more queries.