MongoEngine / MongoEngine/mongoengine
Issue with switch_db: the default database is still touched
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 4.3k
- Forks
- 1.2k
- Avg merge
- 4h 41m
- Merged PRs (30d)
- 11
Description
I'm trying to work with switch_db in a multi tenant-scenario (dynamic db names). I'd want to avoid the "default" alias to be used at all.
The following sample program attemps to save a single document to a database "mydb" , inside a switch_db block. It works as expected, except that the "default" database is also written (the collection "my_object" is created, albeit empty , with its index).
Curiosly, this only happens if I add the "unique=True" restriction... which worried me ... perhaps the checking was done in the wrong database?? fortunately, no. But it's strange, anyway, and it should not happen.
Furthermore: after exiting the switch_db I notice that the added and created object has its db_alias meta attribute as "default". This is rather undesirable, don't you think?
You can try it in an empty Mongo instance (databases "mydb" and "default" are created).
import mongoengine
from mongoengine import Document
from mongoengine.context_managers import switch_db
class MyObject(Document):
st = mongoengine.StringField(unique=True)
url = "mongodb://localhost"
mongoengine.connect("mydb", alias="mydb", host=url)
mongoengine.connect("default", alias="default", host=url)
def add():
alias = "mydb"
with switch_db(MyObject, alias) as MyObject2:
return MyObject2(st="test").save()
obj=add()
print(f"db_alias obj : {obj._meta.get('db_alias','?')}")
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the switch_db context manager and the unique=True field in the provided reproduction. Verify which databases are touched and whether the saved document retains the switched alias; done means only mydb is created or updated and the object reports mydb rather than default.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mongodb, python
- Domain
- database
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100