I accidentally deleted all the docs in a CouchDB database and I want to undelete them.
CouchDB version = 2.2.0 Python = 2.7 and I'm using the python-couchDB library.
My CouchDB is not doing any compaction and 1260 documents are listed in the doc_del_count when I call /couchip:5984/my_db
I followed directions here: Retrieve just deleted document
and adjusted it in Python like so:
docs_to_put_back = []
ids_to_put_back = []
for id in db.changes()['results']:
ids_to_put_back.append(id)
for id in ids_to_put_back:
rev = db.get(id, revs=True, open_revs='all')
current_revision = rev[0]['ok']['_rev']
current_number = rev[0]['ok']['_revisions']['start']
rev_id = rev[0]['ok']['_revisons']['ids'][1] # The last revision id
old_doc = db.get(id, rev=str(current_number-1)+'-'+rev_id)
I started printing old_doc from here and most of the time, it returned a NoneType but I did see that some were printing out the documents that I wanted to restore so I added this to the code:
if old_doc != None:
db.save(old_doc, rev=current_revision)
This didn't work and nothing restored to my database. Now when I try to look at all revisions of these documents, I can't seem to return anything but a NoneType when I call old_doc. I tried looping through all the revisions like this:
for id in ids_to_put_back:
rev = db.get(_id, revs=True, open_revs='all')
current_revision = rev[0]['ok']['_rev']
current_number = rev[0]['ok']['_revisions']['start']
rev_list = rev[0]['ok']['_revisions']['ids']
counter = 1
for revision in rev_list[1:]:
old_doc = db.get(_id, rev=str(current_number-counter)+'-'+revision)
if old_doc == None:
counter += 1
continue
elif old_doc != None:
docs_to_put_back.append(old_doc)
break
else:
pass
docs_to_put_back is returning an empty list. From my understanding, if my database is not compacting, I should be able to get the old documents if I have their old revision numbers. However, from what I've been reading, it seems like this may not be the case.
I've also tried putting the document back into the database first and then tried to get an old revision number with curl like so:
curl -X PUT http://localhost:5984/db/id
{"ok": true, "id":"id", "rev":""3-b7ff1b0135c051822dd2958aec1a1b9c"}
curl -X GET http://localhost:5984/db/id?rev=2-1301c6dd3257decf978655f553ae8fa4
{"_id":"id", "rev":"2-1301c6dd3257decf978655f553ae8fa4", "_deleted":true}
curl -X GET http://localhost:5984/db/id?rev=1-42283a6b30639b12adddb814ba9ee4dc
{"error":"not_found", "reason":"missing"}
Am I hosed? Does CouchDB not have access to all the old revisions (which I've read is a kind of a misnomer)?
This wasn't my best day so if you can please help, that would be awesome! Thank you!
Turns out I am hosed so no you can't get those deleted documents back if you wait too long. By default, CouchDB will check your databases every hour and run compaction if it's over something like 131 kb. After that happens, all my old revisions are "missing."
If only CouchDB had an Undo button for user error....