diff --git a/src/grung/db.py b/src/grung/db.py index ddce634..ba970f1 100644 --- a/src/grung/db.py +++ b/src/grung/db.py @@ -51,22 +51,18 @@ class RecordTable(table.Table): self._check_unique(document) def _check_unique(self, document) -> bool: - matches = [ - dict(match) - for match in super().search( - reduce( - ior, - [ - Query()[field.name].matches(document[field.name], flags=re.IGNORECASE) - for field in document._metadata.fields.values() - if field.unique - ], - ) - ) - if match.doc_id != document.doc_id - ] + matches = [] + queries = reduce( + ior, + [ + Query()[field.name].matches(document[field.name], flags=re.IGNORECASE) + for field in document._metadata.fields.values() + if field.unique + ], + ) + matches = [dict(match) for match in super().search(queries) if match.doc_id != document.doc_id] if matches != []: - raise UniqueConstraintError(document, matches) + raise UniqueConstraintError(document, queries, matches) class GrungDB(TinyDB): diff --git a/src/grung/exceptions.py b/src/grung/exceptions.py index 9b60c50..711e32c 100644 --- a/src/grung/exceptions.py +++ b/src/grung/exceptions.py @@ -3,10 +3,11 @@ class UniqueConstraintError(Exception): Thrown when a db write operation cannot complete due to a field's unique constraint. """ - def __init__(self, document, collisions): + def __init__(self, document, query, collisions): super().__init__( "\n" f" * Record: {dict(document)}\n" + f" * Query: {query}\n" f" * Error: Unique constraint failure\n" " * The record matches the following existing records:\n\n" + "\n".join(str(c) for c in collisions) )