-
Notifications
You must be signed in to change notification settings - Fork 0
⚡ Bolt: Fix N+1 queries in action_devices.py #132
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| ## 2024-05-18 - [Fix N+1 query] | ||
| **Learning:** Fixed N+1 queries in `rstate` and `onQuery` by bulk fetching data instead of using `rquery` inside a loop. | ||
| **Action:** Always check for repeated fetches in loops that can be optimized to a bulk fetch. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
|
|
@@ -73,16 +73,21 @@ def rstate(user_id=None): | |||||||
| if not devices_data: | ||||||||
| return {"devices": {"states": {}}} | ||||||||
|
|
||||||||
| devices = list(devices_data.keys()) | ||||||||
| payload = { | ||||||||
| "devices": { | ||||||||
| "states": {} | ||||||||
| } | ||||||||
| } | ||||||||
| for device in devices: | ||||||||
| for device, raw_data in devices_data.items(): | ||||||||
| device = str(device) | ||||||||
| logger.debug('Getting Device status from: %s', device) | ||||||||
| state_data = rquery(device, user_id=user_id) | ||||||||
|
|
||||||||
| # Use pre-fetched state if available in snapshot, else fallback | ||||||||
| if isinstance(raw_data, dict) and 'states' in raw_data: | ||||||||
| state_data = raw_data['states'] | ||||||||
| else: | ||||||||
| state_data = rquery(device, user_id=user_id) | ||||||||
|
|
||||||||
| if state_data: | ||||||||
| payload['devices']['states'][device] = state_data | ||||||||
| logger.debug('Device state: %s', state_data) | ||||||||
|
|
@@ -199,10 +204,24 @@ def onQuery(body, user_id=None): | |||||||
| payload = { | ||||||||
| "devices": {}, | ||||||||
| } | ||||||||
|
|
||||||||
| # Optimize: bulk fetch device states to avoid N+1 queries | ||||||||
| devices_data = _get_scoped_snapshot(user_id) or {} | ||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Similar to the logic in
Suggested change
|
||||||||
|
|
||||||||
| for i in body['inputs']: | ||||||||
| for device in i['payload']['devices']: | ||||||||
| deviceId = device['id'] | ||||||||
| data = rquery(deviceId, user_id=user_id) | ||||||||
|
|
||||||||
| # Try getting from cache first | ||||||||
| data = None | ||||||||
| raw_data = devices_data.get(deviceId) | ||||||||
| if isinstance(raw_data, dict) and 'states' in raw_data: | ||||||||
| data = raw_data['states'] | ||||||||
|
|
||||||||
| # Fallback to single fetch and validation logic in rquery | ||||||||
| if data is None: | ||||||||
| data = rquery(deviceId, user_id=user_id) | ||||||||
|
|
||||||||
| payload['devices'][deviceId] = data | ||||||||
| return payload | ||||||||
| except Exception as e: | ||||||||
|
|
||||||||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The iteration over
devices_data.items()will raise anAttributeErrorifdevices_datais not a dictionary. While_get_scoped_snapshottypically returns a dictionary, Firebase can return a list if the keys are sequential integers starting from zero. Since the code now relies on.items(), it is safer to explicitly verify the type before iterating.