fix the sql

"if you want something done right, then do it yourself"

The ORM was building a weird and inefficient query to get all the users
for a given organisation_id:

old query:

```sql
SELECT users.*
FROM users
WHERE (
    EXISTS (
        SELECT 1
        FROM user_to_organisation, organisation
        WHERE users.id = user_to_organisation.user_id AND
        organisation.id = user_to_organisation.organisation_id AND
        organisation.id = '63b9557c-22ea-42ac-bcba-edaa50e3ae51'
    )
) AND
users.state = 'active'
ORDER BY users.created_at
```

Note the cross join on users_to_org and org, there are a lot of users in
organisations on preview, as one is added every functional test run.
Even though they're all filtered out and the query returns the correct
data, it still does the nested loop under the hood.

new query:

```sql
SELECT users.*
FROM users
JOIN user_to_organisation AS user_to_organisation_1 ON users.id = user_to_organisation_1.user_id
JOIN organisation ON organisation.id = user_to_organisation_1.organisation_id
WHERE organisation.id = '63b9557c-22ea-42ac-bcba-edaa50e3ae51' AND users.state = 'active' ORDER BY users.created_at;
```

Much more straightforward.
This commit is contained in:
Leo Hemsted
2020-03-30 17:47:15 +01:00
parent c1ba3fb1be
commit 53b80b931f

View File

@@ -127,8 +127,12 @@ def dao_get_invited_organisation_user(user_id):
def dao_get_users_for_organisation(organisation_id):
return User.query.filter(
User.organisations.any(id=organisation_id),
return db.session.query(
User
).join(
User.organisations
).filter(
Organisation.id == organisation_id,
User.state == 'active'
).order_by(User.created_at).all()