Improved CouchRest::Database#save_doc, added "batch" mode to significantly speed up saves at cost of lower durability gurantees.

This commit is contained in:
Igal Koshevoy 2009-11-15 23:14:09 -08:00
parent b8bda3bb02
commit 62ea68df63

View file

@ -129,7 +129,7 @@ module CouchRest
end end
end end
end end
# Save a document to CouchDB. This will use the <tt>_id</tt> field from # Save a document to CouchDB. This will use the <tt>_id</tt> field from
# the document as the id for PUT, or request a new UUID from CouchDB, if # the document as the id for PUT, or request a new UUID from CouchDB, if
# no <tt>_id</tt> is present on the document. IDs are attached to # no <tt>_id</tt> is present on the document. IDs are attached to
@ -139,7 +139,19 @@ module CouchRest
# #
# If <tt>bulk</tt> is true (false by default) the document is cached for bulk-saving later. # If <tt>bulk</tt> is true (false by default) the document is cached for bulk-saving later.
# Bulk saving happens automatically when #bulk_save_cache limit is exceded, or on the next non bulk save. # Bulk saving happens automatically when #bulk_save_cache limit is exceded, or on the next non bulk save.
def save_doc(doc, bulk = false) #
# If <tt>batch</tt> is true (false by default) the document is saved in
# batch mode, "used to achieve higher throughput at the cost of lower
# guarantees. When [...] sent using this option, it is not immediately
# written to disk. Instead it is stored in memory on a per-user basis for a
# second or so (or the number of docs in memory reaches a certain point).
# After the threshold has passed, the docs are committed to disk. Instead
# of waiting for the doc to be written to disk before responding, CouchDB
# sends an HTTP 202 Accepted response immediately. batch=ok is not suitable
# for crucial data, but it ideal for applications like logging which can
# accept the risk that a small proportion of updates could be lost due to a
# crash."
def save_doc(doc, bulk = false, batch = false)
if doc['_attachments'] if doc['_attachments']
doc['_attachments'] = encode_attachments(doc['_attachments']) doc['_attachments'] = encode_attachments(doc['_attachments'])
end end
@ -153,7 +165,9 @@ module CouchRest
result = if doc['_id'] result = if doc['_id']
slug = escape_docid(doc['_id']) slug = escape_docid(doc['_id'])
begin begin
CouchRest.put "#{@root}/#{slug}", doc uri = "#{@root}/#{slug}"
uri << "?batch=ok" if batch
CouchRest.put uri, doc
rescue HttpAbstraction::ResourceNotFound rescue HttpAbstraction::ResourceNotFound
p "resource not found when saving even tho an id was passed" p "resource not found when saving even tho an id was passed"
slug = doc['_id'] = @server.next_uuid slug = doc['_id'] = @server.next_uuid