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:

  • 1.0.0

Defined Under Namespace

Classes: CouchRequest

Constant Summary collapse

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

0x02

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, options = {}) ⇒ Bucket #initialize(options = {}) ⇒ Bucket

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:

  • #initialize(url, options = {}) ⇒ Bucket

    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) (defaults to: {})

      The options for connection. See options definition below.

  • #initialize(options = {}) ⇒ Bucket

    Initialize bucket using options only.

    Parameters:

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

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

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

    • :bootstrap_transports (Array) — default: nil

      the list of bootrap transport mechanisms the library should try during initial connection and also when cluster changes its topology. When nil passed it will fallback to best accessible option. The order of the array elements does not matter at the momemnt. Currently following values are supported:

      :http

      Previous default protocol, which involves open HTTP stream

      :cccp

      Cluster Configutration Carrier Publication: new binary protocol for efficient delivery of cluster configuration changes to the clients. Read more at www.couchbase.com/wiki/display/couchbase/Cluster+Configuration+Carrier+Publication

Raises:

Since:

  • 1.0.0



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# File 'ext/couchbase_ext/bucket.c', line 559

VALUE
cb_bucket_init(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    bucket->self = self;
    bucket->exception = Qnil;
    bucket->type = LCB_TYPE_BUCKET;
    bucket->hostname = cb_vStrLocalhost;
    bucket->port = 8091;
    bucket->pool = cb_vStrDefault;
    bucket->bucket = cb_vStrDefault;
    bucket->username = Qnil;
    bucket->password = Qnil;
    bucket->engine = cb_sym_default;
    bucket->async = 0;
    bucket->quiet = 0;
    bucket->default_ttl = 0;
    bucket->default_flags = 0;
    cb_bucket_transcoder_set(self, cb_mDocument);
    bucket->default_observe_timeout = 2500000;
    bucket->on_error_proc = Qnil;
    bucket->on_connect_proc = Qnil;
    bucket->timeout = 0;
    bucket->environment = cb_sym_production;
    bucket->key_prefix_val = Qnil;
    bucket->node_list = Qnil;
    bucket->bootstrap_transports = Qnil;
    bucket->object_space = st_init_numtable();
    bucket->destroying = 0;
    bucket->connected = 0;
    bucket->on_connect_proc = Qnil;
    bucket->async_disconnect_hook_set = 0;

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

    return self;
}

Instance Attribute Details

#authorityString (readonly)

The authority (“hostname:port”) of the current node

Returns:

See Also:

Since:

  • 1.0.0



1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
# File 'ext/couchbase_ext/bucket.c', line 1022

VALUE
cb_bucket_authority_get(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    VALUE old_hostname = bucket->hostname;
    uint16_t old_port = bucket->port;
    VALUE hostname = cb_bucket_hostname_get(self);
    cb_bucket_port_get(self);

    if (hostname != old_hostname || bucket->port != old_port) {
        char port_s[8];
        snprintf(port_s, sizeof(port_s), ":%u", bucket->port);
        bucket->authority = rb_str_dup(hostname);
        rb_str_cat2(bucket->authority, port_s);
        rb_str_freeze(bucket->authority);
    }
    return bucket->authority;
}

#bucketString (readonly) Also known as: name

The bucket name of the current connection

Returns:

  • (String)

    the bucket name

See Also:

Since:

  • 1.0.0



1047
1048
1049
1050
1051
1052
# File 'ext/couchbase_ext/bucket.c', line 1047

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

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

Since:

  • 1.2.0



930
931
932
933
934
935
# File 'ext/couchbase_ext/bucket.c', line 930

VALUE
cb_bucket_default_arithmetic_init_get(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    return ULL2NUM(bucket->default_arith_init);
}

#default_flagsFixnum

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



758
759
760
761
762
763
# File 'ext/couchbase_ext/bucket.c', line 758

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

#default_formatSymbol

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: 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.default_format = :plain

Selecting plain format using Fixnum constant (deprecated)

connection.default_format = Couchbase::Bucket::FMT_PLAIN

Returns:

  • (Symbol)

    the effective format

See Also:

Since:

  • 1.0.0



794
795
796
797
798
799
800
801
802
803
804
805
806
807
# File 'ext/couchbase_ext/bucket.c', line 794

VALUE
cb_bucket_default_format_get(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);

    if (bucket->transcoder == cb_mDocument) {
        return cb_sym_document;
    } else if (bucket->transcoder == cb_mMarshal) {
        return cb_sym_marshal;
    } else if (bucket->transcoder == cb_mPlain) {
        return cb_sym_plain;
    }
    return Qnil;
}

#default_observe_timeoutFixnum

The default timeout value for #observe_and_wait operation in microseconds

Returns:

  • (Fixnum)

Since:

  • 1.2.0.dp6



1136
1137
1138
1139
1140
1141
# File 'ext/couchbase_ext/bucket.c', line 1136

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

#environmentSymbol (readonly)

The environment of the connection (:development or :production)

Returns:

  • (Symbol)

Since:

  • 1.2.0



1102
1103
1104
1105
1106
1107
# File 'ext/couchbase_ext/bucket.c', line 1102

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

#hostnameString (readonly)

The hostname of the current node

Returns:

  • (String)

    the host name of the management interface (default: “localhost”)

See Also:

Since:

  • 1.0.0



974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
# File 'ext/couchbase_ext/bucket.c', line 974

VALUE
cb_bucket_hostname_get(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    if (bucket->handle) {
        const char *host;
        char *colon;
        unsigned long len;
        host = lcb_get_node(bucket->handle, LCB_NODE_HTCONFIG | LCB_NODE_NEVERNULL, 0);
        if (host != NULL && (colon = strstr(host, ":"))  != NULL) {
            *colon = '\0';
        }
        len = RSTRING_LEN(bucket->hostname);
        if (len != strlen(host) || strncmp(RSTRING_PTR(bucket->hostname), host, len) != 0) {
            bucket->hostname = STR_NEW_CSTR(host);
            rb_str_freeze(bucket->hostname);
        }
    }
    return bucket->hostname;
}

#key_prefixString

Returns 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



951
952
953
954
955
956
# File 'ext/couchbase_ext/bucket.c', line 951

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

#num_replicasFixnum (readonly)

The numbers of the replicas for each node in the cluster

Returns:

  • (Fixnum)

Since:

  • 1.2.0.dp6



1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
# File 'ext/couchbase_ext/bucket.c', line 1116

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

#on_connect {|result| ... } ⇒ Proc

Connection callback for asynchronous mode.

This callback used to notify that bucket instance is connected and ready to handle requests in asynchronous mode.

Examples:

Using lambda syntax

connection = Couchbase.new(:async => true)
connection.on_connect = lambda do |ret|
  if ret.success?
    conn.set("foo", "bar")
  end
end
connection.run

Using block syntax

connection = Couchbase.new(:async => true)
connection.run do |conn|
  connection.on_connect do |ret|
    if ret.success?
      conn.set("foo", "bar")
    end
  end
end
EM.run do
  pool = Pool.new
  connection = Couchbase.new(:engine => :eventmachine, :async => true)
  connection.on_connect do |result|
    unless result.success?
      $stderr.puts "Could not connect to CouchBase #{result.error}"
    else
      pool.add result.bucket
    end
  end
end
EM.run do
  pool = Pool.new
  connection = Couchbase.new(:engine => :eventmachine, :async => true)
  connection.on_connect = pool.method(:couchbase_connect_callback)
end

Yield Parameters:

  • result (Result)

    The result instance, with valid properties #error, #success?, #operation and #bucket

Returns:

  • (Proc)

    the effective callback

Since:

  • 1.3.0



898
899
900
901
902
903
904
905
906
907
908
# File 'ext/couchbase_ext/bucket.c', line 898

VALUE
cb_bucket_on_connect_get(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);

    if (rb_block_given_p()) {
        return cb_bucket_on_connect_set(self, rb_block_proc());
    } else {
        return bucket->on_connect_proc;
    }
}

#on_error {|exc| ... } ⇒ Proc

Error callback for asynchronous mode.

This callback is using to deliver exceptions in asynchronous mode.

Examples:

Using lambda syntax

connection = Couchbase.connect
connection.on_error = lambda {|exc| ... }
connection.run do |conn|
  conn.set("foo", "bar")
end

Using block syntax

connection = Couchbase.connect
connection.on_error {|exc| ... }
connection.run do |conn|
  conn.set("foo", "bar")
end

Yield Parameters:

  • exc (Exception)

    The exception instance

Returns:

  • (Proc)

    the effective callback

Since:

  • 1.0.0



853
854
855
856
857
858
859
860
861
862
863
# File 'ext/couchbase_ext/bucket.c', line 853

VALUE
cb_bucket_on_error_get(VALUE self)
{
    struct cb_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;
    }
}

#passwordString (readonly)

The password used to connect to the cluster

Returns:

  • (String)

    the password for protected buckets

Since:

  • 1.0.0



1087
1088
1089
1090
1091
1092
# File 'ext/couchbase_ext/bucket.c', line 1087

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

#poolString (readonly)

The pool name of the current connection

Returns:

  • (String)

    the pool name (usually “default”)

See Also:

Since:

  • 1.0.0



1060
1061
1062
1063
1064
1065
# File 'ext/couchbase_ext/bucket.c', line 1060

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

#portFixnum (readonly)

The port of the current node

Returns:

  • (Fixnum)

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

See Also:

Since:

  • 1.0.0



1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
# File 'ext/couchbase_ext/bucket.c', line 1001

VALUE
cb_bucket_port_get(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    if (bucket->handle) {
        const char *port;
        port = lcb_get_node(bucket->handle, LCB_NODE_HTCONFIG | LCB_NODE_NEVERNULL, 0);
        if (port && (port = strstr(port, ":"))) {
            port++;
        }
        bucket->port = atoi(port);
    }
    return UINT2NUM(bucket->port);
}

#quiettrue, false 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



742
743
744
745
746
747
# File 'ext/couchbase_ext/bucket.c', line 742

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

#timeoutFixnum

Returns 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



910
911
912
913
914
915
# File 'ext/couchbase_ext/bucket.c', line 910

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

#transcoderObject

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.

@example Simple data transcoder, which use Zlib to compress documents
  class ZlibTranscoder
    FMT_ZLIB = 0x04

    def initialize(base)
      @base = base
    end

    def dump(obj, flags, options = {})
      obj, flags = @base.dump(obj, flags, options)
      z = Zlib::Deflate.new(Zlib::BEST_SPEED)
      buffer = z.deflate(obj, Zlib::FINISH)
      z.close
      [buffer, flags|FMT_ZLIB]
    end

    def load(blob, flags, options = {})
      # decompress value only if Zlib flag set
      if (flags & FMT_ZLIB) == FMT_ZLIB
        z = Zlib::Inflate.new
        blob = z.inflate(blob)
        z.finish
        z.close
      end
      @base.load(blob, flags, options)
    end
  end

Returns:

  • (Object)

    the data transcoder

Since:

  • 1.2.4



774
775
776
777
778
779
# File 'ext/couchbase_ext/bucket.c', line 774

VALUE
cb_bucket_transcoder_get(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    return bucket->transcoder;
}

#urlString (readonly)

The config url for this connection.

Generally it is the bootstrap URL, but it could be different after cluster upgrade. This url is used to fetch the cluster configuration.

Returns:

  • (String)

    the address of the cluster management interface

Since:

  • 1.0.0



1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
# File 'ext/couchbase_ext/bucket.c', line 1165

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

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

#usernameString (readonly)

The user name used to connect to the cluster

Returns:

  • (String)

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

See Also:

Since:

  • 1.0.0



1074
1075
1076
1077
1078
1079
# File 'ext/couchbase_ext/bucket.c', line 1074

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

Instance Method Details

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

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

Returns The CAS value of the object.

Examples:

Add the same key twice

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

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

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

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

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

    Options for operation.

Options Hash (options):

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

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

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

    Flags for storage options. Flags are ignored by the server but preserved for use by the client. For more info see #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



335
336
337
338
339
# File 'ext/couchbase_ext/store.c', line 335

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

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

Append this object to the existing object

Returns The CAS value of the object.

Examples:

Simple append

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

Implementing sets using append

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

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

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

Using optimistic locking. The operation will fail on CAS mismatch

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

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

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

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

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

    Options for operation.

Options Hash (options):

  • :cas (Fixnum)

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

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

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



463
464
465
466
467
# File 'ext/couchbase_ext/store.c', line 463

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

#async?true, false

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

See Also:

Since:

  • 1.0.0



735
736
737
738
739
740
# File 'ext/couchbase_ext/bucket.c', line 735

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

#cas(key, options = {}) {|value| ... } ⇒ Fixnum 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.

Setting the :retry option to a positive number will cause this method to rescue the Error::KeyExists error that happens when an update collision is detected, and automatically get a fresh copy of the value and retry the block. This will repeat as long as there continues to be conflicts, up to the maximum number of retries specified. For asynchronous mode, this means the block will be yielded once for the initial #get, once for the final #set (successful or last failure), and zero or more additional #get retries in between, up to the maximum allowed by the :retry option.

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

  • :retry (Fixnum) — default: 0

    maximum number of times to autmatically retry upon update collision

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



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/couchbase/bucket.rb', line 93

def cas(key, options = {})
  retries_remaining = options.delete(:retry) || 0
  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)) do |set_ret|
        if set_ret.error.is_a?(Couchbase::Error::KeyExists) && (retries_remaining > 0)
          cas(key, options.merge(:retry => retries_remaining - 1), &block)
        else
          block.call(set_ret)
        end
      end
    end
  else
    begin
      val, flags, ver = get(key, :extended => true)
      val = yield(val) # get new value from caller
      set(key, val, options.merge(:cas => ver, :flags => flags))
    rescue Couchbase::Error::KeyExists
      if retries_remaining > 0
        retries_remaining -= 1
        retry
      else
        raise
      end
    end
  end
end

#connected?true, false

Check whether the instance connected to the cluster.

Returns:

  • (true, false)

    true if the instance connected to the cluster

Since:

  • 1.1.0



707
708
709
710
711
712
# File 'ext/couchbase_ext/bucket.c', line 707

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

#create_periodic_timer(interval, &block) ⇒ Couchbase::Timer

Create and register periodic timer

Returns:



285
286
287
# File 'lib/couchbase/bucket.rb', line 285

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

#create_timer(interval, &block) ⇒ Couchbase::Timer

Create and register one-shot timer

Returns:



278
279
280
# File 'lib/couchbase/bucket.rb', line 278

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

#decr(key, delta = 1, options = {}) {|ret| ... } ⇒ Fixnum 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.

Returns 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) (defaults to: 1)

    Integer (up to 64 bits) value to decrement

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

    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



310
311
312
313
314
# File 'ext/couchbase_ext/arithmetic.c', line 310

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

#delete(key, options = {}) ⇒ true, ...

Delete the specified key

Returns the result of the operation.

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) (defaults to: {})

    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.

Returns:

  • (true, false, Hash<String, Boolean>)

    the result of the operation

Raises:

Since:

  • 1.0.0



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
159
160
161
162
163
# File 'ext/couchbase_ext/delete.c', line 100

VALUE
cb_bucket_delete(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    VALUE rv, exc;
    VALUE proc;
    lcb_error_t err;
    struct cb_params_st params;

    if (!cb_bucket_connected_bang(bucket, cb_sym_delete)) {
        return Qnil;
    }

    memset(&params, 0, sizeof(struct cb_params_st));
    rb_scan_args(argc, argv, "0*&", &params.args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    rb_funcall(params.args, cb_id_flatten_bang, 0);
    params.type = cb_cmd_remove;
    params.bucket = bucket;
    cb_params_build(&params);

    ctx = cb_context_alloc_common(bucket, proc, params.cmd.remove.num);
    ctx->quiet = params.cmd.remove.quiet;
    err = lcb_remove(bucket->handle, (const void *)ctx,
            params.cmd.remove.num, params.cmd.remove.ptr);
    cb_params_destroy(&params);
    exc = cb_check_error(err, "failed to schedule delete request", Qnil);
    if (exc != Qnil) {
        cb_context_free(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += params.npayload;
    if (bucket->async) {
        cb_maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            lcb_wait(bucket->handle);
        }
        exc = ctx->exception;
        rv = ctx->rv;
        cb_context_free(ctx);
        if (exc != Qnil) {
            rb_exc_raise(exc);
        }
        exc = bucket->exception;
        if (exc != Qnil) {
            bucket->exception = Qnil;
            rb_exc_raise(exc);
        }
        if (params.cmd.remove.num > 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;
        }
        return rv;
    }
}

#delete_design_doc(id, rev = nil) ⇒ true, false

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



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/couchbase/bucket.rb', line 209

def delete_design_doc(id, rev = nil)
  ddoc = design_docs[id.sub(/^_design\//, '')]
  unless ddoc
    yield nil if block_given?
    return nil
  end
  path = Utils.build_query(ddoc.id, :rev => rev || ddoc.meta['rev'])
  req = make_http_request(path, :method => :delete, :extended => true)
  rv = nil
  req.on_body do |res|
    rv = res
    val = MultiJson.load(res.value)
    if block_given?
      if res.success? && val['error']
        res.error = Error::View.new("delete_design_doc", val['error'])
      end
      yield(res)
    end
  end
  req.continue
  unless async?
    rv.success? or raise res.error
  end
end

#design_docsHash

Fetch design docs stored in current bucket

Returns:

  • (Hash)

Since:

  • 1.2.0



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/couchbase/bucket.rb', line 129

def design_docs
  req = make_http_request("/pools/default/buckets/#{bucket}/ddocs",
                          :type => :management, :extended => true)
  docmap = {}
  req.on_body do |body|
    res = MultiJson.load(body.value)
    res["rows"].each do |obj|
      if obj['doc']
        obj['doc']['value'] = obj['doc'].delete('json')
      end
      doc = DesignDoc.wrap(self, obj)
      key = doc.id.sub(/^_design\//, '')
      next if self.environment == :production && key =~ /dev_/
        docmap[key] = doc
    end
    yield(docmap) if block_given?
  end
  req.continue
  async? ? nil : docmap
end

#disconnecttrue

Close the connection to the cluster

Returns:

  • (true)

Raises:

Since:

  • 1.1.0



1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
# File 'ext/couchbase_ext/bucket.c', line 1420

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

    if (bucket->handle) {
        lcb_destroy(bucket->handle);
        lcb_destroy_io_ops(bucket->io);
        bucket->handle = NULL;
        bucket->io = NULL;
        bucket->connected = 0;
        return Qtrue;
    } else {
        rb_raise(cb_eConnectError, "closed connection");
        return Qfalse;
    }
}

#flush {|ret| ... } ⇒ true

Delete contents of the bucket

Examples:

Simple flush the bucket

c.flush    #=> true

Asynchronous flush

c.run do
  c.flush do |ret|
    ret.operation   #=> :flush
    ret.success?    #=> true
    ret.status      #=> 200
  end
end

Yield Parameters:

  • ret (Result)

    the object with error, status and operation attributes.

Returns:

  • (true)

    always return true (see raise section)

Raises:

See Also:

Since:

  • 1.2.0.beta



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/couchbase/bucket.rb', line 259

def flush
  if !async? && block_given?
    raise ArgumentError, "synchronous mode doesn't support callbacks"
  end
  req = make_http_request("/pools/default/buckets/#{bucket}/controller/doFlush",
                          :type => :management, :method => :post, :extended => true)
  res = nil
  req.on_body do |r|
    res = r
    res.instance_variable_set("@operation", :flush)
    yield(res) if block_given?
  end
  req.continue
  true
end

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

Obtain an object stored in Couchbase by given key.

Overloads:

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

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

    Examples:

    Get single value in quiet 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) (defaults to: {})

      Options for operation.

    Options Hash (options):

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

      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.

    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) associated with the key.

    Raises:

  • #get(keys, options = {}) ⇒ Hash

    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]}.

    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) (defaults to: {})

      Options for operation. (see options definition above)

    Returns:

    • (Hash)

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

See Also:

Since:

  • 1.0.0



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'ext/couchbase_ext/get.c', line 228

VALUE
cb_bucket_get(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    VALUE rv, proc, exc;
    size_t ii;
    lcb_error_t err = LCB_SUCCESS;
    struct cb_params_st params;

    if (!cb_bucket_connected_bang(bucket, cb_sym_get)) {
        return Qnil;
    }

    memset(&params, 0, sizeof(struct cb_params_st));
    rb_scan_args(argc, argv, "0*&", &params.args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    params.type = cb_cmd_get;
    params.bucket = bucket;
    params.cmd.get.keys_ary = rb_ary_new();
    cb_params_build(&params);
    ctx = cb_context_alloc_common(bucket, proc, params.cmd.get.num);
    ctx->extended = params.cmd.get.extended;
    ctx->quiet = params.cmd.get.quiet;
    ctx->transcoder = params.cmd.get.transcoder;
    ctx->transcoder_opts = params.cmd.get.transcoder_opts;
    if (RTEST(params.cmd.get.replica)) {
        if (params.cmd.get.replica == cb_sym_all) {
            ctx->nqueries = lcb_get_num_replicas(bucket->handle);
            ctx->all_replicas = 1;
        }
        err = lcb_get_replica(bucket->handle, (const void *)ctx,
                params.cmd.get.num, params.cmd.get.ptr_gr);
    } else {
        err = lcb_get(bucket->handle, (const void *)ctx,
                params.cmd.get.num, params.cmd.get.ptr);
    }
    cb_params_destroy(&params);
    exc = cb_check_error(err, "failed to schedule get request", Qnil);
    if (exc != Qnil) {
        cb_context_free(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += params.npayload;
    if (bucket->async) {
        cb_maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            lcb_wait(bucket->handle);
        }
        exc = ctx->exception;
        rv = ctx->rv;
        cb_context_free(ctx);
        if (exc != Qnil) {
            rb_exc_raise(exc);
        }
        exc = bucket->exception;
        if (exc != Qnil) {
            bucket->exception = Qnil;
            rb_exc_raise(exc);
        }
        if (params.cmd.get.gat || params.cmd.get.assemble_hash ||
                (params.cmd.get.extended && (params.cmd.get.num > 1 || params.cmd.get.array))) {
            return rv;  /* return as a hash {key => [value, flags, cas], ...} */
        }
        if (params.cmd.get.num > 1 || params.cmd.get.array) {
            VALUE keys, ret;
            ret = rb_ary_new();
            /* make sure ret is guarded so not invisible in a register
             * when stack scanning */
            RB_GC_GUARD(ret);
            keys = params.cmd.get.keys_ary;
            for (ii = 0; ii < params.cmd.get.num; ++ii) {
                rb_ary_push(ret, rb_hash_aref(rv, rb_ary_entry(keys, 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;
        }
    }
}

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

Note:

that server treats values as unsigned numbers, therefore if

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.

you try to store negative number and then increment or decrement it will cause overflow. (see “Integer overflow” example below)

Returns 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
# but it might look like working
c.set("foo", -2)
c.get("foo")           #=> -2
c.incr("foo", 2)       #=> 0
# on server:
#    // UINT64_MAX is 18446744073709551615
#    uint64_t num = atoll("-2");
#    // num is 18446744073709551614
#    num += 2
#    // num is 0

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) (defaults to: 1)

    Integer (up to 64 bits) value to increment

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

    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



219
220
221
222
223
# File 'ext/couchbase_ext/arithmetic.c', line 219

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

#initialize_copy(orig) ⇒ Couchbase::Bucket

Initialize copy

Initializes copy of the object, used by #dup

Parameters:

Returns:



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'ext/couchbase_ext/bucket.c', line 607

VALUE
cb_bucket_init_copy(VALUE copy, VALUE orig)
{
    struct cb_bucket_st *copy_b;
    struct cb_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;
    copy_b->port = orig_b->port;
    copy_b->authority = orig_b->authority;
    copy_b->hostname = orig_b->hostname;
    copy_b->pool = orig_b->pool;
    copy_b->bucket = orig_b->bucket;
    copy_b->username = orig_b->username;
    copy_b->password = orig_b->password;
    copy_b->engine = orig_b->engine;
    copy_b->async = orig_b->async;
    copy_b->quiet = orig_b->quiet;
    copy_b->transcoder = orig_b->transcoder;
    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;
    copy_b->async_disconnect_hook_set = 0;
    if (orig_b->on_error_proc != Qnil) {
        copy_b->on_error_proc = rb_funcall(orig_b->on_error_proc, cb_id_dup, 0);
    }
    if (orig_b->on_connect_proc != Qnil) {
        copy_b->on_connect_proc = rb_funcall(orig_b->on_connect_proc, cb_id_dup, 0);
    }
    if (orig_b->key_prefix_val != Qnil) {
        copy_b->key_prefix_val = rb_funcall(orig_b->key_prefix_val, cb_id_dup, 0);
    }
    if (orig_b->node_list != Qnil) {
        copy_b->node_list = rb_funcall(orig_b->node_list, cb_id_dup, 0);
    }
    if (orig_b->bootstrap_transports != Qnil) {
        copy_b->bootstrap_transports = rb_funcall(orig_b->bootstrap_transports, cb_id_dup, 0);
    }
    copy_b->key_prefix_val = orig_b->key_prefix_val;
    copy_b->object_space = st_init_numtable();
    copy_b->destroying = 0;
    copy_b->connected = 0;

    do_connect(copy_b);

    return copy;
}

#inspectString

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

Returns:

Since:

  • 1.0.0



1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
# File 'ext/couchbase_ext/bucket.c', line 1190

VALUE
cb_bucket_inspect(VALUE self)
{
    VALUE str;
    struct cb_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_append(str, bucket->authority);
    rb_str_buf_cat2(str, "/pools/");
    rb_str_append(str, bucket->pool);
    rb_str_buf_cat2(str, "/buckets/");
    rb_str_append(str, bucket->bucket);
    rb_str_buf_cat2(str, "/\" transcoder=");
    rb_str_append(str, rb_inspect(bucket->transcoder));
    snprintf(buf, 150, ", default_flags=0x%x, quiet=%s, connected=%s, timeout=%u",
            bucket->default_flags,
            bucket->quiet ? "true" : "false",
            (bucket->handle && bucket->connected) ? "true" : "false",
            bucket->timeout);
    rb_str_buf_cat2(str, buf);
    if (bucket->handle && bucket->connected) {
        lcb_config_transport_t type;
        rb_str_buf_cat2(str, ", bootstrap_transport=");
        lcb_cntl(bucket->handle, LCB_CNTL_GET, LCB_CNTL_CONFIG_TRANSPORT, &type);
        switch (type) {
        case LCB_CONFIG_TRANSPORT_HTTP:
            rb_str_buf_cat2(str, ":http");
            break;
        case LCB_CONFIG_TRANSPORT_CCCP:
            rb_str_buf_cat2(str, ":cccp");
            break;
        default:
            rb_str_buf_cat2(str, "<unknown>");
            break;
        }
    }
    if (RTEST(bucket->key_prefix_val)) {
        rb_str_buf_cat2(str, ", key_prefix=");
        rb_str_append(str, rb_inspect(bucket->key_prefix_val));
    }
    rb_str_buf_cat2(str, ">");

    return str;
}

#make_http_request(*args) {|res| ... } ⇒ Couchbase::Bucket::CouchRequest

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



421
422
423
424
425
426
427
428
429
430
# File 'ext/couchbase_ext/http.c', line 421

VALUE
cb_bucket_make_http_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, cb_cCouchRequest);
}

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

Observe key state

Returns 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) (defaults to: {})

    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



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'ext/couchbase_ext/observe.c', line 113

VALUE
cb_bucket_observe(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    VALUE rv, proc, exc;
    lcb_error_t err;
    struct cb_params_st params;

    if (!cb_bucket_connected_bang(bucket, cb_sym_observe)) {
        return Qnil;
    }

    memset(&params, 0, sizeof(struct cb_params_st));
    rb_scan_args(argc, argv, "0*&", &params.args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    params.type = cb_cmd_observe;
    params.bucket = bucket;
    cb_params_build(&params);
    ctx = cb_context_alloc_common(bucket, proc, params.cmd.observe.num);
    err = lcb_observe(bucket->handle, (const void *)ctx,
            params.cmd.observe.num, params.cmd.observe.ptr);
    cb_params_destroy(&params);
    exc = cb_check_error(err, "failed to schedule observe request", Qnil);
    if (exc != Qnil) {
        cb_context_free(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += params.npayload;
    if (bucket->async) {
        cb_maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            lcb_wait(bucket->handle);
        }
        exc = ctx->exception;
        rv = ctx->rv;
        cb_context_free(ctx);
        if (exc != Qnil) {
            rb_exc_raise(exc);
        }
        exc = bucket->exception;
        if (exc != Qnil) {
            bucket->exception = Qnil;
            rb_exc_raise(exc);
        }
        if (params.cmd.observe.num > 1 || params.cmd.observe.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 */
        }
    }
}

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

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:

  • (Fixnum, Hash<String, Fixnum>)

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

Raises:

Since:

  • 1.2.0.dp6



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/couchbase/bucket.rb', line 313

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?
    unless async?
      if keys.size == 1 && (keys[0].is_a?(String) || keys[0].is_a?(Symbol))
        return res.values.first
      else
        return res
      end
    end
  end
end

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

Note:

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

Prepend this object to the existing object

Examples:

Simple prepend example

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

Using explicit format option

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

Using optimistic locking. The operation will fail on CAS mismatch

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

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

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

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

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

    Options for operation.

Options Hash (options):

  • :cas (Fixnum)

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

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

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



522
523
524
525
526
# File 'ext/couchbase_ext/store.c', line 522

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

#query(*args) ⇒ Hash

Perform N1QL query to the cluster. This API is experimental and subject to change in future. Read more info at query.couchbase.com

Examples:

Simple N1QL query

connection.query('select "hello world"')
#=>
   {
       :rows => [
           [0] {
               "$1" => "hello world"
           }
       ],
       :meta => {
           "requestID" => "f0345617-f809-4b75-8340-acaa412b9f3d",
           "signature" => {
               "$1" => "string"
           },
           "results" => [],
           "status" => "success",
           "metrics" => {
               "elapsedTime" => "1.582327ms",
               "executionTime" => "1.470542ms",
               "resultCount" => 1,
               "resultSize" => 43
           }
       }
   }

create primary index

connection.query('create primary index on `travel-sample` using view')
#=>
   {
       :rows => [],
       :meta => {
           "requestID" => "597882ef-3c2b-4ac9-8f08-275fece46645",
           "signature" => nil,
             "results" => [],
              "status" => "success",
             "metrics" => {
                 "elapsedTime" => "1.550941465s",
               "executionTime" => "1.550856413s",
                 "resultCount" => 0,
                  "resultSize" => 0
           }
       }
   }

select first airline

connection.query('select * from `travel-sample` where type = "airline" limit 1')
#=> {
    :rows => [
        [0] {
            "travel-sample" => {
                "callsign" => "Orbit",
                 "country" => "United States",
                    "iata" => nil,
                    "icao" => "OBT",
                      "id" => 16932,
                    "name" => "Orbit Airlines",
                    "type" => "airline"
            }
        }
    ],
    :meta => {
        "requestID" => "f999550c-70b0-43f6-b76d-8cde03288847",
        "signature" => {
            "*" => "*"
        },
          "results" => [],
           "status" => "success",
          "metrics" => {
              "elapsedTime" => "501.048085ms",
            "executionTime" => "500.991849ms",
              "resultCount" => 1,
               "resultSize" => 303
        }
    }
  }

Parameters:

  • query (String)

    string which contains the N1QL query

Returns:

  • (Hash)

    result object with :rows and :meta keys

Since:

  • 1.3.12



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'ext/couchbase_ext/n1ql.c', line 70

VALUE
cb_bucket_query(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    lcb_N1QLPARAMS *params = lcb_n1p_new();
    lcb_CMDN1QL cmd = { 0 };
    lcb_error_t rc;
    VALUE qstr, proc, args;
    VALUE exc, rv;

    rb_scan_args(argc, argv, "1*&", &qstr, &args, &proc);

    rc = lcb_n1p_setquery(params, RSTRING_PTR(qstr), RSTRING_LEN(qstr), LCB_N1P_QUERY_STATEMENT);
    if (rc != LCB_SUCCESS) {
        rb_raise(cb_eQuery, "cannot set query for N1QL command: %s", lcb_strerror(bucket->handle, rc));
    }

    rc = lcb_n1p_mkcmd(params, &cmd);
    if (rc != LCB_SUCCESS) {
        rb_raise(cb_eQuery, "cannot construct N1QL command: %s", lcb_strerror(bucket->handle, rc));
    }

    ctx = cb_context_alloc_common(bucket, proc, 1);
    ctx->rv = rb_hash_new();
    rb_hash_aset(ctx->rv, cb_sym_rows, rb_ary_new());
    rb_hash_aset(ctx->rv, cb_sym_meta, Qnil);
    cmd.callback = n1ql_callback;
    rc = lcb_n1ql_query(bucket->handle, (void *)ctx, &cmd);
    if (rc != LCB_SUCCESS) {
        rb_raise(cb_eQuery, "cannot excute N1QL command: %s\n", lcb_strerror(bucket->handle, rc));
    }
    lcb_n1p_free(params);
    lcb_wait(bucket->handle);

    exc = ctx->exception;
    rv = ctx->rv;
    cb_context_free(ctx);
    if (exc != Qnil) {
        rb_exc_raise(exc);
    }
    exc = bucket->exception;
    if (exc != Qnil) {
        bucket->exception = Qnil;
        rb_exc_raise(exc);
    }
    return rv;
}

#reconnect(url, options = {}) ⇒ Couchbase::Bucket #reconnect(options = {}) ⇒ Couchbase::Bucket

Reconnect the bucket

Reconnect the bucket using initial configuration with optional redefinition.

Overloads:

Since:

  • 1.1.0



689
690
691
692
693
694
695
696
697
698
# File 'ext/couchbase_ext/bucket.c', line 689

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

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

    return self;
}

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

Replace the existing object in the database

Returns The CAS value of the object.

Examples:

Replacing missing key

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

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

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

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

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

    Options for operation.

Options Hash (options):

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

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

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

    Flags for storage options. Flags are ignored by the server but preserved for use by the client. For more info see #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



383
384
385
386
387
# File 'ext/couchbase_ext/store.c', line 383

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

#run(*args) {|bucket| ... } ⇒ nil

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

Use #run without block for async connection

c = Couchbase.new(:async => true)
c.run      # ensure that instance connected
c.set("foo", "bar"){|r| puts r.cas}
c.run

Parameters:

  • options (Hash)

    The options for operation for connection

Yield Parameters:

  • bucket (Bucket)

    the bucket instance

Returns:

  • (nil)

Raises:

Since:

  • 1.0.0



1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
# File 'ext/couchbase_ext/bucket.c', line 1367

VALUE
cb_bucket_run(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    VALUE args[5];

    /* it is allowed to omit block for async connections */
    if (!bucket->async) {
        rb_need_block();
    }
    args[0] = self;
    rb_scan_args(argc, argv, "01&", &args[1], &args[2]);
    args[3] = bucket->async;
    args[4] = bucket->running;
    rb_ensure(do_run, (VALUE)args, ensure_run, (VALUE)args);
    return Qnil;
}

#save_design_doc(data) ⇒ true, false

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



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/couchbase/bucket.rb', line 159

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
  rv = nil
  id = attrs.delete('_id').to_s
  attrs['language'] ||= 'javascript'
  if id !~ /\A_design\//
    rv = Result.new(:operation => :http_request,
                    :key => id,
                    :error => ArgumentError.new("'_id' key must be set and start with '_design/'."))
    yield rv if block_given?
    raise rv.error unless async?
  end
  req = make_http_request(id, :body => MultiJson.dump(attrs),
                          :method => :put, :extended => true)
  req.on_body do |res|
    rv = res
    val = MultiJson.load(res.value)
    if block_given?
      if res.success? && val['error']
        res.error = Error::View.new("save_design_doc", val['error'])
      end
      yield(res)
    end
  end
  req.continue
  unless async?
    rv.success? or raise res.error
  end
end

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

Unconditionally store the object in the Couchbase

Returns The CAS value of the object.

Examples:

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

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

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

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

More advanced multi-set using asynchronous mode

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

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

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

Force JSON document format for value

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

Use hash-like syntax to store the value

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

Use extended hash-like syntax

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

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

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

Perform optimistic locking by specifying last known CAS version

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

Perform asynchronous call

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

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

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

Parameters:

  • key (String, Symbol)

    Key used to reference the value.

  • value (Object)

    Value to be stored

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

    Options for operation.

Options Hash (options):

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

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

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

    Flags for storage options. Flags are ignored by the server but preserved for use by the client. For more info see #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.

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



279
280
281
282
283
# File 'ext/couchbase_ext/store.c', line 279

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

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

Returns 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) (defaults to: nil)

    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



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
159
160
161
# File 'ext/couchbase_ext/stats.c', line 107

VALUE
cb_bucket_stats(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    VALUE rv, exc, proc;
    lcb_error_t err;
    struct cb_params_st params;

    if (!cb_bucket_connected_bang(bucket, cb_sym_stats)) {
        return Qnil;
    }

    memset(&params, 0, sizeof(struct cb_params_st));
    rb_scan_args(argc, argv, "0*&", &params.args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    params.type = cb_cmd_stats;
    params.bucket = bucket;
    cb_params_build(&params);
    ctx = cb_context_alloc_common(bucket, proc, params.cmd.stats.num);
    err = lcb_server_stats(bucket->handle, (const void *)ctx,
            params.cmd.stats.num, params.cmd.stats.ptr);
    exc = cb_check_error(err, "failed to schedule stat request", Qnil);
    cb_params_destroy(&params);
    if (exc != Qnil) {
        cb_context_free(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += params.npayload;
    if (bucket->async) {
        cb_maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            lcb_wait(bucket->handle);
        }
        exc = ctx->exception;
        rv = ctx->rv;
        cb_context_free(ctx);
        if (exc != Qnil) {
            rb_exc_raise(exc);
        }
        exc = bucket->exception;
        if (exc != Qnil) {
            bucket->exception = Qnil;
            rb_exc_raise(exc);
        }
        return rv;
    }

    return Qnil;
}

#stopnil

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



1403
1404
1405
1406
1407
1408
1409
# File 'ext/couchbase_ext/bucket.c', line 1403

VALUE
cb_bucket_stop(VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    lcb_breakout(bucket->handle);
    return Qnil;
}

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

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:

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

    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:

  • #touch(keys) {|ret| ... } ⇒ Hash

    Returns 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



124
125
126
127
128
129
130
131
132
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'ext/couchbase_ext/touch.c', line 124

VALUE
cb_bucket_touch(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    VALUE rv, proc, exc;
    lcb_error_t err;
    struct cb_params_st params;

    if (!cb_bucket_connected_bang(bucket, cb_sym_touch)) {
        return Qnil;
    }

    memset(&params, 0, sizeof(struct cb_params_st));
    rb_scan_args(argc, argv, "0*&", &params.args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    rb_funcall(params.args, cb_id_flatten_bang, 0);
    params.type = cb_cmd_touch;
    params.bucket = bucket;
    cb_params_build(&params);
    ctx = cb_context_alloc_common(bucket, proc, params.cmd.touch.num);
    ctx->quiet = params.cmd.touch.quiet;
    err = lcb_touch(bucket->handle, (const void *)ctx,
            params.cmd.touch.num, params.cmd.touch.ptr);
    cb_params_destroy(&params);
    exc = cb_check_error(err, "failed to schedule touch request", Qnil);
    if (exc != Qnil) {
        cb_context_free(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += params.npayload;
    if (bucket->async) {
        cb_maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            lcb_wait(bucket->handle);
        }
        exc = ctx->exception;
        rv = ctx->rv;
        cb_context_free(ctx);
        if (exc != Qnil) {
            rb_exc_raise(exc);
        }
        exc = bucket->exception;
        if (exc != Qnil) {
            bucket->exception = Qnil;
            rb_exc_raise(exc);
        }
        if (params.cmd.touch.num > 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;
        }
    }
}

#unlock(key, options = {}) ⇒ true, false #unlock(keys) {|ret| ... } ⇒ Hash

Unlock key

The unlock method allow you to unlock key once locked by #get with :lock option.

Overloads:

  • #unlock(key, options = {}) ⇒ true, false

    Returns true if the operation was successful and false otherwise.

    Examples:

    Unlock the single key

    val, _, cas = c.get("foo", :lock => true, :extended => true)
    c.unlock("foo", :cas => cas)

    Parameters:

    • key (String, Symbol)

      Key used to reference the value.

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

      Options for operation.

    Options Hash (options):

    • :cas (Fixnum)

      The CAS value must match the current one from the storage.

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

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

    Returns:

    • (true, false)

      true if the operation was successful and false otherwise.

    Raises:

  • #unlock(keys) {|ret| ... } ⇒ Hash

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

    Examples:

    Unlock several keys

    c.unlock("foo" => cas1, :bar => cas2) #=> {"foo" => true, "bar" => true}

    Unlock several values in async mode

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

    Parameters:

    • keys (Hash)

      The Hash where keys represent the keys in the database, values – the CAS for corresponding key.

    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 unlock operation (true if the operation was successful and false otherwise)

Since:

  • 1.2.0



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'ext/couchbase_ext/unlock.c', line 114

VALUE
cb_bucket_unlock(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    VALUE rv, proc, exc;
    lcb_error_t err;
    struct cb_params_st params;

    if (!cb_bucket_connected_bang(bucket, cb_sym_unlock)) {
        return Qnil;
    }

    memset(&params, 0, sizeof(struct cb_params_st));
    rb_scan_args(argc, argv, "0*&", &params.args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    rb_funcall(params.args, cb_id_flatten_bang, 0);
    params.type = cb_cmd_unlock;
    params.bucket = bucket;
    cb_params_build(&params);
    ctx = cb_context_alloc_common(bucket, proc, params.cmd.unlock.num);
    ctx->quiet = params.cmd.unlock.quiet;
    err = lcb_unlock(bucket->handle, (const void *)ctx,
            params.cmd.unlock.num, params.cmd.unlock.ptr);
    cb_params_destroy(&params);
    exc = cb_check_error(err, "failed to schedule unlock request", Qnil);
    if (exc != Qnil) {
        cb_context_free(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += params.npayload;
    if (bucket->async) {
        cb_maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            lcb_wait(bucket->handle);
        }
        exc = ctx->exception;
        rv = ctx->rv;
        cb_context_free(ctx);
        if (exc != Qnil) {
            rb_exc_raise(exc);
        }
        exc = bucket->exception;
        if (exc != Qnil) {
            bucket->exception = Qnil;
            rb_exc_raise(exc);
        }
        if (params.cmd.unlock.num > 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;
        }
    }
}

#version {|ret| ... } ⇒ Hash

Returns versions of the server for each node in the cluster

Returns 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



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'ext/couchbase_ext/version.c', line 88

VALUE
cb_bucket_version(int argc, VALUE *argv, VALUE self)
{
    struct cb_bucket_st *bucket = DATA_PTR(self);
    struct cb_context_st *ctx;
    VALUE rv, exc, proc;
    lcb_error_t err;
    struct cb_params_st params;

    if (!cb_bucket_connected_bang(bucket, cb_sym_version)) {
        return Qnil;
    }

    memset(&params, 0, sizeof(struct cb_params_st));
    rb_scan_args(argc, argv, "0*&", &params.args, &proc);
    if (!bucket->async && proc != Qnil) {
        rb_raise(rb_eArgError, "synchronous mode doesn't support callbacks");
    }
    params.type = cb_cmd_version;
    params.bucket = bucket;
    cb_params_build(&params);
    ctx = cb_context_alloc_common(bucket, proc, params.cmd.version.num);
    err = lcb_server_versions(bucket->handle, (const void *)ctx,
            params.cmd.version.num, params.cmd.version.ptr);
    exc = cb_check_error(err, "failed to schedule version request", Qnil);
    cb_params_destroy(&params);
    if (exc != Qnil) {
        cb_context_free(ctx);
        rb_exc_raise(exc);
    }
    bucket->nbytes += params.npayload;
    if (bucket->async) {
        cb_maybe_do_loop(bucket);
        return Qnil;
    } else {
        if (ctx->nqueries > 0) {
            /* we have some operations pending */
            lcb_wait(bucket->handle);
        }
        exc = ctx->exception;
        rv = ctx->rv;
        cb_context_free(ctx);
        if (exc != Qnil) {
            rb_exc_raise(exc);
        }
        exc = bucket->exception;
        if (exc != Qnil) {
            bucket->exception = Qnil;
            rb_exc_raise(exc);
        }
        return rv;
    }
}