Class: Couchbase::Bucket

Inherits:
Object
  • Object
show all
Defined in:
ext/couchbase_ext/couchbase_ext.c,
lib/couchbase/bucket.rb,
ext/couchbase_ext/couchbase_ext.c

Overview

This class in charge of all stuff connected to communication with Couchbase.

Since:

Defined Under Namespace

Classes: CouchRequest

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

0x00
FMT_MARSHAL =

Marshal format. The format which supports transparent serialization of ruby objects with standard Marshal.dump and Marhal.load methods.

0x01
FMT_PLAIN =

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: http://dustin.github.com/2011/02/17/memcached-set.html

0x02

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Bucket) initialize(url, options = {}) - (Bucket) initialize(options = {})

Initialize new Bucket.

Examples:

Initialize connection using default options

Couchbase.new

Select custom bucket

Couchbase.new(:bucket => 'foo')
Couchbase.new('http://localhost:8091/pools/default/buckets/foo')

Connect to protected bucket

Couchbase.new(:bucket => 'protected', :username => 'protected', :password => 'secret')
Couchbase.new('http://localhost:8091/pools/default/buckets/protected',
              :username => 'protected', :password => 'secret')

Use list of nodes, in case some nodes might be dead

Couchbase.new(:node_list => ['example.com:8091', 'example.org:8091', 'example.net'])

Overloads:

  • - (Bucket) initialize(url, options = {})

    Initialize bucket using URI of the cluster and options. It is possible to override some parts of URI using the options keys (e.g. :host or :port)

    Parameters:

    • url (String)

      The full URL of management API of the cluster.

    • options (Hash)

      The options for connection. See options definition below.

  • - (Bucket) initialize(options = {})

    Initialize bucket using options only.

    Parameters:

    • options (Hash)

      The options for operation for connection

    Options Hash (options):

    • :node_list (Array) — default: nil

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

Raises:

Since:

  • 1.0.0



1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
# File 'ext/couchbase_ext/couchbase_ext.c', line 1725

static VALUE
cb_bucket_init(int argc, VALUE *argv, VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);

    bucket->self = self;
    bucket->exception = Qnil;
    bucket->hostname = strdup("localhost");
    bucket->port = 8091;
    bucket->pool = strdup("default");
    bucket->bucket = strdup("default");
    bucket->async = 0;
    bucket->quiet = 0;
    bucket->default_ttl = 0;
    bucket->default_flags = 0;
    bucket->default_format = sym_document;
    bucket->default_observe_timeout = 2500000;
    bucket->on_error_proc = Qnil;
    bucket->timeout = 0;
    bucket->environment = sym_production;
    bucket->key_prefix = NULL;
    bucket->key_prefix_val = Qnil;
    bucket->node_list = NULL;
    bucket->object_space = rb_hash_new();

    do_scan_connection_options(bucket, argc, argv);
    do_connect(bucket);

    return self;
}

Instance Attribute Details

- (String) authority (readonly)

Host with port

Returns:

  • (String)

    host with port

Since:

  • 1.0.0



2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
# File 'ext/couchbase_ext/couchbase_ext.c', line 2064

static VALUE
cb_bucket_authority_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    size_t len;

    (void)cb_bucket_hostname_get(self);
    (void)cb_bucket_port_get(self);
    len = strlen(bucket->hostname) + 10;
    bucket->authority = xcalloc(len, sizeof(char));
    if (bucket->authority == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for Bucket");
    }
    snprintf(bucket->authority, len, "%s:%u", bucket->hostname, bucket->port);
    return rb_str_new2(bucket->authority);
}

- (String) bucket (readonly) Also known as: name

The bucket name

Returns:

  • (String)

    the bucket name

Since:

  • 1.0.0



2087
2088
2089
2090
2091
2092
# File 'ext/couchbase_ext/couchbase_ext.c', line 2087

static VALUE
cb_bucket_bucket_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return rb_str_new2(bucket->bucket);
}

- (Fixnum) default_flags

Note:

Amending format bit will also change #default_format value

Default flags for new values.

The library reserves last two lower bits to store the format of the value. The can be masked via FMT_MASK constant.

Examples:

Selecting format bits

connection.default_flags & Couchbase::Bucket::FMT_MASK

Set user defined bits

connection.default_flags |= 0x6660

Returns:

  • (Fixnum)

    the effective flags

Since:

  • 1.0.0



1908
1909
1910
1911
1912
1913
# File 'ext/couchbase_ext/couchbase_ext.c', line 1908

static VALUE
cb_bucket_default_flags_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return ULONG2NUM(bucket->default_flags);
}

- (Symbol) default_format

Note:

Amending default_format will also change #default_flags value

Default format for new values.

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: http://dustin.github.com/2011/02/17/memcached-set.html
  • :marshal format if you’d like to transparently serialize your ruby object with standard Marshal.dump and Marhal.load methods.

Examples:

Selecting plain format using symbol

connection.format = :document

Selecting plain format using Fixnum constant

connection.format = Couchbase::Bucket::FMT_PLAIN

Returns:

  • (Symbol)

    the effective format

See Also:

Since:

  • 1.0.0



1925
1926
1927
1928
1929
1930
# File 'ext/couchbase_ext/couchbase_ext.c', line 1925

static VALUE
cb_bucket_default_format_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return bucket->default_format;
}

- (Object) default_observe_timeout

Get default timeout value for #observe_and_wait operation in microseconds

Since:

  • 1.2.0.dp6



2176
2177
2178
2179
2180
2181
# File 'ext/couchbase_ext/couchbase_ext.c', line 2176

static VALUE
cb_bucket_default_observe_timeout_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return INT2FIX(bucket->default_observe_timeout);
}

- (Symbol) environment (readonly)

The environment (+:development+ or :production)

Returns:

  • (Symbol)

    the environment (+:development+ or :production)

See Also:

Since:

  • 1.2.0



2142
2143
2144
2145
2146
2147
# File 'ext/couchbase_ext/couchbase_ext.c', line 2142

static VALUE
cb_bucket_environment_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return bucket->environment;
}

- (String) hostname (readonly)

The host name of the management interface (default: "localhost")

Returns:

  • (String)

    the host name of the management interface (default: "localhost")

Since:

  • 1.0.0



2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
# File 'ext/couchbase_ext/couchbase_ext.c', line 2028

static VALUE
cb_bucket_hostname_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    if (bucket->handle) {
        xfree(bucket->hostname);
        bucket->hostname = strdup(libcouchbase_get_host(bucket->handle));
        if (bucket->hostname == NULL) {
            rb_raise(eClientNoMemoryError, "failed to allocate memory for Bucket");
        }
    }
    return rb_str_new2(bucket->hostname);
}

- (String) key_prefix

The library will prepend key_prefix to each key to provide simple namespacing.

Returns:

  • (String)

    The library will prepend key_prefix to each key to provide simple namespacing.

Since:

  • 1.2.0.dp5



2004
2005
2006
2007
2008
2009
# File 'ext/couchbase_ext/couchbase_ext.c', line 2004

static VALUE
cb_bucket_key_prefix_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return bucket->key_prefix_val;
}

- (Object) num_replicas (readonly)

The numbers of the replicas for each node in the cluster

Since:

  • 1.2.0.dp6



2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
# File 'ext/couchbase_ext/couchbase_ext.c', line 2156

static VALUE
cb_bucket_num_replicas_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    int32_t nr = libcouchbase_get_num_replicas(bucket->handle);
    if (nr < 0) {
        return Qnil;
    } else {
        return INT2FIX(nr);
    }
}

- (Proc) on_error {|op, key, exc| ... }

Error callback for asynchronous mode.

This callback is using to deliver exceptions in asynchronous mode.

Examples:

Using lambda syntax

connection = Couchbase.new(:async => true)
connection.on_error = lambda {|op, key, exc| ... }
connection.run do |conn|
  conn.set("foo", "bar")
end

Using block syntax

connection = Couchbase.new(:async => true)
connection.on_error {|op, key, exc| ... }
...

Yield Parameters:

  • op (Symbol)

    The operation caused the error

  • key (String)

    The key which cause the error or nil

  • exc (Exception)

    The exception instance

Returns:

  • (Proc)

    the effective callback

Since:

  • 1.0.0



1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
# File 'ext/couchbase_ext/couchbase_ext.c', line 1972

static VALUE
cb_bucket_on_error_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);

    if (rb_block_given_p()) {
        return cb_bucket_on_error_set(self, rb_block_proc());
    } else {
        return bucket->on_error_proc;
    }
}

- (String) password (readonly)

The password for protected buckets

Returns:

  • (String)

    the password for protected buckets

Since:

  • 1.0.0



2127
2128
2129
2130
2131
2132
# File 'ext/couchbase_ext/couchbase_ext.c', line 2127

static VALUE
cb_bucket_password_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return rb_str_new2(bucket->password);
}

- (String) pool (readonly)

The pool name (usually "default")

Returns:

  • (String)

    the pool name (usually "default")

Since:

  • 1.0.0



2100
2101
2102
2103
2104
2105
# File 'ext/couchbase_ext/couchbase_ext.c', line 2100

static VALUE
cb_bucket_pool_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return rb_str_new2(bucket->pool);
}

- (Fixnum) port (readonly)

The port number of the management interface (default: 8091)

Returns:

  • (Fixnum)

    the port number of the management interface (default: 8091)

Since:

  • 1.0.0



2048
2049
2050
2051
2052
2053
2054
2055
2056
# File 'ext/couchbase_ext/couchbase_ext.c', line 2048

static VALUE
cb_bucket_port_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    if (bucket->handle) {
        bucket->port = atoi(libcouchbase_get_port(bucket->handle));
    }
    return UINT2NUM(bucket->port);
}

- (true, false) quiet Also known as: quiet?

Flag specifying behaviour for operations on missing keys

If it is true, the operations will silently return nil or false instead of raising Error::NotFound.

Examples:

Hiding cache miss (considering "miss" key is not stored)

connection.quiet = true
connection.get("miss")     #=> nil

Raising errors on miss (considering "miss" key is not stored)

connection.quiet = false
connection.get("miss")     #=> will raise Couchbase::Error::NotFound

Returns:

  • (true, false)

Since:

  • 1.0.0



1890
1891
1892
1893
1894
1895
# File 'ext/couchbase_ext/couchbase_ext.c', line 1890

static VALUE
cb_bucket_quiet_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return bucket->quiet ? Qtrue : Qfalse;
}

- (Fixnum) timeout

The timeout for the operations in microseconds. The client will raise Error::Timeout exception for all commands which weren’t completed in given timeslot.

Returns:

  • (Fixnum)

    The timeout for the operations in microseconds. The client will raise Error::Timeout exception for all commands which weren’t completed in given timeslot.

Since:

  • 1.1.0



1984
1985
1986
1987
1988
1989
# File 'ext/couchbase_ext/couchbase_ext.c', line 1984

static VALUE
cb_bucket_timeout_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return ULONG2NUM(bucket->timeout);
}

- (String) url (readonly)

The address of the cluster management interface

Returns:

  • (String)

    the address of the cluster management interface

Since:

  • 1.0.0



2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
# File 'ext/couchbase_ext/couchbase_ext.c', line 2205

static VALUE
cb_bucket_url_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    VALUE str;

    (void)cb_bucket_authority_get(self);
    str = rb_str_buf_new2("http://");
    rb_str_buf_cat2(str, bucket->authority);
    rb_str_buf_cat2(str, "/pools/");
    rb_str_buf_cat2(str, bucket->pool);
    rb_str_buf_cat2(str, "/buckets/");
    rb_str_buf_cat2(str, bucket->bucket);
    rb_str_buf_cat2(str, "/");
    return str;
}

- (String) username (readonly)

The username for protected buckets (usually matches the bucket name)

Returns:

  • (String)

    the username for protected buckets (usually matches the bucket name)

Since:

  • 1.0.0



2114
2115
2116
2117
2118
2119
# File 'ext/couchbase_ext/couchbase_ext.c', line 2114

static VALUE
cb_bucket_username_get(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return rb_str_new2(bucket->username);
}

Instance Method Details

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

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

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)

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

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



3777
3778
3779
3780
3781
# File 'ext/couchbase_ext/couchbase_ext.c', line 3777

static VALUE
cb_bucket_add(int argc, VALUE *argv, VALUE self)
{
    return cb_bucket_store(LIBCOUCHBASE_ADD, argc, argv, self);
}

- (Couchbase::View) all_docs(params = {})

Fetch all documents from the bucket.

Parameters:

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

    Params for Couchbase /_all_docs query

Returns:

Since:

  • 1.2.0



120
121
122
# File 'lib/couchbase/bucket.rb', line 120

def all_docs(params = {})
  View.new(self, "_all_docs", params)
end

- (Fixnum) append(key, value, options = {})

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.

Append this object to the existing object

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)

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

  • :observe (Hash)

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

Returns:

  • (Fixnum)

    The CAS value of the object.

Raises:

Since:

  • 1.0.0



3905
3906
3907
3908
3909
# File 'ext/couchbase_ext/couchbase_ext.c', line 3905

static VALUE
cb_bucket_append(int argc, VALUE *argv, VALUE self)
{
    return cb_bucket_store(LIBCOUCHBASE_APPEND, argc, argv, self);
}

- (true, ...) async?

Check whether the connection asynchronous.

By default all operations are synchronous and block waiting for results, but you can make them asynchronous and run event loop explicitly. (see #run)

Examples:

Return value of #get operation depending on async flag

connection = Connection.new
connection.async?      #=> false

connection.run do |conn|
  conn.async?          #=> true
end

Returns:

  • (true, false)

    true if the connection if asynchronous

  • (Boolean)

See Also:

Since:

  • 1.0.0



1883
1884
1885
1886
1887
1888
# File 'ext/couchbase_ext/couchbase_ext.c', line 1883

static VALUE
cb_bucket_async_p(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return bucket->async ? Qtrue : Qfalse;
}

- (Fixnum) cas(key, options = {}) {|value| ... } Also known as: compare_and_swap

Compare and swap value.

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:

In asynchronous mode it will yield result twice, first for #get with Result#operation equal to :get and second time for #set with Result#operation equal to :set.

Examples:

Implement append to JSON encoded value

c.default_format = :document
c.set("foo", {"bar" => 1})
c.cas("foo") do |val|
  val["baz"] = 2
  val
end
c.get("foo")      #=> {"bar" => 1, "baz" => 2}

Append JSON encoded value asynchronously

c.default_format = :document
c.set("foo", {"bar" => 1})
c.run do
  c.cas("foo") do |val|
    case val.operation
    when :get
      val["baz"] = 2
      val
    when :set
      # verify all is ok
      puts "error: #{ret.error.inspect}" unless ret.success?
    end
  end
end
c.get("foo")      #=> {"bar" => 1, "baz" => 2}

Parameters:

  • key (String, Symbol)
  • options (Hash) (defaults to: {})

    the options for "swap" part

Options Hash (options):

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

    the time to live of this key

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

    format of the value

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

    flags for this key

Yield Parameters:

  • value (Object, Result)

    old value in synchronous mode and Result object in asynchronous mode.

Yield Returns:

  • (Object)

    new value.

Returns:

  • (Fixnum)

    the CAS of new value

Raises:

  • (Couchbase::Error::KeyExists)

    if the key was updated before the the code in block has been completed (the CAS value has been changed).

  • (ArgumentError)

    if the block is missing for async mode

See Also:

Since:

  • 1.0.0



82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/couchbase/bucket.rb', line 82

def cas(key, options = {})
  if async?
    block = Proc.new
    get(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)
    end
  else
    val, flags, ver = get(key, :extended => true)
    val = yield(val) # get new value from caller
    set(key, val, options.merge(:cas => ver, :flags => flags))
  end
end

- (true, ...) connected?

Check whether the instance connected to the cluster.

Returns:

  • (true, false)

    true if the instance connected to the cluster

  • (Boolean)

Since:

  • 1.1.0



1855
1856
1857
1858
1859
1860
# File 'ext/couchbase_ext/couchbase_ext.c', line 1855

static VALUE
cb_bucket_connected_p(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    return bucket->handle ? Qtrue : Qfalse;
}

- (Object) create_periodic_timer(interval, &block)



188
189
190
# File 'lib/couchbase/bucket.rb', line 188

def create_periodic_timer(interval, &block)
  Timer.new(self, interval, :periodic => true, &block)
end

- (Object) create_timer(interval, &block)



184
185
186
# File 'lib/couchbase/bucket.rb', line 184

def create_timer(interval, &block)
  Timer.new(self, interval, &block)
end

- (Fixnum) decr(key, delta = 1, options = {}) {|ret| ... } Also known as: decrement

Note:

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.

The actual value of the key.

Examples:

Decrement key by one

c.decr("foo")

Decrement key by 50

c.decr("foo", 50)

Decrement key by one OR initialize with zero

c.decr("foo", :create => true)   #=> will return old-1 or 0

Decrement key by one OR initialize with three

c.decr("foo", 50, :initial => 3) #=> will return old-50 or 3

Decrement key and get its CAS value

val, cas = c.decr("foo", :extended => true)

Decrementing zero

c.set("foo", 0)
c.decrement("foo", 100500)   #=> 0

Decrementing negative value

c.set("foo", -100)
c.decrement("foo", 100500)   #=> 0

Asynchronous invocation

c.run do
  c.decr("foo") do |ret|
    ret.operation   #=> :decrement
    ret.success?    #=> true
    ret.key         #=> "foo"
    ret.value
    ret.cas
  end
end

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • delta (Fixnum)

    Integer (up to 64 bits) value to decrement

  • options (Hash)

    Options for operation.

Options Hash (options):

  • :create (true, false) — default: false

    If set to true, it will initialize the key with zero value and zero flags (use :initial option to set another initial value). Note: it won’t decrement the missing value.

  • :initial (Fixnum) — default: 0

    Integer (up to 64 bits) value for missing key initialization. This option imply :create option is true.

  • :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). This option ignored for existent keys.

  • :extended (true, false) — default: false

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

Yield Parameters:

  • ret (Result)

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

Returns:

  • (Fixnum)

    the actual value of the key.

Raises:

Since:

  • 1.0.0



2750
2751
2752
2753
2754
# File 'ext/couchbase_ext/couchbase_ext.c', line 2750

static VALUE
cb_bucket_decr(int argc, VALUE *argv, VALUE self)
{
    return cb_bucket_arithmetic(-1, argc, argv, self);
}

- (Object) delete(key, options = {})

Delete the specified key

Examples:

Delete the key in quiet mode (default)

c.set("foo", "bar")
c.delete("foo")        #=> true
c.delete("foo")        #=> false

Delete the key verbosely

c.set("foo", "bar")
c.delete("foo", :quiet => false)   #=> true
c.delete("foo", :quiet => true)    #=> nil (default behaviour)
c.delete("foo", :quiet => false)   #=> will raise Couchbase::Error::NotFound

Delete the key with version check

ver = c.set("foo", "bar")          #=> 5992859822302167040
c.delete("foo", :cas => 123456)    #=> will raise Couchbase::Error::KeyExists
c.delete("foo", :cas => ver)       #=> true

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • options (Hash)

    Options for operation.

Options Hash (options):

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

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

Raises:

Since:

  • 1.0.0



2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
# File 'ext/couchbase_ext/couchbase_ext.c', line 2304

static VALUE
cb_bucket_delete(int argc, VALUE *argv, VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    struct context_st *ctx;
    VALUE k, c, rv, proc, exc, opts;
    char *key;
    size_t nkey;
    libcouchbase_cas_t cas = 0;
    libcouchbase_error_t err;

    if (bucket->handle == NULL) {
        rb_raise(eConnectError, "closed connection");
    }
    rb_scan_args(argc, argv, "11&", &k, &opts, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    k = unify_key(bucket, k, 1);
    key = RSTRING_PTR(k);
    nkey = RSTRING_LEN(k);
    ctx = xcalloc(1, sizeof(struct context_st));
    ctx->quiet = bucket->quiet;
    if (ctx == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for context");
    }
    if (opts != Qnil) {
        if (TYPE(opts) == T_BIGNUM || TYPE(opts) == T_FIXNUM) {
            cas = NUM2ULL(opts);
        } else {
            Check_Type(opts, T_HASH);
            if ((c = rb_hash_aref(opts, sym_cas)) != Qnil) {
                cas = NUM2ULL(c);
            }
            if (RTEST(rb_funcall(opts, id_has_key_p, 1, sym_quiet))) {
                ctx->quiet = RTEST(rb_hash_aref(opts, sym_quiet));
            }
        }
    }
    ctx->proc = proc;
    cb_gc_protect(bucket, ctx->proc);
    rv = rb_ary_new();
    ctx->rv = &rv;
    ctx->bucket = bucket;
    ctx->exception = Qnil;
    ctx->nqueries = 1;
    err = libcouchbase_remove(bucket->handle, (const void *)ctx,
            (const void *)key, nkey, cas);
    exc = cb_check_error(err, "failed to schedule delete request", Qnil);
    if (exc != Qnil) {
        xfree(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += HEADER_SIZE + nkey;
    if (bucket->async) {
        maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            libcouchbase_wait(bucket->handle);
        }
        exc = ctx->exception;
        xfree(ctx);
        if (exc != Qnil) {
            cb_gc_unprotect(bucket, exc);
            rb_exc_raise(exc);
        }
        return rv;
    }
}

- (true, false) delete_design_doc(id, rev = nil)

Delete design doc with given id and revision.

Parameters:

  • id (String)

    Design document id. It might have ‘_design/’ prefix.

  • rev (String) (defaults to: nil)

    Document revision. It uses latest revision if rev parameter is nil.

Returns:

  • (true, false)

Since:

  • 1.2.0



171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/couchbase/bucket.rb', line 171

def delete_design_doc(id, rev = nil)
  ddoc = design_docs[id.sub(/^_design\//, '')]
  return nil unless ddoc
  path = Utils.build_query(ddoc['_id'], :rev => rev || ddoc['_rev'])
  req = make_couch_request(path, :method => :delete)
  res = MultiJson.load(req.perform)
  if res['ok']
    true
  else
    raise "Failed to save design document: #{res['error']}"
  end
end

- (Hash) design_docs

Fetch design docs stored in current bucket

Returns:

  • (Hash)

Since:

  • 1.2.0



102
103
104
105
106
107
108
109
110
111
# File 'lib/couchbase/bucket.rb', line 102

def design_docs
  docs = all_docs(:startkey => "_design/", :endkey => "_design0", :include_docs => true)
  docmap = {}
  docs.each do |doc|
    key = doc.id.sub(/^_design\//, '')
    next if self.environment == :production && key =~ /dev_/
    docmap[key] = doc
  end
  docmap
end

- (true) disconnect

Close the connection to the cluster

Returns:

  • (true)

Raises:

Since:

  • 1.1.0



3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
# File 'ext/couchbase_ext/couchbase_ext.c', line 3993

static VALUE
cb_bucket_disconnect(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);

    if (bucket->handle) {
        libcouchbase_destroy(bucket->handle);
        bucket->handle = NULL;
        bucket->io = NULL;
        return Qtrue;
    } else {
        rb_raise(eConnectError, "closed connection");
    }
}

- (true, false) flush {|ret| ... }

Deletes all values from a server

true on success

Examples:

Simple flush the bucket

c.flush    #=> true

Asynchronous flush

c.run do
  c.flush do |ret|
    ret.operation   #=> :flush
    ret.success?    #=> true
    ret.node        #=> "localhost:11211"
  end
end

Yield Parameters:

  • ret (Result)

    the object with error, node and operation attributes.

Returns:

  • (true, false)

    true on success

Raises:

Since:

  • 1.0.0



3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
# File 'ext/couchbase_ext/couchbase_ext.c', line 3261

static VALUE
cb_bucket_flush(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    struct context_st *ctx;
    VALUE rv, exc;
    libcouchbase_error_t err;

    if (bucket->handle == NULL) {
        rb_raise(eConnectError, "closed connection");
    }
    if (!bucket->async && rb_block_given_p()) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    ctx = xcalloc(1, sizeof(struct context_st));
    if (ctx == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for context");
    }
    rv = Qtrue; /* optimistic by default */
    ctx->rv = &rv;
    ctx->bucket = bucket;
    ctx->exception = Qnil;
    if (rb_block_given_p()) {
        ctx->proc = rb_block_proc();
    } else {
        ctx->proc = Qnil;
    }
    ctx->nqueries = 1;
    cb_gc_protect(bucket, ctx->proc);
    err = libcouchbase_flush(bucket->handle, (const void *)ctx);
    exc = cb_check_error(err, "failed to schedule flush request", Qnil);
    if (exc != Qnil) {
        xfree(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += HEADER_SIZE;
    if (bucket->async) {
        maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            libcouchbase_wait(bucket->handle);
        }
        exc = ctx->exception;
        xfree(ctx);
        if (exc != Qnil) {
            cb_gc_unprotect(bucket, exc);
            rb_exc_raise(exc);
        }
        return rv;
    }
}

- (Object, ...) get(*keys, options = {}) {|ret| ... } - (Hash) get(keys, options = {}) Also known as: []

Obtain an object stored in Couchbase by given key.

Overloads:

  • - (Object, ...) get(*keys, options = {}) {|ret| ... }

    The value(s) (or tuples in extended mode) assiciated with the key.

    Examples:

    Get single value in quite mode (the default)

    c.get("foo")     #=> the associated value or nil
    

    Use alternative hash-like syntax

    c["foo"]         #=> the associated value or nil
    

    Get single value in verbose mode

    c.get("missing-foo", :quiet => false)  #=> raises Couchbase::NotFound
    c.get("missing-foo", :quiet => true)   #=> returns nil
    

    Get and touch single value. The key won’t be accessible after 10 seconds

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

    Extended get

    val, flags, cas = c.get("foo", :extended => true)
    

    Get multiple keys

    c.get("foo", "bar", "baz")   #=> [val1, val2, val3]
    

    Get multiple keys with assembing result into the Hash

    c.get("foo", "bar", "baz", :assemble_hash => true)
    #=> {"foo" => val1, "bar" => val2, "baz" => val3}
    

    Extended get multiple keys

    c.get("foo", "bar", :extended => true)
    #=> {"foo" => [val1, flags1, cas1], "bar" => [val2, flags2, cas2]}
    

    Asynchronous get

    c.run do
      c.get("foo", "bar", "baz") do |res|
        ret.operation   #=> :get
        ret.success?    #=> true
        ret.key         #=> "foo", "bar" or "baz" in separate calls
        ret.value
        ret.flags
        ret.cas
      end
    end
    

    Get and lock key using default timeout

    c.get("foo", :lock => true)
    

    Determine lock timeout parameters

    c.stats.values_at("ep_getl_default_timeout", "ep_getl_max_timeout")
    #=> [{"127.0.0.1:11210"=>"15"}, {"127.0.0.1:11210"=>"30"}]
    

    Get and lock key using custom timeout

    c.get("foo", :lock => 3)
    

    Get and lock multiple keys using custom timeout

    c.get("foo", "bar", :lock => 3)
    

    Parameters:

    • keys (String, Symbol, Array)

      One or several keys to fetch

    • options (Hash)

      Options for operation.

    Options Hash (options):

    • :extended (true, false) — default: false

      If set to true, the operation will return tuple +[value, flags, cas]+, otherwise (by default) it returns just 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) — default: false

      Read key from replica node. Options :ttl and :lock are not compatible with :replica.

    Yield Parameters:

    • ret (Result)

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

    Returns:

    • (Object, Array, Hash)

      the value(s) (or tuples in extended mode) assiciated with the key.

    Raises:

  • - (Hash) get(keys, options = {})

    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 =&gt; value} or {key =&gt; [value, flags, cas]}.

    Examples:

    Get and touch multiple keys

    c.get("foo" => 10, "bar" => 20)   #=> {"foo" => val1, "bar" => val2}
    

    Extended get and touch multiple keys

    c.get({"foo" => 10, "bar" => 20}, :extended => true)
    #=> {"foo" => [val1, flags1, cas1], "bar" => [val2, flags2, cas2]}
    

    Get and lock multiple keys for chosen period in seconds

    c.get("foo" => 10, "bar" => 20, :lock => true)
    #=> {"foo" => val1, "bar" => val2}
    

    Parameters:

    • keys (Hash)

      Map key-ttl

    • options (Hash)

      Options for operation. (see options definition above)

    Returns:

    • (Hash)

      the values (or tuples in extended mode) assiciated with the keys.

See Also:

Since:

  • 1.0.0



2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
# File 'ext/couchbase_ext/couchbase_ext.c', line 2989

static VALUE
cb_bucket_get(int argc, VALUE *argv, VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    struct context_st *ctx;
    VALUE args, rv, proc, exc, keys;
    size_t nn, ii, ll = 0;
    libcouchbase_error_t err = LIBCOUCHBASE_SUCCESS;
    struct key_traits_st *traits;
    int extended, mgat, is_array, assemble_hash;

    if (bucket->handle == NULL) {
        rb_raise(eConnectError, "closed connection");
    }
    rb_scan_args(argc, argv, "0*&", &args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    traits = xcalloc(1, sizeof(struct key_traits_st));
    traits->bucket = bucket;
    nn = cb_args_scan_keys(RARRAY_LEN(args), args, traits);
    ctx = xcalloc(1, sizeof(struct context_st));
    if (ctx == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for context");
    }
    mgat = traits->mgat;
    assemble_hash = traits->assemble_hash;
    keys = traits->keys_ary;
    is_array = traits->is_array;
    ctx->proc = proc;
    cb_gc_protect(bucket, ctx->proc);
    ctx->bucket = bucket;
    ctx->extended = traits->extended;
    ctx->quiet = traits->quiet;
    ctx->force_format = traits->force_format;
    rv = rb_hash_new();
    ctx->rv = &rv;
    ctx->exception = Qnil;
    ctx->nqueries = traits->nkeys;
    if (traits->lock) {
        for (ii = 0; ii < traits->nkeys; ++ii) {
            err = libcouchbase_getl(bucket->handle, (const void *)ctx,
                    (const void *)traits->keys[ii], traits->lens[ii],
                    traits->ttls + ii);
            if (err != LIBCOUCHBASE_SUCCESS) {
                break;
            }
        }
    } else if (traits->replica) {
        err = libcouchbase_get_replica(bucket->handle, (const void *)ctx,
                traits->nkeys, (const void * const *)traits->keys,
                traits->lens);
    } else {
        err = libcouchbase_mget(bucket->handle, (const void *)ctx,
                traits->nkeys, (const void * const *)traits->keys,
                traits->lens, (traits->explicit_ttl) ? traits->ttls : NULL);
    }
    if (err == LIBCOUCHBASE_SUCCESS) {
        for (ii = 0; ii < traits->nkeys; ++ii) {
            ll += traits->lens[ii];
        }
    }
    xfree(traits->keys);
    xfree(traits->lens);
    xfree(traits->ttls);
    xfree(traits);
    exc = cb_check_error(err, "failed to schedule get request", Qnil);
    if (exc != Qnil) {
        xfree(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += HEADER_SIZE + 4 + ll;
    if (bucket->async) {
        maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            libcouchbase_wait(bucket->handle);
        }
        exc = ctx->exception;
        extended = ctx->extended;
        xfree(ctx);
        if (exc != Qnil) {
            cb_gc_unprotect(bucket, exc);
            rb_exc_raise(exc);
        }
        if (bucket->exception != Qnil) {
            rb_exc_raise(bucket->exception);
        }
        if (assemble_hash || mgat || (extended && (nn > 1 || is_array))) {
            return rv;  /* return as a hash {key => [value, flags, cas], ...} */
        }
        if (nn > 1 || is_array) {
            VALUE *keys_ptr, ret;
            ret = rb_ary_new();
            keys_ptr = RARRAY_PTR(keys);
            for (ii = 0; ii < nn; ii++) {
                rb_ary_push(ret, rb_hash_aref(rv, keys_ptr[ii]));
            }
            return ret;  /* return as an array [value1, value2, ...] */
        } else {
            VALUE vv = Qnil;
            rb_hash_foreach(rv, cb_first_value_i, (VALUE)&vv);
            return vv;
        }
    }
}

- (Fixnum) incr(key, delta = 1, options = {}) {|ret| ... } Also known as: increment

Note:

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.

The actual value of the key.

Examples:

Increment key by one

c.incr("foo")

Increment key by 50

c.incr("foo", 50)

Increment key by one OR initialize with zero

c.incr("foo", :create => true)   #=> will return old+1 or 0

Increment key by one OR initialize with three

c.incr("foo", 50, :initial => 3) #=> will return old+50 or 3

Increment key and get its CAS value

val, cas = c.incr("foo", :extended => true)

Integer overflow

c.set("foo", -100)
c.get("foo")           #=> -100
c.incr("foo")          #=> 18446744073709551517

Asynchronous invocation

c.run do
  c.incr("foo") do |ret|
    ret.operation   #=> :increment
    ret.success?    #=> true
    ret.key         #=> "foo"
    ret.value
    ret.cas
  end
end

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • delta (Fixnum)

    Integer (up to 64 bits) value to increment

  • options (Hash)

    Options for operation.

Options Hash (options):

  • :create (true, false) — default: false

    If set to true, it will initialize the key with zero value and zero flags (use :initial option to set another initial value). Note: it won’t increment the missing value.

  • :initial (Fixnum) — default: 0

    Integer (up to 64 bits) value for missing key initialization. This option imply :create option is true.

  • :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). This option ignored for existent keys.

  • :extended (true, false) — default: false

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

Yield Parameters:

  • ret (Result)

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

Returns:

  • (Fixnum)

    the actual value of the key.

Raises:

Since:

  • 1.0.0



2659
2660
2661
2662
2663
# File 'ext/couchbase_ext/couchbase_ext.c', line 2659

static VALUE
cb_bucket_incr(int argc, VALUE *argv, VALUE self)
{
    return cb_bucket_arithmetic(+1, argc, argv, self);
}

- (Couchbase::Bucket) initialize_copy

Initialize copy

Initializes copy of the object, used by #dup

Parameters:

Returns:



1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
# File 'ext/couchbase_ext/couchbase_ext.c', line 1765

static VALUE
cb_bucket_init_copy(VALUE copy, VALUE orig)
{
    struct bucket_st *copy_b;
    struct bucket_st *orig_b;

    if (copy == orig)
        return copy;

    if (TYPE(orig) != T_DATA || TYPE(copy) != T_DATA ||
            RDATA(orig)->dfree != (RUBY_DATA_FUNC)cb_bucket_free) {
        rb_raise(rb_eTypeError, "wrong argument type");
    }

    copy_b = DATA_PTR(copy);
    orig_b = DATA_PTR(orig);

    copy_b->self = copy_b->self;
    copy_b->port = orig_b->port;
    copy_b->authority = strdup(orig_b->authority);
    copy_b->hostname = strdup(orig_b->hostname);
    copy_b->pool = strdup(orig_b->pool);
    copy_b->bucket = strdup(orig_b->bucket);
    if (orig_b->username) {
        copy_b->username = strdup(orig_b->username);
    }
    if (orig_b->password) {
        copy_b->password = strdup(orig_b->password);
    }
    if (orig_b->key_prefix) {
        copy_b->key_prefix = strdup(orig_b->key_prefix);
    }
    copy_b->async = orig_b->async;
    copy_b->quiet = orig_b->quiet;
    copy_b->default_format = orig_b->default_format;
    copy_b->default_flags = orig_b->default_flags;
    copy_b->default_ttl = orig_b->default_ttl;
    copy_b->environment = orig_b->environment;
    copy_b->timeout = orig_b->timeout;
    copy_b->exception = Qnil;
    if (orig_b->on_error_proc != Qnil) {
        copy_b->on_error_proc = rb_funcall(orig_b->on_error_proc, id_dup, 0);
    }
    if (orig_b->key_prefix_val != Qnil) {
        copy_b->key_prefix_val = rb_funcall(orig_b->key_prefix_val, id_dup, 0);
    }

    do_connect(copy_b);

    return copy;
}

- (String) inspect

Returns a string containing a human-readable representation of the Couchbase::Bucket.

Returns:

  • (String)

Since:

  • 1.0.0



2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
# File 'ext/couchbase_ext/couchbase_ext.c', line 2230

static VALUE
cb_bucket_inspect(VALUE self)
{
    VALUE str;
    struct bucket_st *bucket = DATA_PTR(self);
    char buf[200];

    str = rb_str_buf_new2("#<");
    rb_str_buf_cat2(str, rb_obj_classname(self));
    snprintf(buf, 25, ":%p \"", (void *)self);
    (void)cb_bucket_authority_get(self);
    rb_str_buf_cat2(str, buf);
    rb_str_buf_cat2(str, "http://");
    rb_str_buf_cat2(str, bucket->authority);
    rb_str_buf_cat2(str, "/pools/");
    rb_str_buf_cat2(str, bucket->pool);
    rb_str_buf_cat2(str, "/buckets/");
    rb_str_buf_cat2(str, bucket->bucket);
    rb_str_buf_cat2(str, "/");
    snprintf(buf, 150, "\" default_format=:%s, default_flags=0x%x, quiet=%s, connected=%s, timeout=%u",
            rb_id2name(SYM2ID(bucket->default_format)),
            bucket->default_flags,
            bucket->quiet ? "true" : "false",
            bucket->handle ? "true" : "false",
            bucket->timeout);
    rb_str_buf_cat2(str, buf);
    if (bucket->key_prefix) {
        rb_str_buf_cat2(str, ", key_prefix=");
        rb_str_append(str, rb_inspect(bucket->key_prefix_val));
    }
    rb_str_buf_cat2(str, ">");

    return str;
}

- (Couchbase::Bucket::CouchRequest) make_couch_request {|res| ... }

Parameters:

  • path (String)
  • options (Hash)

Yield Parameters:

  • res (String, Couchbase::Result)

    the response chunk if the :extended option is false and result object otherwise

Returns:

Since:

  • 1.2.0



4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
# File 'ext/couchbase_ext/couchbase_ext.c', line 4559

static VALUE
cb_bucket_make_couch_request(int argc, VALUE *argv, VALUE self)
{
    VALUE args[4]; /* bucket, path, options, block */

    args[0] = self;
    rb_scan_args(argc, argv, "11&", &args[1], &args[2], &args[3]);

    return rb_class_new_instance(4, args, cCouchRequest);
}

- (Hash<String, Array<Result>>, Array<Result>) observe(*keys, options = {}) {|ret| ... }

Observe key state

The state of the keys on all nodes. If the keys argument was String or Symbol, this method will return just array of results (result per each node), otherwise it will return hash map.

Examples:

Observe single key

c.observe("foo")
#=> [#<Couchbase::Result:0x00000001650df0 ....>, ...]

Observe multiple keys

keys = ["foo", "bar"]
stats = c.observe(keys)
stats.size   #=> 2
stats["foo"] #=> #<Couchbase::Result:0x00000001650df0 ....>

Parameters:

  • keys (String, Symbol, Array)

    One or several keys to fetch

  • options (Hash)

    Options for operation.

Yield Parameters:

  • ret (Result)

    the result of operation in asynchronous mode (valid attributes: error, status, operation, key, cas, from_master, time_to_persist, time_to_replicate).

Returns:

  • (Hash<String, Array<Result>>, Array<Result>)

    the state of the keys on all nodes. If the keys argument was String or Symbol, this method will return just array of results (result per each node), otherwise it will return hash map.

Since:

  • 1.2.0.dp6



2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
# File 'ext/couchbase_ext/couchbase_ext.c', line 2784

static VALUE
cb_bucket_observe(int argc, VALUE *argv, VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    struct context_st *ctx;
    VALUE args, rv, proc, exc;
    size_t ii, ll = 0, nn;
    libcouchbase_error_t err = LIBCOUCHBASE_SUCCESS;
    struct key_traits_st *traits;
    int is_array;

    if (bucket->handle == NULL) {
        rb_raise(eConnectError, "closed connection");
    }
    rb_scan_args(argc, argv, "0*&", &args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    traits = xcalloc(1, sizeof(struct key_traits_st));
    traits->bucket = bucket;
    is_array = traits->is_array;
    nn = cb_args_scan_keys(RARRAY_LEN(args), args, traits);
    ctx = xcalloc(1, sizeof(struct context_st));
    if (ctx == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for context");
    }
    ctx->proc = proc;
    cb_gc_protect(bucket, ctx->proc);
    ctx->bucket = bucket;
    rv = rb_hash_new();
    ctx->rv = &rv;
    ctx->exception = Qnil;
    ctx->nqueries = traits->nkeys;
    err = libcouchbase_observe(bucket->handle, (const void *)ctx,
            traits->nkeys, (const void * const *)traits->keys, traits->lens);
    if (err == LIBCOUCHBASE_SUCCESS) {
        for (ii = 0; ii < traits->nkeys; ++ii) {
            ll += traits->lens[ii];
        }
    }
    xfree(traits->keys);
    xfree(traits->lens);
    xfree(traits->ttls);
    xfree(traits);
    exc = cb_check_error(err, "failed to schedule observe request", Qnil);
    if (exc != Qnil) {
        xfree(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += HEADER_SIZE + 4 + ll;
    if (bucket->async) {
        maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            libcouchbase_wait(bucket->handle);
        }
        exc = ctx->exception;
        xfree(ctx);
        if (exc != Qnil) {
            cb_gc_unprotect(bucket, exc);
            rb_exc_raise(exc);
        }
        if (bucket->exception != Qnil) {
            rb_exc_raise(bucket->exception);
        }
            if (nn > 1 || is_array) {
            return rv;  /* return as a hash {key => {}, ...} */
        } else {
            VALUE vv = Qnil;
            rb_hash_foreach(rv, cb_first_value_i, (VALUE)&vv);
            return vv;  /* return first value */
        }
    }
}

- (Couchbase::Result+) observe_and_wait(*keys, &block)

Wait for persistence condition

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:

Since:

  • 1.2.0.dp6



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
# File 'lib/couchbase/bucket.rb', line 214

def observe_and_wait(*keys, &block)
  options = {:timeout => default_observe_timeout}
  options.update(keys.pop) if keys.size > 1 && keys.last.is_a?(Hash)
  verify_observe_options(options)
  if block && !async?
    raise ArgumentError, "synchronous mode doesn't support callbacks"
  end
  if keys.size == 0
    raise ArgumentError, "at least one key is required"
  end
  if keys.size == 1 && keys[0].is_a?(Hash)
    key_cas = keys[0]
  else
    key_cas = keys.flatten.reduce({}) do |h, kk|
      h[kk] = nil   # set CAS to nil
      h
    end
  end
  if async?
    do_observe_and_wait(key_cas, options, &block)
  else
    res = do_observe_and_wait(key_cas, options, &block) while res.nil?
    if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol))
      return res[0]
    else
      return res
    end
  end
end

- (Object) prepend(key, value, options = {})

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.

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)

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

  • :observe (Hash)

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

Raises:

Since:

  • 1.0.0



3964
3965
3966
3967
3968
# File 'ext/couchbase_ext/couchbase_ext.c', line 3964

static VALUE
cb_bucket_prepend(int argc, VALUE *argv, VALUE self)
{
    return cb_bucket_store(LIBCOUCHBASE_PREPEND, argc, argv, self);
}

- (Object) reconnect(url, options = {}) - (Object) reconnect(options = {})

Reconnect the bucket

Reconnect the bucket using initial configuration with optional redefinition.

Overloads:

Since:

  • 1.1.0



1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
# File 'ext/couchbase_ext/couchbase_ext.c', line 1837

static VALUE
cb_bucket_reconnect(int argc, VALUE *argv, VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);

    do_scan_connection_options(bucket, argc, argv);
    do_connect(bucket);

    return self;
}

- (Fixnum) replace(key, value, options = {})

Replace the existing object in the database

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)

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

Returns:

  • (Fixnum)

    The CAS value of the object.

Raises:

Since:

  • 1.0.0



3825
3826
3827
3828
3829
# File 'ext/couchbase_ext/couchbase_ext.c', line 3825

static VALUE
cb_bucket_replace(int argc, VALUE *argv, VALUE self)
{
    return cb_bucket_store(LIBCOUCHBASE_REPLACE, argc, argv, self);
}

- (nil) run {|bucket| ... }

Run the event loop.

Examples:

Use block to run the loop

c = Couchbase.new
c.run do
  c.get("foo") {|ret| puts ret.value}
end

Use lambda to run the loop

c = Couchbase.new
operations = lambda do |c|
  c.get("foo") {|ret| puts ret.value}
end
c.run(&operations)

Use threshold to send out commands automatically

c = Couchbase.connect
sent = 0
c.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

Parameters:

  • options (Hash)

    The options for operation for connection

Yield Parameters:

  • bucket (Bucket)

    the bucket instance

Returns:

  • (nil)

Raises:

Since:

  • 1.0.0



3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
# File 'ext/couchbase_ext/couchbase_ext.c', line 3605

static VALUE
cb_bucket_run(int argc, VALUE *argv, VALUE self)
{
    VALUE args[3];

    rb_need_block();
    args[0] = self;
    rb_scan_args(argc, argv, "01&", &args[1], &args[2]);
    rb_ensure(do_run, (VALUE)args, ensure_run, (VALUE)args);
    return Qnil;
}

- (true, false) save_design_doc(data)

Update or create design doc with supplied views

Parameters:

  • data (Hash, IO, String)

    The source object containing JSON encoded design document. It must have _id key set, this key should start with _design/.

Returns:

  • (true, false)

Since:

  • 1.2.0



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
# File 'lib/couchbase/bucket.rb', line 133

def save_design_doc(data)
  attrs = case data
          when String
            MultiJson.load(data)
          when IO
            MultiJson.load(data.read)
          when Hash
            data
          else
            raise ArgumentError, "Document should be Hash, String or IO instance"
          end

  if attrs['_id'].to_s !~ /^_design\//
    raise ArgumentError, "'_id' key must be set and start with '_design/'."
  end
  attrs['language'] ||= 'javascript'
  req = make_couch_request(attrs['_id'],
                           :body => MultiJson.dump(attrs),
                           :method => :put)
  res = MultiJson.load(req.perform)
  if res['ok']
    true
  else
    raise "Failed to save design document: #{res['error']}"
  end
end

- (Fixnum) set(key, value, options = {}) {|ret| ... } Also known as: []=

Unconditionally store the object in the Couchbase

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)

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.set["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)

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

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



3721
3722
3723
3724
3725
# File 'ext/couchbase_ext/couchbase_ext.c', line 3721

static VALUE
cb_bucket_set(int argc, VALUE *argv, VALUE self)
{
    return cb_bucket_store(LIBCOUCHBASE_SET, argc, argv, self);
}

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

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.

Where keys are stat keys, values are host-value pairs

Examples:

Found how many items in the bucket

total = 0
c.stats["total_items"].each do |key, value|
  total += value.to_i
end

Found total items number asynchronously

total = 0
c.run do
  c.stats do |ret|
    if ret.key == "total_items"
      total += ret.value.to_i
    end
  end
end

Get memory stats (works on couchbase buckets)

c.stats(:memory)   #=> {"mem_used"=>{...}, ...}

Parameters:

  • arg (String)

    argument to STATS query

Yield Parameters:

  • ret (Result)

    the object with node, key and value attributes.

Returns:

  • (Hash)

    where keys are stat keys, values are host-value pairs

Raises:

Since:

  • 1.0.0



3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
# File 'ext/couchbase_ext/couchbase_ext.c', line 3438

static VALUE
cb_bucket_stats(int argc, VALUE *argv, VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    struct context_st *ctx;
    VALUE rv, exc, arg, proc;
    char *key;
    size_t nkey;
    libcouchbase_error_t err;

    if (bucket->handle == NULL) {
        rb_raise(eConnectError, "closed connection");
    }
    rb_scan_args(argc, argv, "01&", &arg, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }

    ctx = xcalloc(1, sizeof(struct context_st));
    if (ctx == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for context");
    }
    rv = rb_hash_new();
    ctx->rv = &rv;
    ctx->bucket = bucket;
    ctx->proc = proc;
    cb_gc_protect(bucket, ctx->proc);
    ctx->exception = Qnil;
    if (arg != Qnil) {
        arg = unify_key(bucket, arg, 0);
        key = RSTRING_PTR(arg);
        nkey = RSTRING_LEN(arg);
    } else {
        key = NULL;
        nkey = 0;
    }
    ctx->nqueries = 1;
    err = libcouchbase_server_stats(bucket->handle, (const void *)ctx,
            key, nkey);
    exc = cb_check_error(err, "failed to schedule stat request", Qnil);
    if (exc != Qnil) {
        xfree(ctx);
        rb_exc_raise(exc);
    }
    if (bucket->async) {
        bucket->nbytes += HEADER_SIZE + nkey;
        maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            libcouchbase_wait(bucket->handle);
        }
        exc = ctx->exception;
        xfree(ctx);
        if (exc != Qnil) {
            cb_gc_unprotect(bucket, exc);
            rb_exc_raise(exc);
        }
        if (bucket->exception != Qnil) {
            rb_exc_raise(bucket->exception);
        }
        return rv;
    }

    return Qnil;
}

- (nil) stop

Stop the event loop.

Examples:

Breakout the event loop when 5th request is completed

c = Couchbase.connect
c.run do
  10.times do |ii|
    c.get("foo") do |ret|
      puts ii
      c.stop if ii == 5
    end
  end
end

Returns:

  • (nil)

Since:

  • 1.2.0



3635
3636
3637
3638
3639
3640
3641
# File 'ext/couchbase_ext/couchbase_ext.c', line 3635

static VALUE
cb_bucket_stop(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    bucket->io->stop_event_loop(bucket->io);
    return Qnil;
}

- (true, false) touch(key, options = {}) {|ret| ... } - (Hash) touch(keys) {|ret| ... }

Update the expiry time of an item

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:

  • - (true, false) touch(key, options = {}) {|ret| ... }

    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)

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

    Yield Parameters:

    • ret (Result)

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

    Returns:

    • (true, false)

      true if the operation was successful and false otherwise.

    Raises:

  • - (Hash) touch(keys) {|ret| ... }

    Mapping keys to result of touch operation (true if the operation was successful and false otherwise)

    Examples:

    Touch several values

    c.touch("foo" => 10, :bar => 20) #=> {"foo" => true, "bar" => true}
    

    Touch several values in async mode

    c.run do
      c.touch("foo" => 10, :bar => 20) do |ret|
         ret.operation   #=> :touch
         ret.success?    #=> true
         ret.key         #=> "foo" and "bar" in separate calls
      end
    end
    

    Touch single value

    c.touch("foo" => 10)             #=> true
    

    Parameters:

    • keys (Hash)

      The Hash where keys represent the keys in the database, values — the expiry times for corresponding key. See description of :ttl argument above for more information about TTL values.

    Yield Parameters:

    • ret (Result)

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

    Returns:

    • (Hash)

      Mapping keys to result of touch operation (true if the operation was successful and false otherwise)

Since:

  • 1.0.0



3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
# File 'ext/couchbase_ext/couchbase_ext.c', line 3161

static VALUE
cb_bucket_touch(int argc, VALUE *argv, VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    struct context_st *ctx;
    VALUE args, rv, proc, exc;
    size_t nn, ii, ll;
    libcouchbase_error_t err;
    struct key_traits_st *traits;

    if (bucket->handle == NULL) {
        rb_raise(eConnectError, "closed connection");
    }
    rb_scan_args(argc, argv, "0*&", &args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    rb_funcall(args, id_flatten_bang, 0);
    traits = xcalloc(1, sizeof(struct key_traits_st));
    traits->bucket = bucket;
    nn = cb_args_scan_keys(RARRAY_LEN(args), args, traits);
    ctx = xcalloc(1, sizeof(struct context_st));
    if (ctx == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for context");
    }
    ctx->proc = proc;
    cb_gc_protect(bucket, ctx->proc);
    ctx->bucket = bucket;
    rv = rb_hash_new();
    ctx->rv = &rv;
    ctx->exception = Qnil;
    ctx->nqueries = traits->nkeys;
    err = libcouchbase_mtouch(bucket->handle, (const void *)ctx,
            traits->nkeys, (const void * const *)traits->keys,
            traits->lens, traits->ttls);
    for (ii = 0, ll = 0; ii < traits->nkeys; ++ii) {
        ll += traits->lens[ii];
    }
    xfree(traits->keys);
    xfree(traits->lens);
    xfree(traits);
    exc = cb_check_error(err, "failed to schedule touch request", Qnil);
    if (exc != Qnil) {
        xfree(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += HEADER_SIZE + 4 + ll;
    if (bucket->async) {
        maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            libcouchbase_wait(bucket->handle);
        }
        exc = ctx->exception;
        xfree(ctx);
        if (exc != Qnil) {
            cb_gc_unprotect(bucket, exc);
            rb_exc_raise(exc);
        }
        if (bucket->exception != Qnil) {
            rb_exc_raise(bucket->exception);
        }
        if (nn > 1) {
            return rv;  /* return as a hash {key => true, ...} */
        } else {
            VALUE vv = Qnil;
            rb_hash_foreach(rv, cb_first_value_i, (VALUE)&vv);
            return vv;
        }
    }
}

- (Hash) version {|ret| ... }

Returns versions of the server for each node in the cluster

Node-version pairs

Examples:

Synchronous version request

c.version            #=> will render version

Asynchronous version request

c.run do
  c.version do |ret|
    ret.operation    #=> :version
    ret.success?     #=> true
    ret.node         #=> "localhost:11211"
    ret.value        #=> will render version
  end
end

Yield Parameters:

  • ret (Result)

    the object with error, node, operation and value attributes.

Returns:

  • (Hash)

    node-version pairs

Raises:

Since:

  • 1.1.0



3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
# File 'ext/couchbase_ext/couchbase_ext.c', line 3342

static VALUE
cb_bucket_version(VALUE self)
{
    struct bucket_st *bucket = DATA_PTR(self);
    struct context_st *ctx;
    VALUE rv, exc;
    libcouchbase_error_t err;

    if (bucket->handle == NULL) {
        rb_raise(eConnectError, "closed connection");
    }
    if (!bucket->async && rb_block_given_p()) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    ctx = xcalloc(1, sizeof(struct context_st));
    if (ctx == NULL) {
        rb_raise(eClientNoMemoryError, "failed to allocate memory for context");
    }
    rv = rb_hash_new();
    ctx->rv = &rv;
    ctx->bucket = bucket;
    ctx->exception = Qnil;
    if (rb_block_given_p()) {
        ctx->proc = rb_block_proc();
    } else {
        ctx->proc = Qnil;
    }
    cb_gc_protect(bucket, ctx->proc);
    ctx->nqueries = 1;
    err = libcouchbase_server_versions(bucket->handle, (const void *)ctx);
    exc = cb_check_error(err, "failed to schedule version request", Qnil);
    if (exc != Qnil) {
        xfree(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += HEADER_SIZE;
    if (bucket->async) {
        maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            libcouchbase_wait(bucket->handle);
        }
        exc = ctx->exception;
        xfree(ctx);
        if (exc != Qnil) {
            cb_gc_unprotect(bucket, exc);
            rb_exc_raise(exc);
        }
        return rv;
    }
}