Overview

Defined Under Namespace

Constant Summary

FMT_MASK =

Bitmask for flag bits responsible for format

0x03

FMT_DOCUMENT =

Document format. The (default) format supports most of ruby types which
could be mapped to JSON data (hashes, arrays, strings, numbers). Future
version will be able to run map/reduce queries on the values in the
document form (hashes).

Plain format. The format which force client don't apply any conversions
to the value, but it should be passed as String. It could be useful for
building custom algorithms or formats. For example implement set: dustin.github.com/2011/02/17/memcached-set.html

the list of nodes to connect to. If specified it takes precedence over
:host option. The list must be array of strings in form of host
names or host names with ports (in first case port 8091 will be used, see
examples).

:host(String)
— default:
"localhost"
—

the hostname or IP address of the node

:port(Fixnum)
— default:
8091
—

the port of the managemenent API

:pool(String)
— default:
"default"
—

the pool name

:bucket(String)
— default:
"default"
—

the bucket name

:default_ttl(Fixnum)
— default:
0
—

the TTL used by default during storing key-value pairs.

:default_flags(Fixnum)
— default:
0
—

the default flags.

:default_format(Symbol)
— default:
:document
—

the format, which will be used for values by default. Note that changing
format will amend flags. (see #default_format)

:username(String)
— default:
nil
—

the user name to connect to the cluster. Used to authenticate on management
API. The username could be skipped for protected buckets, the bucket name
will be used instead.

:password(String)
— default:
nil
—

the password of the user.

:quiet(true, false)
— default:
false
—

the flag controlling if raising exception when the client executes
operations on non-existent keys. If it is true it will raise
Error::NotFound exceptions. The default behaviour is to return
nil value silently (might be useful in Rails cache).

:environment(Symbol)
— default:
:production
—

the mode of the connection. Currently it influences only on design
documents set. If the environment is :development, you will able
to get design documents with 'dev_' prefix, otherwise (in
:production mode) the library will hide them from you.

:key_prefix(String)
— default:
nil
—

the prefix string which will be prepended to each key before sending out,
and sripped before returning back to the application.

:timeout(Fixnum)
— default:
2500000
—

the timeout for IO operations (in microseconds)

:default_arithmetic_init(Fixnum, true)
— default:
0
—

the default initial value for arithmetic operations. Setting this option to
any non positive number forces creation missing keys with given default
value. Setting it to true will use zero as initial value. (see
#incr and #decr).

:engine(Symbol)
— default:
:default
—

the IO engine to use Currently following engines are supported:

:default

Built-in engine (multi-thread friendly)

:select

select(2) IO plugin from libcouchbase

:iocp

“I/O Completion Ports” plugin from libcouchbase (windows only)

:libevent

libevent IO plugin from libcouchbase (optional)

:libev

libev IO plugin from libcouchbase (optional)

:eventmachine

EventMachine plugin (builtin, but requires EM gem and ruby 1.9+)

:async(true, false)
— default:
false
—

If true, the connection instance will be considered always asynchronous and
IO interaction will be occured only when #run called.
See #on_connect to hook your code after the instance
will be connected.

#default_arithmetic_init ⇒ Fixnum, true

Returns The initial value for arithmetic operations #incr and
#decr. Setting this attribute will force aforementioned operations
create keys unless they exists in the bucket and will use given value. You
can also just specify true if you'd like just force key
creation with zero default value.

Returns:

(Fixnum, true)
—

The initial value for arithmetic operations #incr and
#decr. Setting this attribute will force aforementioned operations
create keys unless they exists in the bucket and will use given value. You
can also just specify true if you'd like just force key
creation with zero default value.

#default_format ⇒ Symbol

It uses flags field to store the format. It accepts either the Symbol
(:document, :marshal, :plain) or Fixnum (use
constants FMT_DOCUMENT, FMT_MARSHAL, FMT_PLAIN) and silently ignores all
other value.

Here is some notes regarding how to choose the format:

:document (default) format supports most of ruby types which could
be mapped to JSON data (hashes, arrays, strings, numbers). Future version
will be able to run map/reduce queries on the values in the document form
(hashes).

:plain format if you no need any conversions to be applied to your
data, but your data should be passed as String. It could be useful for
building custom algorithms or formats. For example implement set: dustin.github.com/2011/02/17/memcached-set.html

EM.rundopool=Pool.newconnection=Couchbase.new(:engine=>:eventmachine,:async=>true)connection.on_connectdo|result|unlessresult.success?$stderr.puts"Could not connect to CouchBase #{result.error}"elsepool.addresult.bucketendendend

#transcoder ⇒ Object

Set data transcoder for the current connection

It is possible to define custom transcoder to handle all value
transformation, for example, if you need to adopt legacy application. The
transcoder should respond to two methods: dump and load.
They are accepting the data itself, the flags field, and the options hash
from the library.

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 #default_flags.

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

The representation for storing the value in the bucket. For more info see
#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
#observe_and_wait.

#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 #cas for workaround.

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
#default_format.

:observe(Hash)
—

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

Reads a key's value from the server and yields it to a block. Replaces
the key's value with the result of the block as long as the key
hasn't been updated in the meantime, otherwise raises
Error::KeyExists. CAS stands for “compare and swap”, and
avoids the need for manual key mutexing. Read more info here:

# File 'lib/couchbase/bucket.rb', line 82defcas(key,options={})ifasync?block=Proc.newget(key)do|ret|val=block.call(ret)# get new value from caller
set(ret.key,val,options.merge(:cas=>ret.cas,:flags=>ret.flags),&block)endelseval,flags,ver=get(key,:extended=>true)val=yield(val)# get new value from caller
set(key,val,options.merge(:cas=>ver,:flags=>flags))endend

that server values stored and transmitted as unsigned numbers, therefore if
you try to decrement negative or zero key, you will always get zero.

Decrement the value of an existing numeric key

The decrement methods reduce the value of a given key if the corresponding
value can be parsed to an integer value. These operations are provided at a
protocol level to eliminate the need to get, update, and reset a simple
integer value in the database. It supports the use of an explicit offset
value that will be used to reduce the stored value in the database.

If set to true, the operation won't raise error for missing
key, it will return nil. Otherwise it will raise error in
synchronous mode. In asynchronous mode this option ignored.

: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/delete an item simultaneously.

If set to true, the operation will return a tuple +[value, flags,
cas]+, otherwise (by default) it returns just the value.

: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).

:quiet(true, false)
— default:
self.quiet
—

If set to true, the operation won't raise error for missing
key, it will return nil. Otherwise it will raise error in
synchronous mode. In asynchronous mode this option ignored.

:format(Symbol)
— default:
nil
—

Explicitly choose the decoder for this key (:plain,
:document, :marshal). See #default_format.

:lock(Fixnum, Boolean)
—

Lock the keys for time span. If this parameter is true the key(s)
will be locked for default timeout. Also you can use number to setup your
own timeout in seconds. If it will be lower that zero or exceed the
maximum, the server will use default value. You can determine actual
default and maximum values calling #stats without arguments and
inspecting keys “ep_getl_default_timeout” and “ep_getl_max_timeout”
correspondingly. See overloaded hash syntax to specify custom timeout per
each key.

:assemble_hash(true, false)
— default:
false
—

Assemble Hash for results. Hash assembled automatically if
:extended option is true or in case of “get and touch” multimple
keys.

:replica(true, false, :all, :first, Fixnum)
— default:
false
—

Read key from replica node. Options :ttl and :lock are
not compatible with :replica. Value true is a synonym to
:first, which means sequentially iterate over all replicas and
return first successful response, skipping all failures. It is also
possible to query all replicas in parallel using the :all option,
or pass a replica index, starting from zero.

When the method receive hash map, it will behave like it receive list of
keys (keys.keys), but also touch each key setting expiry time to
the corresponding value. But unlike usual get this command always return
hash map {key => value} or {key => [value, flags, cas]}.

that server values stored and transmitted as unsigned numbers, therefore if
you try to store negative number and then increment or decrement it will
cause overflow. (see “Integer overflow” example below)

Increment the value of an existing numeric key

The increment methods allow you to increase a given stored integer value.
These are the incremental equivalent of the decrement operations and work
on the same basis; updating the value of a key if it can be parsed to an
integer. The update operation occurs on the server and is provided at the
protocol level. This simplifies what would otherwise be a two-stage get and
set operation.

#observe_and_wait(*keys, &block) ⇒ Fixnum, Hash<String, Fixnum>

This operation is useful when some confidence needed regarding the state of
the keys. With two parameters :replicated and :persisted
it allows to set up the waiting rule.

Parameters:

keys(String, Symbol, Array, Hash)
—

The list of the keys to observe. Full form is hash with key-cas value
pairs, but there are also shortcuts like just Array of keys or single key.
CAS value needed to when you need to ensure that the storage persisted
exactly the same version of the key you are asking to observe.

options(Hash)
—

The options for operation

Returns:

(Fixnum, Hash<String, Fixnum>)
—

will return CAS value just like mutators or pairs key-cas in case of
multiple keys.

# File 'lib/couchbase/bucket.rb', line 286defobserve_and_wait(*keys,&block)options={:timeout=>default_observe_timeout}options.update(keys.pop)ifkeys.size>1&&keys.last.is_a?(Hash)verify_observe_options(options)ifblock&&!async?raiseArgumentError,"synchronous mode doesn't support callbacks"endifkeys.size==0raiseArgumentError,"at least one key is required"endifkeys.size==1&&keys[0].is_a?(Hash)key_cas=keys[0]elsekey_cas=keys.flatten.reduce({})do|h,kk|h[kk]=nil# set CAS to nil
hendendifasync?do_observe_and_wait(key_cas,options,&block)elseres=do_observe_and_wait(key_cas,options,&block)whileres.nil?unlessasync?ifkeys.size==1&&(keys[0].is_a?(String)||keys[0].is_a?(Symbol))returnres.values.firstelsereturnresendendendend

#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 #cas for workaround.

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
#default_format.

:observe(Hash)
—

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

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 #default_flags.

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

The representation for storing the value in the bucket. For more info see
#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
#observe_and_wait.

c=Couchbase.connectsent=0c.run(:send_threshold=>8192)do# 8Kb
c.set("foo1","x"*100){|r|sent+=1}# 128 bytes buffered, sent is 0 now
c.set("foo2","x"*10000){|r|sent+=1}# 10028 bytes added, sent is 2 now
c.set("foo3","x"*100){|r|sent+=1}end# all commands were executed and sent is 3 now

# File 'lib/couchbase/bucket.rb', line 132defsave_design_doc(data)attrs=casedatawhenStringMultiJson.load(data)whenIOMultiJson.load(data.read)whenHashdataelseraiseArgumentError,"Document should be Hash, String or IO instance"endrv=nilid=attrs.delete('_id').to_sattrs['language']||='javascript'ifid!~/\A_design\//rv=Result.new(:operation=>:http_request,:key=>id,:error=>ArgumentError.new("'_id' key must be set and start with '_design/'."))yieldrvifblock_given?raiserv.errorunlessasync?endreq=make_http_request(id,:body=>MultiJson.dump(attrs),:method=>:put,:extended=>true)req.on_bodydo|res|rv=resval=MultiJson.load(res.value)ifblock_given?ifres.success?&&val['error']res.error=Error::View.new("save_design_doc",val['error'])endyield(res)endendreq.continueunlessasync?rv.success?orraiseres.errorendend

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 #default_flags.

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

The representation for storing the value in the bucket. For more info see
#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
#observe_and_wait.

#stats(arg = nil) {|ret| ... } ⇒ Hash

Request server statistics.

Fetches stats from each node in cluster. Without a key specified the server
will respond with a “default” set of statistical information. In
asynchronous mode each statistic is returned in separate call where the
Result object yielded (#key contains the name of the statistical
item and the #value contains the value, the #node will
indicate the server address). In synchronous mode it returns the hash of
stats keys and node-value pairs as a value.

The touch method allow you to update the expiration time on a
given key. This can be useful for situations where you want to prevent an
item from expiring without resetting the associated value. For example, for
a session database you might want to keep the session alive in the database
each time the user accesses a web page without explicitly updating the
session value, keeping the user's session active and available.

Overloads:

#touch(key, options = {}) {|ret| ... } ⇒ true, false

Returns true if the operation was successful and false
otherwise.

Examples:

Touch value using default_ttl

c.touch("foo")

Touch value using custom TTL (10 seconds)

c.touch("foo",:ttl=>10)

Parameters:

key(String, Symbol)
—

Key used to reference the value.

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

:quiet(true, false)
— default:
self.quiet
—

If set to true, the operation won't raise error for missing
key, it will return nil.