Skip to content

Commit

Permalink
Merge pull request #21 from tarsil/fix/uniques
Browse files Browse the repository at this point in the history
Add unique index validation
  • Loading branch information
tarsil authored Jan 16, 2024
2 parents c48437b + 9afd043 commit 9058ae9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
4 changes: 3 additions & 1 deletion mongoz/core/db/documents/metaclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,10 +340,12 @@ def __search_for_fields(base: Type, attrs: Any) -> None:
if not new_class.is_proxy_document:
# For the indexes
_index: Union[Index, None] = None
if hasattr(field, "index") and field.index and field.unique is True:
if hasattr(field, "index") and field.index and field.unique:
_index = Index(name, unique=True, sparse=field.sparse)
elif hasattr(field, "index") and field.index:
_index = Index(name, sparse=field.sparse)
elif hasattr(field, "unique") and field.unique:
_index = Index(name, unique=True)

if _index is not None:
index_names = [index.name for index in meta.indexes or []]
Expand Down
41 changes: 41 additions & 0 deletions tests/indexes/test_unique.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from typing import AsyncGenerator

import pydantic
import pytest
from pymongo.errors import DuplicateKeyError
from tests.conftest import client

import mongoz
from mongoz import Document

pytestmark = pytest.mark.anyio
pydantic_version = pydantic.__version__[:3]


class Movie(Document):
name: str = mongoz.String(unique=True)
is_published: bool = mongoz.Boolean(default=False)

class Meta:
registry = client
database = "test_db"


@pytest.fixture(scope="function", autouse=True)
async def prepare_database() -> AsyncGenerator:
await Movie.drop_indexes(force=True)
await Movie.objects.delete()
await Movie.create_indexes()
yield
await Movie.drop_indexes(force=True)
await Movie.objects.delete()
await Movie.create_indexes()


async def test_unique():
movie = await Movie.objects.create(name="Barbie")

assert movie.is_published is False

with pytest.raises(DuplicateKeyError):
await Movie.objects.create(name="Barbie")

0 comments on commit 9058ae9

Please sign in to comment.