Class: IbmCloudRest::Database

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server, name) ⇒ Database

Create a IbmCloudRest::Database adapter for the supplied IbmCloudRest::Server and database name.

Parameters

server<IbmCloudRest::Server>

database host

name<String>

database name



16
17
18
19
20
21
22
23
24
25
# File 'lib/ibm_cloud_rest/core/database.rb', line 16

def initialize(server, name)
  @name = name
  @server = server
  @host = server.uri
  @uri  = "/#{name.gsub('/','%2F')}"
  @root = host + uri
  @streamer = Streamer.new(self)
  @bulk_save_cache = []
  @bulk_save_cache_limit = 500  # must be smaller than the uuid count
end

Instance Attribute Details

#bulk_save_cache_limitObject

Returns the value of attribute bulk_save_cache_limit.



7
8
9
# File 'lib/ibm_cloud_rest/core/database.rb', line 7

def bulk_save_cache_limit
  @bulk_save_cache_limit
end

#hostObject (readonly)

Returns the value of attribute host.



6
7
8
# File 'lib/ibm_cloud_rest/core/database.rb', line 6

def host
  @host
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/ibm_cloud_rest/core/database.rb', line 6

def name
  @name
end

#rootObject (readonly)

Returns the value of attribute root.



6
7
8
# File 'lib/ibm_cloud_rest/core/database.rb', line 6

def root
  @root
end

#serverObject (readonly)

Returns the value of attribute server.



6
7
8
# File 'lib/ibm_cloud_rest/core/database.rb', line 6

def server
  @server
end

#uriObject (readonly)

Returns the value of attribute uri.



6
7
8
# File 'lib/ibm_cloud_rest/core/database.rb', line 6

def uri
  @uri
end

Instance Method Details

#bulk_save(docs = nil, use_uuids = true) ⇒ Object Also known as: bulk_delete

POST an array of documents to CouchDB. If any of the documents are missing ids, supply one from the uuid cache.

If called with no arguments, bulk saves the cache of documents to be bulk saved.



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/ibm_cloud_rest/core/database.rb', line 189

def bulk_save(docs = nil, use_uuids = true)
  if docs.nil?
    docs = @bulk_save_cache
    @bulk_save_cache = []
  end
  if (use_uuids) 
    ids, noids = docs.partition{|d|d['_id']}
    uuid_count = [noids.length, @server.uuid_batch_count].max
    noids.each do |doc|
      nextid = @server.next_uuid(uuid_count) rescue nil
      doc['_id'] = nextid if nextid
    end
  end
  IbmCloudRest.post "#{@root}/_bulk_docs", {:docs => docs}
end

#compact!Object

Compact the database, removing old document revisions and optimizing space use.



249
250
251
# File 'lib/ibm_cloud_rest/core/database.rb', line 249

def compact!
  IbmCloudRest.post "#{@root}/_compact"
end

#copy(doc, dest) ⇒ Object

DEPRECATION NOTICE



243
244
245
246
# File 'lib/ibm_cloud_rest/core/database.rb', line 243

def copy(doc, dest)
  puts "IbmCloudRest::Database's copy method is being deprecated, please use copy_doc instead"
  copy_doc(doc, dest)
end

#copy_doc(doc, dest) ⇒ Object

COPY an existing document to a new id. If the destination id currently exists, a rev must be provided. dest can take one of two forms if overwriting: “id_to_overwrite?rev=revision” or the actual doc hash with a ‘_rev’ key

Raises:

  • (ArgumentError)


231
232
233
234
235
236
237
238
239
240
# File 'lib/ibm_cloud_rest/core/database.rb', line 231

def copy_doc(doc, dest)
  raise ArgumentError, "_id is required for copying" unless doc['_id']
  slug = escape_docid(doc['_id'])        
  destination = if dest.respond_to?(:has_key?) && dest['_id'] && dest['_rev']
    "#{dest['_id']}?rev=#{dest['_rev']}"
  else
    dest
  end
  IbmCloudRest.copy "#{@root}/#{slug}", destination
end

#create!Object

Create the database



254
255
256
257
# File 'lib/ibm_cloud_rest/core/database.rb', line 254

def create!
  bool = server.create_db(@name) rescue false
  bool && true
end

#delete(doc, bulk = false) ⇒ Object

DEPRECATION NOTICE



223
224
225
226
# File 'lib/ibm_cloud_rest/core/database.rb', line 223

def delete(doc, bulk=false)
  puts "IbmCloudRest::Database's delete method is being deprecated, please use delete_doc instead"
  delete_doc(doc, bulk)
end

#delete!Object

DELETE the database itself. This is not undoable and could be rather catastrophic. Use with care!



282
283
284
285
# File 'lib/ibm_cloud_rest/core/database.rb', line 282

def delete!
  clear_extended_doc_fresh_cache
  IbmCloudRest.delete @root
end

#delete_attachment(doc, name, force = false) ⇒ Object

DELETE an attachment directly from CouchDB



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/ibm_cloud_rest/core/database.rb', line 116

def delete_attachment(doc, name, force=false)
  uri = url_for_attachment(doc, name)
  # this needs a rev
  begin
    JSON.parse(HttpAbstraction.delete(uri))
  rescue Exception => error
    if force
      # get over a 409
      doc = get(doc['_id'])
      uri = url_for_attachment(doc, name)
      JSON.parse(HttpAbstraction.delete(uri))
    else
      error
    end
  end
end

#delete_doc(doc, bulk = false) ⇒ Object

DELETE the document from CouchDB that has the given _id and _rev.

If bulk is true (false by default) the deletion is recorded for bulk-saving (bulk-deletion :) later. Bulk saving happens automatically when #bulk_save_cache limit is exceded, or on the next non bulk save.

Raises:

  • (ArgumentError)


211
212
213
214
215
216
217
218
219
220
# File 'lib/ibm_cloud_rest/core/database.rb', line 211

def delete_doc(doc, bulk = false)
  raise ArgumentError, "_id and _rev required for deleting" unless doc['_id'] && doc['_rev']      
  if bulk
    @bulk_save_cache << { '_id' => doc['_id'], '_rev' => doc['_rev'], '_deleted' => true }
    return bulk_save if @bulk_save_cache.length >= @bulk_save_cache_limit
    return { "ok" => true } # Mimic the non-deferred version
  end
  slug = escape_docid(doc['_id'])        
  IbmCloudRest.delete "#{@root}/#{slug}?rev=#{doc['_rev']}"
end

#documents(params = {}) ⇒ Object

Query the _all_docs view. Accepts all the same arguments as view.



38
39
40
41
42
43
44
45
46
# File 'lib/ibm_cloud_rest/core/database.rb', line 38

def documents(params = {})
  keys = params.delete(:keys)
  url = IbmCloudRest.paramify_url "#{@root}/_all_docs", params
  if keys
    IbmCloudRest.post(url, {:keys => keys})
  else
    IbmCloudRest.get url
  end
end

#fetch_attachment(doc, name) ⇒ Object

GET an attachment directly from CouchDB



102
103
104
105
# File 'lib/ibm_cloud_rest/core/database.rb', line 102

def fetch_attachment(doc, name)
  uri = url_for_attachment(doc, name)
  HttpAbstraction.get uri
end

#get(id, params = {}) ⇒ Object

GET a document from CouchDB, by id. Returns a Ruby Hash.



87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ibm_cloud_rest/core/database.rb', line 87

def get(id, params = {})
  slug = escape_docid(id)
  url = IbmCloudRest.paramify_url("#{@root}/#{slug}", params)
  result = IbmCloudRest.get(url)
  return result unless result.is_a?(Hash)
  doc = if /^_design/ =~ result["_id"]
    Design.new(result)
  else
    Document.new(result)
  end
  doc.database = self
  doc
end

#get_bulk(ids) ⇒ Object Also known as: bulk_load

load a set of documents by passing an array of ids



49
50
51
# File 'lib/ibm_cloud_rest/core/database.rb', line 49

def get_bulk(ids)
  documents(:keys => ids, :include_docs => true)
end

#infoObject

GET the database info from CouchDB



33
34
35
# File 'lib/ibm_cloud_rest/core/database.rb', line 33

def info
  IbmCloudRest.get @root
end

#put_attachment(doc, name, file, options = {}) ⇒ Object

PUT an attachment directly to CouchDB



108
109
110
111
112
113
# File 'lib/ibm_cloud_rest/core/database.rb', line 108

def put_attachment(doc, name, file, options = {})
  docid = escape_docid(doc['_id'])
  name = CGI.escape(name)
  uri = url_for_attachment(doc, name)
  JSON.parse(HttpAbstraction.put(uri, file, options))
end

#recreate!Object

Delete and re create the database



260
261
262
263
264
265
266
# File 'lib/ibm_cloud_rest/core/database.rb', line 260

def recreate!
  delete!
  create!
rescue HttpAbstraction::ResourceNotFound
ensure
  create!
end

#replicate_from(other_db) ⇒ Object

Replicates via “pulling” from another database to this database. Makes no attempt to deal with conflicts.

Raises:

  • (ArgumentError)


269
270
271
272
# File 'lib/ibm_cloud_rest/core/database.rb', line 269

def replicate_from other_db
  raise ArgumentError, "must provide a CouchReset::Database" unless other_db.kind_of?(IbmCloudRest::Database)
  IbmCloudRest.post "#{@host}/_replicate", :source => other_db.root, :target => name
end

#replicate_to(other_db) ⇒ Object

Replicates via “pushing” to another database. Makes no attempt to deal with conflicts.

Raises:

  • (ArgumentError)


275
276
277
278
# File 'lib/ibm_cloud_rest/core/database.rb', line 275

def replicate_to other_db
  raise ArgumentError, "must provide a CouchReset::Database" unless other_db.kind_of?(IbmCloudRest::Database)
  IbmCloudRest.post "#{@host}/_replicate", :target => other_db.root, :source => name
end

#save(doc, bulk = false) ⇒ Object

DEPRECATION NOTICE



179
180
181
182
# File 'lib/ibm_cloud_rest/core/database.rb', line 179

def save(doc, bulk=false)
  puts "IbmCloudRest::Database's save method is being deprecated, please use save_doc instead"
  save_doc(doc, bulk)
end

#save_doc(doc, bulk = false) ⇒ Object

Save a document to CouchDB. This will use the _id field from the document as the id for PUT, or request a new UUID from CouchDB, if no _id is present on the document. IDs are attached to documents on the client side because POST has the curious property of being automatically retried by proxies in the event of network segmentation and lost responses.

If bulk 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.



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
# File 'lib/ibm_cloud_rest/core/database.rb', line 142

def save_doc(doc, bulk = false)
  if doc['_attachments']
    doc['_attachments'] = encode_attachments(doc['_attachments'])
  end
  if bulk
    @bulk_save_cache << doc
    return bulk_save if @bulk_save_cache.length >= @bulk_save_cache_limit
    return {"ok" => true} # Compatibility with Document#save
  elsif !bulk && @bulk_save_cache.length > 0
    bulk_save
  end
  result = if doc['_id']
    slug = escape_docid(doc['_id'])
    begin     
      IbmCloudRest.put "#{@root}/#{slug}", doc
    rescue HttpAbstraction::ResourceNotFound
      p "resource not found when saving even tho an id was passed"
      slug = doc['_id'] = @server.next_uuid
      IbmCloudRest.put "#{@root}/#{slug}", doc
    end
  else
    begin
      slug = doc['_id'] = @server.next_uuid
      IbmCloudRest.put "#{@root}/#{slug}", doc
    rescue #old version of couchdb
      IbmCloudRest.post @root, doc
    end
  end
  if result['ok']
    doc['_id'] = result['id']
    doc['_rev'] = result['rev']
    doc.database = self if doc.respond_to?(:database=)
  end
  result
end

#slow_view(funcs, params = {}) ⇒ Object Also known as: temp_view

POST a temporary view function to CouchDB for querying. This is not recommended, as you don’t get any performance benefit from CouchDB’s materialized views. Can be quite slow on large databases.



57
58
59
60
61
62
# File 'lib/ibm_cloud_rest/core/database.rb', line 57

def slow_view(funcs, params = {})
  keys = params.delete(:keys)
  funcs = funcs.merge({:keys => keys}) if keys
  url = IbmCloudRest.paramify_url "#{@root}/_temp_view", params
  JSON.parse(HttpAbstraction.post(url, funcs.to_json, {"Content-Type" => 'application/json'}))
end

#to_sObject

returns the database’s uri



28
29
30
# File 'lib/ibm_cloud_rest/core/database.rb', line 28

def to_s
  @root
end

#view(name, params = {}, &block) ⇒ Object

Query a CouchDB view as defined by a _design document. Accepts paramaters as described in wiki.apache.org/couchdb/HttpViewApi



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/ibm_cloud_rest/core/database.rb', line 69

def view(name, params = {}, &block)
  keys = params.delete(:keys)
  name = name.split('/') # I think this will always be length == 2, but maybe not...
  dname = name.shift
  vname = name.join('/')
  url = IbmCloudRest.paramify_url "#{@root}/_design/#{dname}/_view/#{vname}", params
  if keys
    IbmCloudRest.post(url, {:keys => keys})
  else
    if block_given?
      @streamer.view("_design/#{dname}/_view/#{vname}", params, &block)
    else
      IbmCloudRest.get url
    end
  end
end