Skip to content
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

[BUG] update() raises a RevisionIdWasChanged when expecting a DuplicateKeyError #1057

Open
NiziL opened this issue Oct 17, 2024 · 1 comment
Labels
bug Something isn't working good first issue Good for newcomers

Comments

@NiziL
Copy link

NiziL commented Oct 17, 2024

Describe the bug

When creating a Document with an unique indexed attribute, violating the uniqueness raise a RevisionIdWasChanged instead of a DuplicateKeyError.

To Reproduce

import asyncio
from typing import Annotated

import pymongo
from beanie import Document, Indexed, init_beanie
from motor.motor_asyncio import AsyncIOMotorClient


client = AsyncIOMotorClient("mongodb://localhost:27017/test")


class MyDocument(Document):
    unique: Annotated[str, Indexed(index_type=pymongo.TEXT, unique=True)]


async def test():
    await init_beanie(client.get_default_database(), document_models=[MyDocument])
    doc = MyDocument(unique="test")
    await doc.save()
    doc2 = MyDocument(unique="test")
    await doc2.save()


if __name__ == "__main__":
    asyncio.run(test())

Expected behavior
Raise the DuplicateKeyError instead of replacing it by a RevisionIdWasChanged.

Additional context
The bug comes from documents.py, line 739/740.

I feel like we could easily catch the error, ensure the DuplicateKeyError comes from a revision id issue, and either raise a RevisionIdWasChanged or this error.
Something like:

except DuplicateKeyError as e:
    raise RevisionIdWasChanged if "revision_id" in str(e) else e 

I can prepare a PR for this, I just feel like my solution is a bit hacky right now... Any ideas ?

@staticxterm staticxterm added bug Something isn't working good first issue Good for newcomers labels Oct 17, 2024
@NiziL NiziL changed the title [BUG] update() raises a RevisionIdWasChanged when expection a DuplicateKeyError [BUG] update() raises a RevisionIdWasChanged when expecting a DuplicateKeyError Oct 17, 2024
@RamonGiovane
Copy link

Probably another side effect of this bug: #833 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

3 participants