Schlagwort-Archive: deleted

CouchDB: restore deleted documents

This is a python based approach to restore deleted documents from couchdb if you have not compacted the database already. The following code snipped is based on this solution.

#!/usr/bin/python

import httplib
import json

SERVER_URL = 'localhost:5984' # host address
FILE_NAME = 'deleted.json' # one line in deleted.json: id,rev\n (comma-seperatet id and rev of deleted doc one line each)
DB_NAME = 'db' #database name

conn = httplib.HTTPConnection(SERVER_URL)

def count_lines(filename):
    lines = 0
    for line in open(filename):
        lines += 1
    return lines

with open(FILE_NAME) as file:
	i = 0
	count = count_lines(FILE_NAME)
	for line in file:
		i += 1
		print 'Document [{}/{}]'.format(i,count)
		
		doc = line.split(',')
		id = doc[0]
		rev = doc[1].rstrip()
		
		#empty doc
		uri = '/{}/{}?rev={}'.format(DB_NAME, id, rev)
		body = '{}'
		headers = {"Content-type": "application/json"}
		print uri
		conn.request("PUT", uri, body, headers)
		r = conn.getresponse()
		r.read()
		
		#get old rev
		uri = '/{}/{}?revs_info=true'.format(DB_NAME, id)
		conn.request("GET", uri)
		print uri
		r = conn.getresponse()
		obj = json.loads(r.read())
		oldRev = obj['_revs_info'][2]['rev'].encode("utf-8")
		print oldRev
		currentRev = obj['_revs_info'][0]['rev'].encode("utf-8")
		print currentRev
		
		#get old doc
		uri = '/{}/{}?rev={}'.format(DB_NAME, id, oldRev)
		print uri
		conn.request("GET", uri)
		r = conn.getresponse()
		doc = r.read()
		
		#restore old doc
		uri = '/{}/{}?rev={}'.format(DB_NAME, id, currentRev)
		print uri
		body = doc.replace(oldRev, currentRev)
		headers = {"Content-type": "application/json"}
		conn.request("PUT", uri, body, headers)
		r = conn.getresponse()
		print r.read()