Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/did/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,17 +188,30 @@ 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,
branch_id=None,
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
Expand Down Expand Up @@ -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)
Expand Down
30 changes: 25 additions & 5 deletions src/did/implementations/sqlitedb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1313,6 +1313,7 @@ def _do_add_doc(
branch_id,
OnDuplicate="error",
custom_file_handler=None,
OnDeletedId="error",
**kwargs,
):
import json
Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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()

Expand Down
45 changes: 45 additions & 0 deletions tests/test_document_reclamation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading