-
Notifications
You must be signed in to change notification settings - Fork 62
/
database.rb
317 lines (288 loc) · 9.95 KB
/
database.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
module CouchPotato
class Database
class ValidationsFailedError < ::StandardError; end
# Pass in a cache to enable caching #load calls.
# A cache needs to respond to #[], #[]= and #clear (just use a Hash).
attr_accessor :cache
cattr_accessor :default_batch_size
self.default_batch_size = 500
attr_reader :name # the (unresolved) name of the database unless this is the default database
def initialize(couchrest_database, name: nil)
@name = name
@couchrest_database = couchrest_database
end
# executes a view and return the results. you pass in a view spec
# which is usually a result of a SomePersistentClass.some_view call.
#
# Example:
#
# class User
# include CouchPotato::Persistence
# property :age
# view :all, key: :age
# end
# db = CouchPotato.database
#
# db.view(User.all) # => [user1, user2]
#
# You can pass the usual parameters you can pass to a couchdb view to the view:
#
# db.view(User.all(limit: 5, startkey: 2, reduce: false))
#
# For your convenience when passing a hash with only a key parameter you can just pass in the value
#
# db.view(User.all(key: 1)) == db.view(User.all(1))
#
# Instead of passing a startkey and endkey you can pass in a key with a range:
#
# db.view(User.all(key: 1..20)) == db.view(startkey: 1, endkey: 20) == db.view(User.all(1..20))
#
# You can also pass in multiple keys:
#
# db.view(User.all(keys: [1, 2, 3]))
def view(spec)
id = view_cache_id(spec)
cached = cache && id.is_a?(String) && cache[id]
if cache
if cached
ActiveSupport::Notifications.instrument('couch_potato.view.cached') do
cached
end
else
cache[id] = view_without_caching(spec)
cache[id]
end
else
view_without_caching(spec)
end
end
# returns the first result from a #view query or nil
def first(spec)
spec.view_parameters = spec.view_parameters.merge({:limit => 1})
view(spec).first
end
# returns th first result from a #view or raises CouchPotato::NotFound
def first!(spec)
first(spec) || raise(CouchPotato::NotFound)
end
# saves a document. returns true on success, false on failure.
# if passed a block will:
# * yield the object to be saved to the block and run if once before saving
# * on conflict: reload the document, run the block again and retry saving
def save_document(document, validate = true, retries = 0, &block)
cache&.clear
begin
block.call document if block
save_document_without_conflict_handling(document, validate)
rescue CouchRest::Conflict
if block
handle_write_conflict document, validate, retries, &block
else
raise CouchPotato::Conflict.new
end
end
end
alias_method :save, :save_document
# saves a document, raises a CouchPotato::Database::ValidationsFailedError on failure
def save_document!(document)
save_document(document) || raise(ValidationsFailedError.new(document.errors.full_messages))
end
alias_method :save!, :save_document!
def destroy_document(document)
cache&.clear
begin
destroy_document_without_conflict_handling document
rescue CouchRest::Conflict
retry if document = document.reload
end
end
alias_method :destroy, :destroy_document
# loads a document by its id(s)
# id - either a single id or an array of ids
# returns either a single document or an array of documents (if an array of ids was passed).
# returns nil if the single document could not be found. when passing an array and some documents
# could not be found these are omitted from the returned array
def load_document(id)
cached = cache && id.is_a?(String) && cache[id]
if cache
if cached
ActiveSupport::Notifications.instrument('couch_potato.load.cached') do
cached
end
else
cache[id] = load_document_without_caching(id)
cache[id]
end
else
load_document_without_caching(id)
end
end
alias_method :load, :load_document
# loads one or more documents by its id(s)
# behaves like #load except it raises a CouchPotato::NotFound if any of the documents could not be found
def load!(id)
doc = load(id)
if id.is_a?(Array)
missing_docs = id - doc.map(&:id)
end
raise(CouchPotato::NotFound, missing_docs.try(:join, ', ')) if doc.nil? || missing_docs.try(:any?)
doc
end
def inspect #:nodoc:
"#<CouchPotato::Database @root=\"#{couchrest_database.root}\">"
end
# returns the underlying CouchRest::Database instance
def couchrest_database
@couchrest_database
end
# returns a new database instance connected to the CouchDB database
# with the given name. the name is passed through the
# additional_databases configuration to resolve it to a database
# configured there.
# if the current database has a cache, the new database will receive
# a cleared copy of it.
def switch_to(database_name)
resolved_database_name = CouchPotato.resolve_database_name(database_name)
self
.class
.new(CouchPotato.couchrest_database_for_name(resolved_database_name), name: database_name)
.tap(©_clear_cache_proc)
end
# returns a new database instance connected to the default CouchDB database.
# if the current database has a cache, the new database will receive
# a cleared copy of it.
def switch_to_default
self
.class
.new(CouchPotato.couchrest_database)
.tap(©_clear_cache_proc)
end
private
def copy_clear_cache_proc
->(db) {
next unless cache
db.cache = cache.dup
db.cache.clear
}
end
def view_without_caching(spec)
ActiveSupport::Notifications.instrument('couch_potato.view', name: "#{spec.design_document}/#{spec.view_name}") do
results = CouchPotato::View::ViewQuery.new(
couchrest_database,
spec.design_document,
{spec.view_name => {
:map => spec.map_function,
:reduce => spec.reduce_function
}
},
({spec.list_name => spec.list_function} unless spec.list_name.nil?),
spec.lib,
spec.language
).query_view!(spec.view_parameters)
processed_results = spec.process_results results
processed_results.each do |document|
document.database = self if document.respond_to?(:database=)
end if processed_results.respond_to?(:each)
processed_results
end
end
def load_document_without_caching(id)
raise "Can't load a document without an id (got nil)" if id.nil?
ActiveSupport::Notifications.instrument('couch_potato.load') do
if id.is_a?(Array)
bulk_load id
else
instance = couchrest_database.get(id)
instance.database = self if instance
instance
end
end
end
def view_cache_id(spec)
spec.send(:klass).to_s + spec.view_name.to_s + spec.view_parameters.to_s
end
def handle_write_conflict(document, validate, retries, &block)
cache&.clear
if retries == 5
raise CouchPotato::Conflict.new
else
reloaded = document.reload
document.attributes = reloaded.attributes
document._rev = reloaded._rev
save_document document, validate, retries + 1, &block
end
end
def destroy_document_without_conflict_handling(document)
document.run_callbacks :destroy do
document._deleted = true
couchrest_database.delete_doc document.to_hash
end
document._id = nil
document._rev = nil
end
def save_document_without_conflict_handling(document, validate = true)
if document.new?
create_document(document, validate)
else
update_document(document, validate)
end
end
def bulk_load(ids)
response = couchrest_database.bulk_load ids
docs = response['rows'].map{|row| row["doc"]}.compact
docs.each{|doc|
doc.database = self if doc.respond_to?(:database=)
}
end
def create_document(document, validate)
document.database = self
if validate
document.errors.clear
return false if false == document.run_callbacks(:validation_on_save) do
return false if false == document.run_callbacks(:validation_on_create) do
return false unless valid_document?(document)
end
end
end
return false if false == document.run_callbacks(:save) do
return false if false == document.run_callbacks(:create) do
res = couchrest_database.save_doc document.to_hash
document._rev = res['rev']
document._id = res['id']
end
end
true
end
def update_document(document, validate)
if validate
document.errors.clear
return false if false == document.run_callbacks(:validation_on_save) do
return false if false == document.run_callbacks(:validation_on_update) do
return false unless valid_document?(document)
end
end
end
return false if false == document.run_callbacks(:save) do
return false if false == document.run_callbacks(:update) do
if document.changed?
res = couchrest_database.save_doc document.to_hash
document._rev = res['rev']
end
end
end
true
end
def valid_document?(document)
original_errors_hash = document.errors.to_hash
document.valid?
original_errors_hash.each do |k, v|
if v.respond_to?(:each)
v.each {|message| document.errors.add(k, message)}
else
document.errors.add(k, v)
end
end
document.errors.empty?
end
end
end