Module: Couchbase::Operations::Store

Defined in:
lib/couchbase/operations/store.rb

Constant Summary collapse

STORE_OP_METHODS =
{
  set:     -> client, key, value, ttl, transcoder { client.set(key, ttl, value, transcoder) },
  add:     -> client, key, value, ttl, transcoder { client.add(key, ttl, value, transcoder) },
  replace: -> client, key, value, ttl, transcoder { client.replace(key, ttl, value, transcoder) },
  append:  -> client, key, value, ttl, transcoder { client.append(key, value) },
  prepend: -> client, key, value, ttl, transcoder { client.prepend(key, value) }
}.freeze

Instance Method Summary collapse

Instance Method Details

#[]=(key, *args) ⇒ Object



139
140
141
142
143
144
# File 'lib/couchbase/operations/store.rb', line 139

def []=(key, *args)
  options = args.size > 1 ? args.shift : {}
  value   = args.pop

  set(key, value, options)
end

#add(key, value, options = {}) {|ret| ... } ⇒ Fixnum

Add the item to the database, but fail if the object exists already

Returns The CAS value of the object.

Examples:

Add the same key twice

c.add("foo", "bar")  #=> stored successully
c.add("foo", "baz")  #=> will raise Couchbase::Error::KeyExists: failed to store value (key="foo", error=0x0c)

Ensure that the key will be persisted at least on the one node

c.add("foo", "bar", :observe => {:persisted => 1})

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

  • options (Hash) (defaults to: {})

    Options for operation.

Options Hash (options):

  • :ttl (Fixnum) — default: self.default_ttl

    Expiry time for key. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).

  • :flags (Fixnum) — default: self.default_flags

    Flags for storage options. Flags are ignored by the server but preserved for use by the client. For more info see Bucket#default_flags.

  • :format (Symbol) — default: self.default_format

    The representation for storing the value in the bucket. For more info see Bucket#default_format.

  • :cas (Fixnum)

    The CAS value for an object. This value created on the server and is guaranteed to be unique for each value of a given key. This value is used to provide simple optimistic concurrency control when multiple clients or threads try to update an item simultaneously.

  • :observe (Hash)

    Apply persistence condition before returning result. When this option specified the library will observe given condition. See Bucket#observe_and_wait.

Yield Parameters:

  • ret (Result)

    the result of operation in asynchronous mode (valid attributes: error, operation, key).

Returns:

  • (Fixnum)

    The CAS value of the object.

Raises:

Since:

  • 1.0.0



195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/couchbase/operations/store.rb', line 195

def add(key, value = nil, options = {})
  if async?
    if block_given?
      async_add(key, value, options, &Proc.new)
    else
      async_add(key, value, options)
    end
  else
    sync_block_error if block_given?
    store_op(:add, key, value, options)
  end
end

#append(key, value, options = {}) ⇒ Fixnum

Note:

This operation is kind of data-aware from server point of view. This mean that the server treats value as binary stream and just perform concatenation, therefore it won’t work with :marshal and :document formats, because of lack of knowledge how to merge values in these formats. See Bucket#cas for workaround.

Append this object to the existing object

Returns The CAS value of the object.

Examples:

Simple append

c.set("foo", "aaa")
c.append("foo", "bbb")
c.get("foo")           #=> "aaabbb"

Implementing sets using append

def set_add(key, *values)
  encoded = values.flatten.map{|v| "+#{v} "}.join
  append(key, encoded)
end

def set_remove(key, *values)
  encoded = values.flatten.map{|v| "-#{v} "}.join
  append(key, encoded)
end

def set_get(key)
  encoded = get(key)
  ret = Set.new
  encoded.split(' ').each do |v|
    op, val = v[0], v[1..-1]
    case op
    when "-"
      ret.delete(val)
    when "+"
      ret.add(val)
    end
  end
  ret
end

Using optimistic locking. The operation will fail on CAS mismatch

ver = c.set("foo", "aaa")
c.append("foo", "bbb", :cas => ver)

Ensure that the key will be persisted at least on the one node

c.append("foo", "bar", :observe => {:persisted => 1})

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

  • options (Hash) (defaults to: {})

    Options for operation.

Options Hash (options):

  • :cas (Fixnum)

    The CAS value for an object. This value created on the server and is guaranteed to be unique for each value of a given key. This value is used to provide simple optimistic concurrency control when multiple clients or threads try to update an item simultaneously.

  • :format (Symbol) — default: self.default_format

    The representation for storing the value in the bucket. For more info see Bucket#default_format.

  • :observe (Hash)

    Apply persistence condition before returning result. When this option specified the library will observe given condition. See Bucket#observe_and_wait.

Returns:

  • (Fixnum)

    The CAS value of the object.

Raises:

Since:

  • 1.0.0



343
344
345
346
# File 'lib/couchbase/operations/store.rb', line 343

def append(key, value)
  sync_block_error if block_given?
  store_op(:append, key, value)
end

#async_add(key, value, options, &block) ⇒ Object



208
209
210
# File 'lib/couchbase/operations/store.rb', line 208

def async_add(key, value, options, &block)
  async_store_op(:add, key, value, options, &block)
end

#async_replace(key, value, options, &block) ⇒ Object



266
267
268
# File 'lib/couchbase/operations/store.rb', line 266

def async_replace(key, value, options, &block)
  async_store_op(:replace, key, value, options, &block)
end

#async_set(key, value, options, &block) ⇒ Object



135
136
137
# File 'lib/couchbase/operations/store.rb', line 135

def async_set(key, value, options, &block)
  async_store_op(:set, key, value, options, &block)
end

#prepend(key, value, options = {}) ⇒ Object

Note:

This operation is kind of data-aware from server point of view. This mean that the server treats value as binary stream and just perform concatenation, therefore it won’t work with :marshal and :document formats, because of lack of knowledge how to merge values in these formats. See Bucket#cas for workaround.

Prepend this object to the existing object

Examples:

Simple prepend example

c.set("foo", "aaa")
c.prepend("foo", "bbb")
c.get("foo")           #=> "bbbaaa"

Using explicit format option

c.default_format       #=> :document
c.set("foo", {"y" => "z"})
c.prepend("foo", '[', :format => :plain)
c.append("foo", ', {"z": "y"}]', :format => :plain)
c.get("foo")           #=> [{"y"=>"z"}, {"z"=>"y"}]

Using optimistic locking. The operation will fail on CAS mismatch

ver = c.set("foo", "aaa")
c.prepend("foo", "bbb", :cas => ver)

Ensure that the key will be persisted at least on the one node

c.prepend("foo", "bar", :observe => {:persisted => 1})

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

  • options (Hash) (defaults to: {})

    Options for operation.

Options Hash (options):

  • :cas (Fixnum)

    The CAS value for an object. This value created on the server and is guaranteed to be unique for each value of a given key. This value is used to provide simple optimistic concurrency control when multiple clients or threads try to update an item simultaneously.

  • :format (Symbol) — default: self.default_format

    The representation for storing the value in the bucket. For more info see Bucket#default_format.

  • :observe (Hash)

    Apply persistence condition before returning result. When this option specified the library will observe given condition. See Bucket#observe_and_wait.

Raises:

Since:

  • 1.0.0



400
401
402
403
# File 'lib/couchbase/operations/store.rb', line 400

def prepend(key, value)
  sync_block_error if block_given?
  store_op(:prepend, key, value)
end

#replace(key, value, options = {}) ⇒ Fixnum

Replace the existing object in the database

Returns The CAS value of the object.

Examples:

Replacing missing key

c.replace("foo", "baz")  #=> will raise Couchbase::Error::NotFound: failed to store value (key="foo", error=0x0d)

Ensure that the key will be persisted at least on the one node

c.replace("foo", "bar", :observe => {:persisted => 1})

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

  • options (Hash) (defaults to: {})

    Options for operation.

Options Hash (options):

  • :ttl (Fixnum) — default: self.default_ttl

    Expiry time for key. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).

  • :flags (Fixnum) — default: self.default_flags

    Flags for storage options. Flags are ignored by the server but preserved for use by the client. For more info see Bucket#default_flags.

  • :format (Symbol) — default: self.default_format

    The representation for storing the value in the bucket. For more info see Bucket#default_format.

  • :cas (Fixnum)

    The CAS value for an object. This value created on the server and is guaranteed to be unique for each value of a given key. This value is used to provide simple optimistic concurrency control when multiple clients or threads try to update an item simultaneously.

  • :observe (Hash)

    Apply persistence condition before returning result. When this option specified the library will observe given condition. See Bucket#observe_and_wait.

Returns:

  • (Fixnum)

    The CAS value of the object.

Raises:

Since:

  • 1.0.0



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/couchbase/operations/store.rb', line 253

def replace(key, value, options = {})
  if async?
    if block_given?
      async_replace(key, value, options, &Proc.new)
    else
      async_replace(key, value, options)
    end
  else
    sync_block_error if block_given?
    store_op(:replace, key, value, options)
  end
end

#set(key, value, options = {}) {|ret| ... } ⇒ Fixnum

Unconditionally store the object in the Couchbase

Returns The CAS value of the object.

Examples:

Store the key which will be expired in 2 seconds using relative TTL.

c.set("foo", "bar", :ttl => 2)

Perform multi-set operation. It takes a Hash store its keys/values into the bucket

c.set("foo1" => "bar1", "foo2" => "bar2")
#=> {"foo1" => cas1, "foo2" => cas2}

More advanced multi-set using asynchronous mode

c.run do
  # fire and forget
  c.set("foo1", "bar1", :ttl => 10)
  # receive result into the callback
  c.set("foo2", "bar2", :ttl => 10) do |ret|
    if ret.success?
      puts ret.cas
    end
  end
end

Store the key which will be expired in 2 seconds using absolute TTL.

c.set("foo", "bar", :ttl => Time.now.to_i + 2)

Force JSON document format for value

c.set("foo", {"bar" => "baz}, :format => :document)

Use hash-like syntax to store the value

c["foo"] = {"bar" => "baz}

Use extended hash-like syntax

c["foo", {:flags => 0x1000, :format => :plain}] = "bar"
c["foo", :flags => 0x1000] = "bar"  # for ruby 1.9.x only

Set application specific flags (note that it will be OR-ed with format flags)

c.set("foo", "bar", :flags => 0x1000)

Perform optimistic locking by specifying last known CAS version

c.set("foo", "bar", :cas => 8835713818674332672)

Perform asynchronous call

c.run do
  c.set("foo", "bar") do |ret|
    ret.operation   #=> :set
    ret.success?    #=> true
    ret.key         #=> "foo"
    ret.cas
  end
end

Ensure that the key will be persisted at least on the one node

c.set("foo", "bar", :observe => {:persisted => 1})

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

  • options (Hash) (defaults to: {})

    Options for operation.

Options Hash (options):

  • :ttl (Fixnum) — default: self.default_ttl

    Expiry time for key. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).

  • :flags (Fixnum) — default: self.default_flags

    Flags for storage options. Flags are ignored by the server but preserved for use by the client. For more info see Bucket#default_flags.

  • :format (Symbol) — default: self.default_format

    The representation for storing the value in the bucket. For more info see Bucket#default_format.

  • :cas (Fixnum)

    The CAS value for an object. This value is created on the server and is guaranteed to be unique for each value of a given key. This value is used to provide simple optimistic concurrency control when multiple clients or threads try to update an item simultaneously.

  • :observe (Hash)

    Apply persistence condition before returning result. When this option specified the library will observe given condition. See Bucket#observe_and_wait.

Yield Parameters:

  • ret (Result)

    the result of operation in asynchronous mode (valid attributes: error, operation, key).

Returns:

  • (Fixnum)

    The CAS value of the object.

Raises:

Since:

  • 1.0.0



122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/couchbase/operations/store.rb', line 122

def set(key, value = nil, options = {})
  if async?
    if block_given?
      async_set(key, value, options, &Proc.new)
    else
      async_set(key, value, options)
    end
  else
    sync_block_error if block_given?
    store_op(:set, key, value, options)
  end
end