Skip to content

fix: lazy imports in sql_connection_manager, remove hardcoded $set wrapper - #504

Open
saurabhhhcodes wants to merge 1 commit into
UTSAVS26:mainfrom
saurabhhhcodes:fix/pysnippets-batch-1
Open

fix: lazy imports in sql_connection_manager, remove hardcoded $set wrapper#504
saurabhhhcodes wants to merge 1 commit into
UTSAVS26:mainfrom
saurabhhhcodes:fix/pysnippets-batch-1

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Jul 24, 2026

Copy link
Copy Markdown

Bug 1: Module-level imports causing ImportError

sql_connection_manager.py imported psycopg2 and mysql.connector at module level. Installing either module alone would cause an ImportError for the other, preventing use of the module entirely.

Fix: Moved imports inside their respective functions (lazy imports).

Bug 2: Hardcoded $set wrapper in mongo_document_update

update_document always wrapped update_data in {"$set": ...}, making it impossible to use MongoDB operators like $inc, $unset, $push, $pull, etc.

Fix: Pass update_data directly to update_one/update_many without wrapping.

Summary by CodeRabbit

  • Bug Fixes
    • MongoDB document updates now support complete MongoDB update documents, including operators such as $set.
    • Database drivers are loaded only when their corresponding connection method is used, improving startup reliability when optional drivers are unavailable.

@github-actions

Copy link
Copy Markdown
Contributor

👋 Thank you for opening this pull request! We're excited to review your contribution. Please give us a moment, and we'll get back to you shortly!

Feel free to join our community on Discord to discuss more!

@github-actions
github-actions Bot requested review from UTSAVS26 and pavitraag July 24, 2026 08:11
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

MongoDB updates now accept complete MongoDB update documents, while MySQL and PostgreSQL drivers load only when their connection functions execute.

Changes

MongoDB update document contract

Layer / File(s) Summary
Direct MongoDB update documents
pysnippets/database/mongodb/mongo_document_update.py
update_many and update_one receive update_data unchanged instead of an automatically added $set wrapper.

Connection-scoped SQL driver imports

Layer / File(s) Summary
Connection-scoped driver loading
pysnippets/database/mysql/sql_connection_manager.py
mysql.connector and psycopg2 are imported inside their respective connection functions rather than at module import time.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes both main changes and is concise enough for history scanning.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pysnippets/database/mongodb/mongo_document_update.py`:
- Around line 15-17: Restore automatic $set wrapping for update_data in the
update_many and update_one branches so callers can continue passing plain field
data such as {"age": 31}. Preserve the existing filter_criteria and multi-update
selection behavior; do not switch the API contract to require full MongoDB
update documents.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8da0e08d-0158-41fa-b034-084cb65b4799

📥 Commits

Reviewing files that changed from the base of the PR and between 9f6eda4 and 00f8f9c.

📒 Files selected for processing (2)
  • pysnippets/database/mongodb/mongo_document_update.py
  • pysnippets/database/mysql/sql_connection_manager.py

Comment on lines +15 to +17
result = collection.update_many(filter_criteria, update_data)
else:
result = collection.update_one(filter_criteria, {'$set': update_data})
result = collection.update_one(filter_criteria, update_data)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== repo files matching target =="
fd -a 'mongo_document_update.py|database.md|test_mongo.py' . || true

echo "== target snippet and surrounding context =="
if [ -f pysnippets/database/mongodb/mongo_document_update.py ]; then
  wc -l pysnippets/database/mongodb/mongo_document_update.py
  cat -n pysnippets/database/mongodb/mongo_document_update.py
fi

echo "== doc references =="
if [ -f pysnippets/database/database.md ]; then
  nl -ba pysnippets/database/database.md | sed -n '1,220p'
fi

echo "== test references =="
if [ -f Tests/database/test_mongo.py ]; then
  wc -l Tests/database/test_mongo.py
  nl -ba Tests/database/test_mongo.py | sed -n '1,260p'
fi

echo "== search update_many/update_one usages in repo =="
rg -n "update_many|update_one|mongo_document_update|update_data|set.*age|age.*31" . || true

Repository: UTSAVS26/PySnippets

Length of output: 1324


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== database.md =="
if [ -f pysnippets/database/database.md ]; then
  awk '{printf "%6d\t%s\n", NR, $0}' pysnippets/database/database.md | sed -n '1,240p'
fi

echo "== test_mongo.py =="
if [ -f Tests/database/test_mongo.py ]; then
  awk '{printf "%6d\t%s\n", NR, $0}' Tests/database/test_mongo.py | sed -n '1,280p'
fi

echo "== relevant repository usages =="
rg -n "update_many|update_one|update_document|update_data|set|age.*31|\$set" . || true

echo "== repository commit diff stat/name-only =="
git diff --stat HEAD~1..HEAD 2>/dev/null || git diff --stat 2>/dev/null || true
git diff --name-only HEAD~1..HEAD 2>/dev/html|sed -n '1,200p' || true

Repository: UTSAVS26/PySnippets

Length of output: 50376


🌐 Web query:

PyMongo collection update_one update document operator required behavior passing field update updateData

💡 Result:

In PyMongo, the update_one() method requires an update document that specifies the modifications to apply to the matched document [1][2]. This update document must use MongoDB update operator expressions (e.g., $set, $inc, $unset) to modify specific fields [1][3][4]. Key Requirements and Behavior: 1. Update Operators: The update parameter must be a mapping (dictionary) that contains update operator expressions [1][2]. For example, to update a field named "status" to "active", you must pass {'$set': {'status': 'active'}} rather than simply passing {'status': 'active'} [3]. Passing a naked document (without operators) as the update parameter is generally incorrect for update_one() and will typically cause an error or unexpected behavior, as MongoDB will interpret it as an attempt to replace the entire document content if used in a replacement context, which update_one() does not support [3]. 2. Update Document Structure: - The update document must be a dictionary-like object [2]. - It specifies the change to perform using operators like $set (to modify a field), $inc (to increment a numeric field), or $unset (to remove a field) [4][5]. 3. Alternative (Aggregation Pipeline): Starting in MongoDB 4.2 and supported by PyMongo, the update parameter can also be an aggregation pipeline (a list of stages) instead of an update operator document [6][3][2]. This allows for more complex updates, such as setting a field based on the value of another field [3]. Example of standard usage: collection.update_one({'_id': 1}, {'$set': {'field_to_update': 'new_value'}}) Summary: Always wrap your field updates in appropriate operators like $set within the update dictionary to ensure correct modification of the targeted document [1][3].

Citations:


Preserve the automatic $set wrapping or update the API contract.

update_data is still documented as plain field data ({"age": 31}), and Tests/database/test_mongo.py expects $set wrapping. Passing those values directly to PyMongo makes this a document replacement-style update contract rather than a targeted field update. Either wrap update_data with $set again when callers provide field data, or change all caller/test expectations to full MongoDB update documents.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pysnippets/database/mongodb/mongo_document_update.py` around lines 15 - 17,
Restore automatic $set wrapping for update_data in the update_many and
update_one branches so callers can continue passing plain field data such as
{"age": 31}. Preserve the existing filter_criteria and multi-update selection
behavior; do not switch the API contract to require full MongoDB update
documents.

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.

1 participant