Class: CouchPotato::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/couch_potato/database.rb

Defined Under Namespace

Classes: ValidationsFailedError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(couchrest_database, name: nil) ⇒ Database

Returns a new instance of Database.



15
16
17
18
# File 'lib/couch_potato/database.rb', line 15

def initialize(couchrest_database, name: nil)
  @name = name
  @couchrest_database = couchrest_database
end

Instance Attribute Details

#cacheObject

Pass in a cache to enable caching #load calls. A cache needs to respond to #[], #[]= and #clear (just use a Hash).



10
11
12
# File 'lib/couch_potato/database.rb', line 10

def cache
  @cache
end

#couchrest_databaseObject (readonly)

returns the underlying CouchRest::Database instance



206
207
208
# File 'lib/couch_potato/database.rb', line 206

def couchrest_database
  @couchrest_database
end

#nameObject (readonly)

the (unresolved) name of the database unless this is the default database



13
14
15
# File 'lib/couch_potato/database.rb', line 13

def name
  @name
end

#switched_databasesObject

Returns the value of attribute switched_databases.



208
209
210
# File 'lib/couch_potato/database.rb', line 208

def switched_databases
  @switched_databases
end

Instance Method Details

#destroy_document(document) ⇒ Object Also known as: destroy



136
137
138
139
140
141
142
143
# File 'lib/couch_potato/database.rb', line 136

def destroy_document(document)
  cache&.clear
  begin
    destroy_document_without_conflict_handling document
  rescue CouchRest::Conflict
    retry if document = document.reload
  end
end

#first(spec) ⇒ Object

returns the first result from a #view query or nil



97
98
99
100
101
# File 'lib/couch_potato/database.rb', line 97

def first(spec)
  spec.view_parameters = spec.view_parameters.merge({ limit: 1 })
  result = view(spec)
  flex_view?(spec) ? result.docs.first : result.first
end

#first!(spec) ⇒ Object

returns th first result from a #view or raises CouchPotato::NotFound



104
105
106
# File 'lib/couch_potato/database.rb', line 104

def first!(spec)
  first(spec) || raise(CouchPotato::NotFound)
end

#inspectObject

Signature:

  • nodoc:



201
202
203
# File 'lib/couch_potato/database.rb', line 201

def inspect #:nodoc:
  "#<CouchPotato::Database @root=\"#{couchrest_database.root}\">"
end

#load!(id) ⇒ Object

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



193
194
195
196
197
198
199
# File 'lib/couch_potato/database.rb', line 193

def load!(id)
  doc = load(id)
  missing_docs = id - doc.map(&:id) if id.is_a?(Array)
  raise(CouchPotato::NotFound, missing_docs.try(:join, ', ')) if doc.nil? || missing_docs.try(:any?)

  doc
end

#load_document(id) ⇒ Object Also known as: load

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



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/couch_potato/database.rb', line 151

def load_document(id)
  return load_documents(id) if id.is_a?(Array)
  
  cached = cache && cache[id]
  if cache
    if cache.key?(id)
      ActiveSupport::Notifications.instrument('couch_potato.load.cached', id: id, doc: cached) do
        cached
      end
    else
      cache[id] = load_document_without_caching(id)
      cache[id]
    end
  else
    load_document_without_caching(id)
  end
end

#load_documents(ids) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/couch_potato/database.rb', line 170

def load_documents(ids)
  ids = ids.compact
  return [] if ids.empty?

  uncached_ids = ids - (cache&.keys || [])
  uncached_docs_by_id = bulk_load(uncached_ids).index_by {|doc| doc.id if doc.respond_to?(:id) }
  cached_docs_by_id = cache&.slice(*ids) || {}
  if cached_docs_by_id.any?
    ActiveSupport::Notifications.instrument('couch_potato.load.cached', ids: cached_docs_by_id.keys, docs: cached_docs_by_id.values) do
      cached_docs_by_id
    end
  end
  if cache
    uncached_ids.each do |id|
      doc = uncached_docs_by_id[id]
      cache[id] = doc
    end
  end
  ids.filter_map { |id| (cached_docs_by_id[id]) || uncached_docs_by_id[id] }
end

#save_document(document, options = {}, retries = 0, &block) ⇒ Object Also known as: save

saves a document. returns true on success, false on failure. By default validations are run before saving. You can disable validations by passing validate: false as an option. You can also pass a custom validation context by passing context: :custom_context 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


115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/couch_potato/database.rb', line 115

def save_document(document, options = {}, retries = 0, &block)
  cache&.clear
  begin
    block&.call document
    save_document_without_conflict_handling(document, options)
  rescue CouchRest::Conflict
    if block
      handle_write_conflict document, options, retries, &block
    else
      raise CouchPotato::Conflict
    end
  end
end

#save_document!(document, options = {}, &block) ⇒ Object Also known as: save!

saves a document, raises a CouchPotato::Database::ValidationsFailedError on failure



131
132
133
# File 'lib/couch_potato/database.rb', line 131

def save_document!(document, options = {}, &block)
  save_document(document, options, &block) || raise(ValidationsFailedError, document.errors.full_messages)
end

#switch_to(database_name) ⇒ Object

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.



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/couch_potato/database.rb', line 216

def switch_to(database_name)
  self.switched_databases ||= {}
  if (db = switched_databases[database_name || :default])
    return db
  end
  switched_databases[name || :default] ||= self


  resolved_database_name = CouchPotato.resolve_database_name(database_name) unless database_name == :default
  couchrest_database = resolved_database_name ? CouchPotato.couchrest_database_for_name(resolved_database_name) : CouchPotato.couchrest_database
  new_db = self
    .class
    .new(couchrest_database, name: database_name == :default ? nil : database_name)
    .tap(&copy_clear_cache_proc)

  new_db.switched_databases = switched_databases
  new_db
end

#switch_to_defaultObject

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.



238
239
240
# File 'lib/couch_potato/database.rb', line 238

def switch_to_default
  switch_to(:default)
end

#view(spec) ⇒ Object

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]))


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/couch_potato/database.rb', line 49

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

#view_in_batches(spec, batch_size: default_batch_size) ⇒ Object

Same as #view but instead of returning the results, it yields them to a given block in batches of the given size, making multiple requests with according skip/limit params sent to CouchDB.



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
# File 'lib/couch_potato/database.rb', line 69

def view_in_batches(spec, batch_size: default_batch_size)
  rows = nil
  batch = 0
  loop do
    spec.view_parameters = spec
      .view_parameters
      .merge({limit: batch_size})
      .merge(
        if rows
          {
            startkey: rows&.last&.dig('key'),
            startkey_docid: rows&.last&.dig('id'),
            skip: 1
          }
        else
          {}
        end
      )
    result = raw_view(spec)
    rows = result['rows']
    yield process_view_results(result, spec)
    break if rows.size < batch_size

    batch += 1
  end
end