Another tool execution optimization...

Prefetch all groups, roles, and associations when using User.all_users(). This reduces three queries down to one if the user has no groups or group roles and only belongs to the private user role, obviously the number of queries saved would increase more and more if the user belonged to multiple roles or groups.
This commit is contained in:
John Chilton
2015-11-24 15:10:43 +00:00
parent 42d006162c
commit 01c57908ea
+21 -2
View File
@@ -187,8 +187,27 @@ class User( object, Dictifiable ):
"""
Return a unique list of Roles associated with this user or any of their groups.
"""
roles = [ ura.role for ura in self.roles ]
for group in [ uga.group for uga in self.groups ]:
try:
db_session = object_session( self )
user = db_session.query(
User
).filter_by( # don't use get, it will use session variant.
id=self.id
).options(
joinedload("roles"),
joinedload("roles.role"),
joinedload("groups"),
joinedload("groups.group"),
joinedload("groups.group.roles"),
joinedload("groups.group.roles.role")
).one()
except Exception:
# If not persistent user, just use models normaly and
# skip optimizations...
user = self
roles = [ ura.role for ura in user.roles ]
for group in [ uga.group for uga in user.groups ]:
for role in [ gra.role for gra in group.roles ]:
if role not in roles:
roles.append( role )