Search code examples
swiftcouchbase-lite

Store attributes in deleted couchbase documents


I want to be able to save the data inside deleted records in a Couchbase Lite application. According the couchbase lite documentation I should be able to save a deleted_at attribute along with all of the current attributes using this code (slightly modified for a newer era of Swift syntax):

do {
    try document.update { (newRev) -> Bool in
        newRev.isDeletion = true
        newRev["deleted_at"] = currentTimeStamp

        print("Document deleted at: \(document["deleted_at"])")
        // prints "Document deleted at: nil"

        print("Revision deleted at: \(newRev["deleted_at"])")
        // prints "Revision deleted at: Optional(2016-03-14)"
        return true
    }
} catch let error as NSError {
    self.handleError(error)
}

However, if I try to access the attributes later, they don't exist:

print("Deleted: \(document.isDeleted)")
// prints "Deleted: Optional(true)"

print("Deleted at: \(document["deleted_at"])")  
// prints "Deleted at: nil"

I'm pretty sure this should print the timestamp associated with the deleted_at attribute.

I thought that maybe couchbase doesn't allow accessing data from deleted records, but restoring the record doesn't allow access either:

do {
    try document.update { (newRev) -> Bool in
        newRev.isDeletion = false

        print("Document deleted at: \(document["deleted_at"])")
        // prints "Document deleted at: nil"

        print("Revision deleted at: \(newRev["deleted_at"])")
        // prints "Revision deleted at: nil"
        return true
    }
} catch let error as NSError {
    self.handleError(error)
}

print("Deleted: \(document.isDeleted)")
// prints "Deleted: Optional(false)"

print("Deleted at: \(document["deleted_at"])")  
// prints "Deleted at: nil"

Is there something I can do to get this to work?


Solution

  • CBLDocument doesn't normally load a deleted revision. Most of the time, if a document's been deleted the developer considers it gone, so CBLDocument.currentRevision will return nil instead of returning the "tombstone" revision. This then affects the property accessors, which call currentRevision.

    If you want to get the tombstone revision anyway, because you stored data in it, you can use other accessors like getLeafRevisions or getRevisionHistory.

    (FYI, I wrote this code, so this is probably the authoritative answer :)