diff --git a/src/did/database.py b/src/did/database.py index 22abcb4..e563192 100644 --- a/src/did/database.py +++ b/src/did/database.py @@ -188,6 +188,13 @@ def validate_docs(self, document_objs): #: ``did.database.add_docs`` ``OnDuplicate {mustBeMember(...)} = 'error'``. _ON_DUPLICATE_CHOICES = ("ignore", "warn", "error") + #: Allowed values for the ``OnDeletedId`` option of ``add_docs``: + #: ``"error"`` refuses a retired document id (one removed from every + #: branch); ``"restore"`` un-retires it and adds the document. Use + #: ``"restore"`` only for the same document coming back, never to give an + #: old id to a new document (VH-Lab/NDI-matlab#1238). + _ON_DELETED_ID_CHOICES = ("error", "restore") + def add_docs( self, document_objs, @@ -195,10 +202,16 @@ def add_docs( validate=True, OnDuplicate="error", custom_file_handler=None, + OnDeletedId="error", **kwargs, ): """Add documents to a branch. + ``OnDeletedId`` mirrors MATLAB's name-value argument of the same name: + ``"error"`` (default) refuses a document whose id was retired by an + earlier removal from every branch; ``"restore"`` un-retires the id and + adds the document, for the same document being restored. + ``custom_file_handler`` mirrors MATLAB's ``customFileHandler`` name-value argument: a callable used to retrieve a file whose location is not a local path (``ndic://``, a URL). It is called as @@ -226,6 +239,16 @@ def add_docs( f"{self._ON_DUPLICATE_CHOICES}; got {OnDuplicate!r}." ) + if str(OnDeletedId).lower() not in self._ON_DELETED_ID_CHOICES: + raise ValueError( + "OnDeletedId must be one of " + f"{self._ON_DELETED_ID_CHOICES}; got {OnDeletedId!r}." + ) + # Passed on only when not the default, so a _do_add_doc written + # before the option existed keeps working for every other caller. + if str(OnDeletedId).lower() != "error": + kwargs["OnDeletedId"] = OnDeletedId + # Ensure all input docs pass schema validation (unless requested not to) if validate: self.validate_docs(document_objs) diff --git a/src/did/implementations/sqlitedb.py b/src/did/implementations/sqlitedb.py index d50d072..aa03452 100644 --- a/src/did/implementations/sqlitedb.py +++ b/src/did/implementations/sqlitedb.py @@ -1313,6 +1313,7 @@ def _do_add_doc( branch_id, OnDuplicate="error", custom_file_handler=None, + OnDeletedId="error", **kwargs, ): import json @@ -1324,6 +1325,12 @@ def _do_add_doc( "OnDuplicate must be one of " f"{self._ON_DUPLICATE_CHOICES}; got {OnDuplicate!r}." ) + on_deleted = str(OnDeletedId).lower() + if on_deleted not in self._ON_DELETED_ID_CHOICES: + raise ValueError( + "OnDeletedId must be one of " + f"{self._ON_DELETED_ID_CHOICES}; got {OnDeletedId!r}." + ) doc_id = document_obj.id() cursor = self._journal_cursor() @@ -1351,12 +1358,23 @@ def _do_add_doc( # they must not be re-used under DID's branch model, and because both # languages have to agree about whether this is legal on a database # file they share. + # + # OnDeletedId="restore" is the exception, for the SAME document + # coming back (NDI re-downloading from the cloud a document deleted + # locally, VH-Lab/NDI-matlab#1238). The id is un-retired inside the + # try block below, so a failure rolls that back with everything else. + restore_deleted_id = False if self._is_deleted_doc_id(cursor, doc_id): - raise ValueError( - f"Cannot add document '{doc_id}' - a document with this id was " - f"previously removed from every branch. Document ids are never " - f"re-used; generate a new id for a new document." - ) + if on_deleted == "restore": + restore_deleted_id = True + else: + raise ValueError( + f"Cannot add document '{doc_id}' - a document with this id was " + f"previously removed from every branch. Document ids are never " + f"re-used; generate a new id for a new document, or pass " + f"OnDeletedId='restore' if this is the same document being " + f"restored." + ) # Snapshot the fields cache so a rollback also unwinds any field_idx # entries _populate_doc_data added for fields whose INSERTs get rolled @@ -1365,6 +1383,8 @@ def _do_add_doc( cache_before = dict(self._fields_cache) try: + if restore_deleted_id: + cursor.execute("DELETE FROM deleted_docs WHERE doc_id = ?", (doc_id,)) cursor.execute("SELECT doc_idx FROM docs WHERE doc_id = ?", (doc_id,)) row = cursor.fetchone() diff --git a/tests/test_document_reclamation.py b/tests/test_document_reclamation.py index 5fe24ff..e5bdd9a 100644 --- a/tests/test_document_reclamation.py +++ b/tests/test_document_reclamation.py @@ -144,6 +144,51 @@ def test_removed_doc_id_cannot_be_added_again(self): self.db._do_add_doc(doc, "a") self.assertIn("previously removed", str(caught.exception)) + def test_removed_doc_can_be_restored_on_request(self): + """VH-Lab/NDI-matlab#1238: the same document coming back is let in.""" + doc = Document("demoA", **{"demoA.value": 1}) + self.db.add_docs([doc], "a") + self.db.remove_docs(doc.id(), "a") + + self.db.add_docs([doc], "a", OnDeletedId="restore") + self.assertIn(doc.id(), self.db.get_doc_ids("a")) + self.assertFalse( + self.query("SELECT doc_id FROM deleted_docs WHERE doc_id = ?", (doc.id(),)), + "restoring the document must un-retire its id", + ) + + # Removed again, it is retired again, and the default still refuses + self.db.remove_docs(doc.id(), "a") + with self.assertRaises(ValueError): + self.db.add_docs([doc], "a") + + def test_failed_restore_leaves_id_retired(self): + """The un-retirement rolls back with the rest of a failed add.""" + doc = Document("demoA", **{"demoA.value": 1}) + self.db.add_docs([doc], "a") + self.db.remove_docs(doc.id(), "a") + + def fail(*args, **kwargs): + raise RuntimeError("injected failure") + + original = self.db._populate_doc_data + self.db._populate_doc_data = fail + try: + with self.assertRaises(RuntimeError): + self.db.add_docs([doc], "a", OnDeletedId="restore") + finally: + self.db._populate_doc_data = original + self.assertTrue( + self.query("SELECT doc_id FROM deleted_docs WHERE doc_id = ?", (doc.id(),)), + "a restore that fails must leave the id retired", + ) + + def test_invalid_on_deleted_id_is_rejected(self): + with self.assertRaises(ValueError): + self.db.add_docs( + [Document("demoA", **{"demoA.value": 1})], "a", OnDeletedId="bogus" + ) + def test_retirement_survives_reopening_the_file(self): """The id is retired in the database, not just in memory.""" doc = Document("demoA")