Introduction

This guide provides information for developers who want to use the Couchbase C SDK to build applications that use Couchbase Server.

Getting Started

Now that you’ve installed Couchbase and have probably created a cluster of Couchbase servers, you will need to use a client library to save and retrieve data from the cluster. The Couchbase C client library, also known as libcouchbase, is one way of doing so.

Here’s a quick outline of what you’ll learn in this chapter:

  • How to obtain the client library.

  • How to build the client library from source (optional).

  • Write a simple program to demonstrate connecting to Couchbase and saving some data.

To explore other C SDK methods, please refer to the Couchbase C SDK Language reference.

Downloading the Couchbase Client Library

Download the latest client library from http://www.couchbase.com/communities/c-client-library. It is available as a source archive in both .zip and .tar.gz formats.

Installing from Source: Linux and Mac OS X

Installation is like many common libraries, following the ./configure, make, make install conventions.

For libvbucket, extract the archive then cd into the directory and run:

shell> ./configure
shell> make install

Standard configure options such as --prefix can be passed to the configure command. Running./configure with –help with provide additional information on configuration options.

For libcouchbase, extract the archive, then cd into the directory and run:

shell> ./configure CPPFLAGS="-I/opt/couchbase/include" --disable-couchbasemock
shell> make install

The --disable-couchbasemock simply disables some tests which are common during development of libcouchbase, but not required when installing a release.

Installing from Source: Microsoft Windows

Building and installing on Microsoft Windows depends on nmake and tools in Microsoft Visual Studio 2010.

Open the Visual Studio Command Prompt, and navigate to the directory for the extracted archive for libvbucket. The NMakefile defines an INSTALL variable as C:\local. Edit the NMakefile if you wish to change the installation location. Then build and install libvbucket:

shell> nmake -f NMakefile install

Because it uses memcached binary protocol, libcouchbase requires header files from the memcached project. After obtaining the memcached source, copy memcached.h and protocol_binary.h into c:\local\include\memcached.

Then navigate to the directory for libcouchbase. Edit the NMakefile if you wish to change the installation location, then build and install libcouchbase:

shell> nmake -f NMakefile install

Installing on CentOS/ReHat

Installation on CentOS/RedHat Linux consists of adding a set of RPMs.

Installing on Ubuntu

Installation on Ubuntu Linux consists of adding a set of.deb packages. After downloading the packages, simply add the packages with the dpkg command. There is a dependent order between the packages, as libcouchbase depends on libvbucket.

Also, note that as is common with Ubuntu packaging, the library is broken up into three separate pieces. One is the library itself. The next is the -dev package which contains header files needed during development. The final package contains the debug symbols, which may be useful when using a debugger during development.

The most basic of installs is just a matter of installing libvbucket1 and libcouchbase with its header files and debug symbols.

shell> sudo dpkg -i libvbucket1-1_amd64.deb
shell> sudo dpkg -i libcouchbase1-1_amd64.deb
shell> sudo dpkg -i libcouchbase-dev-1_amd64.deb
shell> sudo dpkg -i libcouchbase1-dbg-1_amd64.deb

Hello C Couchbase

This chapter will get you started with Couchbase Server and the Couchbase C SDK, libcouchbase.

This section assumes you have downloaded and set up a compatible version of Couchbase Server and have at least one instance of Couchbase Server and one data bucket established. If you need to set up these items, you can do with the Couchbase Administrative Console, or Couchbase Command-Line Interface (CLI), or the Couchbase REST API. For information and instructions, see:

After you have your Couchbase Server set up and you have installed the needed client libraries, you can compile and run the following basic program.

/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Example "hello Couchbase" libcouchbase program.
 *
 * @author Matt Ingenthron
 */

#include <getopt.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include <libcouchbase/couchbase.h>

/* the callback invoked by the library when receiving an error */
static void error_callback(libcouchbase_t instance,
                           libcouchbase_error_t error,
                           const char *errinfo)
{
    (void)instance;
    fprintf(stderr, "Error %d", error);
    if (errinfo) {
        fprintf(stderr, ": %s", errinfo);
    }
    fprintf(stderr, "\n");
    exit(EXIT_FAILURE);
}

/* the callback invoked by the library when receiving a get response */
static void get_callback(libcouchbase_t instance,
                         const void *cookie,
                         libcouchbase_error_t error,
                         const void *key, size_t nkey,
                         const void *bytes, size_t nbytes,
                         uint32_t flags, uint64_t cas)
{
    (void)instance; (void)cookie; (void)cas;
    fwrite(bytes, 1, nbytes, stdout);
    fprintf(stdout, "\n");
    fflush(stdout);
    fprintf(stderr, "Get callback received\n");
}


int main(int argc, char **argv)
{
    libcouchbase_t instance;    /* our libcouchbase instance */
    libcouchbase_error_t oprc;  /* for checking various responses */

    const char *host = "localhost:8091";
    const char *username = NULL;
    const char *passwd = NULL;
    const char *bucket = "default";

    instance = libcouchbase_create(host, username,
                                   passwd, bucket, NULL);
    if (instance == NULL) {
        fprintf(stderr, "Failed to create libcouchbase instance\n");
        return 1;
    }

    (void)libcouchbase_set_error_callback(instance, error_callback);
    (void)libcouchbase_set_get_callback(instance, get_callback);

    if (libcouchbase_connect(instance) != LIBCOUCHBASE_SUCCESS) {
        fprintf(stderr, "Failed to connect libcouchbase instance to server\n");
        return 1;
    }

    /* Wait for the connect to compelete */
    libcouchbase_wait(instance);

    /* A simple document we want to create */
    char *key = "hello";
    char *doc = "{ \"message\": \"world\" }";

    /* Store doc to in the system */
    oprc = libcouchbase_store(instance,
                              NULL,
                              LIBCOUCHBASE_SET,
                              key, /* the key or _id of the document */
                              strlen(key), /* the key length */
                              doc,
                              strlen(doc), /* length of */
                              0,  /* flags,  */
                              0,  /* expiration */
                              0); /* and CAS values, see API reference */

    if (oprc != LIBCOUCHBASE_SUCCESS) {
        fprintf(stderr, "Failed to create hello store operation.\n");
        return 1;
    }

    /* Wait for the operation to compelete */
    libcouchbase_wait(instance);

    oprc = libcouchbase_get_last_error(instance);
    if (oprc == LIBCOUCHBASE_SUCCESS) {
        fprintf(stderr, "Successfully set hello.\n");
    } else {
        fprintf(stderr, "Could not set hello.  Error received is %d\n", oprc);
        return 1;
    }

    /* Now go and get "hello" */
    const char* keys[1];
    size_t nkey[1];
    keys[0] = key;
    nkey[0] = strlen(key);
    oprc = libcouchbase_mget(instance,
                             NULL,
                             1,
                             (const void*const*)keys,
                             nkey,
                             NULL);

    if (oprc != LIBCOUCHBASE_SUCCESS) {
        fprintf(stderr, "Failed to create hello mget operation.\n");
        return 1;
    }

    /* Wait for the operation to compelete */
    libcouchbase_wait(instance);

    return 0;
}

Tutorial

This tutorial assumes you have installed libcouchbase on your systems per the installation instructions in the Getting Started section of this guide. Because the method of building a program based on libcouchbase may vary between Linux/Mac OS and Windows, this tutorial will focus on the components of the program rather than how to build it.

If you need to set up a server node or data bucket, you can do with the Couchbase Administrative Console, or Couchbase Command-Line Interface (CLI), or the Couchbase REST API. For information and instructions, see:

After you have your Couchbase Server set up and you have installed the needed client libraries, you can compile and run the following basic program.

Simple Example

Before getting into a more complex example of the programming model to this library, we will walk through simple, straightforward example of a program which builds with libcouchbase, connects to a server, sets and gets a value:

/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2010, 2011 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Example program using libcouchbase_tap_cluster.
 * @author Trond Norbye
 * @todo add documentation
 */
#include "config.h"
#include <getopt.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include <libcouchbase/couchbase.h>

#ifdef WIN32
#define PRIu64 "llu"

static int isatty(int a) {
    (void)a;
    return 1;
}

static char *getpass(const char *prompt)
{
    size_t len;
    static char buffer[1024];
    fprintf(stdout, "%s", prompt);
    fflush(stdout);

    if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
        return NULL;
    }

    len = strlen(buffer) - 1;
    while (buffer[len] == '\r' || buffer[len] == '\n') {
        buffer[len] = '\0';
        --len;
    }

    return buffer;
}
#endif

static void usage(char cmd, const void *arg, void *cookie);
static void set_char_ptr(char cmd, const void *arg, void *cookie) {
    const char **myptr = cookie;
    *myptr = arg;
    (void)cmd;
}

const char *host = "localhost:8091";
const char *username = NULL;
const char *passwd = NULL;
const char *bucket = NULL;
const char *filename = "-";

static void set_auth_data(char cmd, const void *arg, void *cookie) {
    (void)cmd;
    (void)cookie;
    username = arg;
    if (isatty(fileno(stdin))) {
        char prompt[80];
        snprintf(prompt, sizeof(prompt), "Please enter password for %s: ", username);
        passwd = getpass(prompt);
        if (passwd == NULL) {
            exit(EXIT_FAILURE);
        }
    } else {
        char buffer[80];
        size_t len;
        if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
            exit(EXIT_FAILURE);
        }
        len = strlen(buffer) - 1;
        while (len > 0 && isspace(buffer[len])) {
            buffer[len] = '\0';
            --len;
        }
        if (len == 0) {
            exit(EXIT_FAILURE);
        }
        passwd = strdup(buffer);
    }
}

typedef void (*OPTION_HANDLER)(char cmd, const void *arg, void *cookie);
static struct {
    const char *name;
    const char *description;
    int argument;
    char letter;
    OPTION_HANDLER handler;
    void *cookie;
} my_options[256];

static void setup_options(void)
{
    my_options['?'].name = "help";
    my_options['?'].description = "\t-?\tPrint program usage information";
    my_options['?'].argument = 0;
    my_options['?'].letter = '?';
    my_options['?'].handler = usage;
    my_options['u'].name = "username";
    my_options['u'].description = "\t-u nm\tSpecify username";
    my_options['u'].argument = 1;
    my_options['u'].letter = 'u';
    my_options['u'].handler = set_auth_data;
    my_options['h'].name = "host";
    my_options['h'].description = "\t-h host\tHost to read configuration from";
    my_options['h'].argument = 1;
    my_options['h'].letter = 'h';
    my_options['h'].handler = set_char_ptr;
    my_options['h'].cookie = (void*)&host;
    my_options['b'].name = "bucket";
    my_options['b'].description = "\t-b bucket\tThe bucket to connect to";
    my_options['b'].argument = 1;
    my_options['b'].letter = 'b';
    my_options['b'].handler = set_char_ptr;
    my_options['b'].cookie = (void*)&bucket;
    my_options['o'].name = "file";
    my_options['o'].description = "\t-o filename\tSend the output to this file";
    my_options['o'].argument = 1;
    my_options['o'].letter = 'o';
    my_options['o'].handler = set_char_ptr;
    my_options['o'].cookie = (void*)&filename;
}

/**
 * Handle all of the command line options the user passed on the command line.
 * Please note that this function will set optind to point to the first option
 * @param argc Argument count
 * @param argv Argument vector
 */
static void handle_options(int argc, char **argv) {
    struct option opts[256];
    int ii = 0;
    char shortopts[128];
    int jj = 0;
    int kk = 0;
    int c;

    memset(opts, 0, sizeof(opts));
    memset(shortopts, 0, sizeof(shortopts));
    setup_options();

    for (ii = 0; ii < 256; ++ii) {
        if (my_options[ii].name != NULL) {
            opts[jj].name = (char*)my_options[ii].name;
            opts[jj].has_arg = my_options[ii].argument ? required_argument : no_argument;
            opts[jj].val = my_options[ii].letter;

            shortopts[kk++] = (char)opts[jj].val;
            if (my_options[ii].argument) {
                shortopts[kk++] = ':';
            }
        }
    }

    while ((c = getopt_long(argc, argv, shortopts, opts, NULL)) != EOF) {
        if (my_options[c].handler != NULL) {
            my_options[c].handler((char)c, optarg, my_options[c].cookie);
        } else {
            usage((char)c, NULL, NULL);
        }
    }
}

FILE *output;

static void tap_mutation(libcouchbase_t instance,
                         const void *cookie,
                         const void *key,
                         size_t nkey,
                         const void *data,
                         size_t nbytes,
                         uint32_t flags,
                         uint32_t exp,
                         const void *es,
                         size_t nes)
{
    fwrite(key, nkey, 1, output);
    fprintf(output, " 0x%04X\r\n", (unsigned int)nbytes);
    (void)instance;
    (void)cookie;
    (void)data;
    (void)flags;
    (void)exp;
    (void)es;
    (void)nes;
}

static void error_callback(libcouchbase_t instance,
                           libcouchbase_error_t error,
                           const char *errinfo)
{
    (void)instance;
    fprintf(stderr, "Error %d", error);
    if (errinfo) {
        fprintf(stderr, ": %s", errinfo);
    }
    fprintf(stderr, "\n");
    exit(EXIT_FAILURE);
}

int main(int argc, char **argv)
{
    struct libcouchbase_io_opt_st *io;
    libcouchbase_t instance;

    handle_options(argc, argv);

    if (strcmp(filename, "-") == 0) {
        output = stdout;
    } else {
        output = fopen(filename, "w");
        if (output == NULL) {
            fprintf(stderr, "Failed to open %s: %s\n", filename,
                    strerror(errno));
            return 1;
        }
    }

    io = libcouchbase_create_io_ops(LIBCOUCHBASE_IO_OPS_DEFAULT, NULL, NULL);
    if (io == NULL) {
        fprintf(stderr, "Failed to create IO instance\n");
        return 1;
    }
    instance = libcouchbase_create(host, username,
                                                  passwd, bucket, io);
    if (instance == NULL) {
        fprintf(stderr, "Failed to create libcouchbase instance\n");
        return 1;
    }

    (void)libcouchbase_set_error_callback(instance, error_callback);

    if (libcouchbase_connect(instance) != LIBCOUCHBASE_SUCCESS) {
        fprintf(stderr, "Failed to connect libcouchbase instance to server\n");
        return 1;
    }

    /* Wait for the connect to compelete */
    libcouchbase_wait(instance);

    (void)libcouchbase_set_tap_mutation_callback(instance, tap_mutation);
    libcouchbase_tap_cluster(instance, NULL, NULL, 1);

    return 0;
}

static void usage(char cmd, const void *arg, void *cookie)
{
    int ii;
    (void)cmd;
    (void)arg;
    (void)cookie;

    fprintf(stderr, "Usage: ./memdump [options]\n");
    for (ii = 0; ii < 256; ++ii) {
        if (my_options[ii].name != NULL) {
            fprintf(stderr, "%s\n", my_options[ii].description);
        }
    }
    exit(EXIT_FAILURE);
}

Additional Resources

In addition to the other sections of this manual, namely the Getting Started guide and the API reference, a libcouchbase distribution includes an examples directory and a tools directory, each of which show simple Couchbase tools and and example libcouchbase programs.

On Linux you may find these examples in TODO…

C Function Summary

libcouchbase provides a well defined API for accessing the data stored in a Couchbase cluster. A summary of the supported methods are listed in Couldn’t resolve xref tag: table-couchbase-sdk-c-summary.

API Call lcb_arithmetic (lcb_t instance, const void* cookie, const void* key, size_t nkey, int64_t delta, time_t exptime, bool create, uint64_t initial)
Asynchronous no
Description Spool an arithmetic operation to the cluster. The operation may be sent immediately, but you won’t be sure (or get the result) until you run the event loop (or call lcb_wait).
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
const void* key An identifier in the database
size_t nkey Number of bytes in the key
int64_t delta The delta to increment/decrement
time_t exptime The expiry time for the object. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).
bool create Should the key be created if it does not exist?
uint64_t initial The initial value for the key if created
Errors
LCB_ETMPFAIL No vbucket configuration available
LCB_SUCCESS Command successfully scheduled

API Call lcb_arithmetic_by_key (lcb_t instance, const void* cookie, const void* hashkey, size_t nhashkey, const void* key, size_t nkey, int64_t delta, time_t exptime, bool create, uint64_t initial)
Asynchronous no
Description Spool an arithmetic operation to the cluster, but use another key to locate the server. The operation may be sent immediately, but you won’t be sure (or get the result) until you run the event loop (or call lcb_wait).
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
const void* hashkey This alternate hashkey allows a client application to group a set of unique keys together to a given server though the keys themselves may be unique. For example, you may wish to use the hashkey “user” for the two data keys “user:name” and “user:birthdate”. Note that not all clients support this option so it may not be interoperable between clients.
size_t nhashkey The number of bytes in the alternative key
const void* key An identifier in the database
size_t nkey Number of bytes in the key
int64_t delta The delta to increment/decrement
time_t exptime The expiry time for the object. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).
bool create Should the key be created if it does not exist?
uint64_t initial The initial value for the key if created
Errors
LCB_ETMPFAIL No vbucket configuration available
LCB_SUCCESS Command successfully scheduled

API Call lcb_connect (lcb_t instance)
Asynchronous no
Description Initiate a connect attempt to the Couchbase cluster to get the serverlist. Please note that this method is asynchronous, so you need to call lcb_wait to wait for the method to compete.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
Errors
LCB_NETWORK_ERROR If an IO error occurred
LCB_SUCCESS Command successfully scheduled
LCB_UNKNOWN_HOST Failed to lookup host name

API Call lcb_create (const char* host, const char* user, const char* passwd, const char* bucket, lcb_io_ops_t* iops)
Asynchronous no
Description lcb_create allocates and initializes an instance of lcb. No connection attempt is at this time. host may be specified as “host:port” and is the REST interface port for the cluster (default: “localhost:8091”). user and password are the username/password combination you want to authenticate as. bucket specifies the bucket you would like to connect to. opps is the io operation structure to use (see lcb_create_io_ops). The bucket name and the username are commonly the same.
Returns lcb_t ( The handle to the couchbase instance. )
Arguments
const char* host Hostname
const char* user Username
const char* passwd Password
const char* bucket Bucket name
lcb_io_ops_t* iops I/O operation structure
Errors
lcb_t an instance of lcb on success
NULL on failure

API Call lcb_create_io_ops ()
Asynchronous no
Description todo: fixme
Returns (none)
Arguments
None

API Call lcb_destroy (lcb_t instance)
Asynchronous no
Description lcb_destory release all allocated resources and invalidates the lcb instance.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_disable_timings (lcb_t instance)
Asynchronous no
Description Stop recording of timing metrics and release all resources allocated for timing metrics.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_enable_timings (lcb_t instance)
Asynchronous no
Description Start recording of timing metrics for operations against the cluster.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_flush (lcb_t instance, const void* cookie)
Asynchronous no
Description lcb_flush may be used to remove all key/value pairs from the entire cluster.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
Errors
LCB_ETMPFAIL No vbucket configuration available
LCB_SUCCESS Command successfully scheduled

API Call lcb_get_cookie (lcb_t instance)
Asynchronous no
Description Each libcochbase instance may have a single pointer (cookie) associated with it. libcouchbaes_get_cookie retrieves this cookie.
Returns const void* ( Pointer to data )
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_get_last_error (lcb_t instance)
Asynchronous no
Description Returns the last error that was seen within libcoubhase
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_get_timings (lcb_t instance)
Asynchronous no
Description Retrieve the timing metrics from lcb. TODO fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_mget (lcb_t instance, const void* cookie, size_t num_keys, const void * const* keys, const size_t* nkeys, const time_t* exp)
Asynchronous no
Description Get a number of values from the cache. You need to run the event loop yourself to retrieve the data. You might want to alter the expiry time for the object you’re fetching, and to do so you should specify the new expiry time in the exp parameter. To use an ordinary mget use NULL for the exp parameter.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
size_t num_keys Number of keys
const void * const* keys Pointer to the array of keys
const size_t* nkeys Pointer to the array with the length of the keys
const time_t* exp Pointer to the expiry time

API Call lcb_mget_by_key (lcb_t instance, const void* cookie, const void* hashkey, size_t nhashkey, size_t num_keys, const void * const* keys, const size_t* nkeys, const time_t* exp)
Asynchronous no
Description Get a number of values from the cache. You need to run the event loop yourself (or call lcb_execute) to retrieve the data. You might want to alter the expiry time for the object you’re fetching, and to do so you should specify the new expiry time in the exp parameter. To use an ordinary mget use NULL for the exp parameter. lcb_mget_by_key differs from lcb_mget that you may use another key to look up the server to retrieve the objects from.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
const void* hashkey This alternate hashkey allows a client application to group a set of unique keys together to a given server though the keys themselves may be unique. For example, you may wish to use the hashkey “user” for the two data keys “user:name” and “user:birthdate”. Note that not all clients support this option so it may not be interoperable between clients.
size_t nhashkey The number of bytes in the alternative key
size_t num_keys Number of keys
const void * const* keys Pointer to the array of keys
const size_t* nkeys Pointer to the array with the length of the keys
const time_t* exp Pointer to the expiry time

API Call lcb_mtouch (lcb_t instance, const void* cookie, size_t num_keys, const void * const* keys, const size_t* nkeys, const time_t* exp)
Asynchronous no
Description Touch (set expiration time) on a number of values in the cache You need to run the event loop yourself (or call lcb_wait) to retrieve the results of the operations.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
size_t num_keys Number of keys
const void * const* keys Pointer to the array of keys
const size_t* nkeys Pointer to the array with the length of the keys
const time_t* exp Pointer to the expiry time

API Call lcb_mtouch_by_key (lcb_t instance, const void* cookie, const void* hashkey, size_t nhashkey, const void * const* keys, const size_t* nkeys, const time_t* exp)
Asynchronous no
Description Touch (set expiration time) on a number of values in the cache You need to run the event loop yourself (or call lcb_wait) to retrieve the results of the operations. lcb_mtouch_by_key differs from lcb_mtouch that you may use another key to look up the server for the keys.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
const void* hashkey This alternate hashkey allows a client application to group a set of unique keys together to a given server though the keys themselves may be unique. For example, you may wish to use the hashkey “user” for the two data keys “user:name” and “user:birthdate”. Note that not all clients support this option so it may not be interoperable between clients.
size_t nhashkey The number of bytes in the alternative key
const void * const* keys Pointer to the array of keys
const size_t* nkeys Pointer to the array with the length of the keys
const time_t* exp Pointer to the expiry time

API Call lcb_remove (lcb_t instance, const void* cookie, const void* key, size_t nkey, uint64_t cas)
Asynchronous no
Description Spool a remove operation to the cluster. The operation may be sent immediately, but you won’t be sure (or get the result) until you run the event loop (or call lcb_wait).
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
const void* key An identifier in the database
size_t nkey Number of bytes in the key
uint64_t cas The cas value for an object 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.

API Call lcb_remove_by_key (lcb_t instance, const void* cookie, const void* hashkey, size_t nhashkey, const void* key, size_t nkey, uint64_t cas)
Asynchronous no
Description Spool a remove operation to the cluster. The operation may be sent immediately, but you won’t be sure (or get the result) until you run the event loop (or call lcb_wait).
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
const void* hashkey This alternate hashkey allows a client application to group a set of unique keys together to a given server though the keys themselves may be unique. For example, you may wish to use the hashkey “user” for the two data keys “user:name” and “user:birthdate”. Note that not all clients support this option so it may not be interoperable between clients.
size_t nhashkey The number of bytes in the alternative key
const void* key An identifier in the database
size_t nkey Number of bytes in the key
uint64_t cas The cas value for an object 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.

API Call lcb_server_stats (lcb_t instance, const void* cookie, const void* key, size_t nkey)
Asynchronous no
Description Request server statistics. Without a key specified the server will respond with a “default” set of statistical information. Each statistic is returned in its own packet (key contains the name of the statistical item and the body contains the value in ASCII format). The sequence of return packets is terminated with a packet that contains no key and no value. The command will signal about transfer completion by passing NULL as the server endpoint and 0 for key length. Note that key length will be zero when some server responds with error. In the latter case server endpoint argument will indicate the server address.
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
const void* key An identifier in the database
size_t nkey Number of bytes in the key

API Call lcb_set_arithmetic_callback (lcb_t instance, lcb_error_callback callback)
Asynchronous no
Description Specify the callback to be used for all arithmetic operations. The callback will be called whenever the operation completes, and the parameters to the callback will describe the result of the operation.
Returns ()
Arguments
lcb_t instance The handle to the couchbase instance.
lcb_error_callback callback The callback function

API Call lcb_set_cookie (lcb_t instance, const void* cookie)
Asynchronous no
Description Each libcochbase instance may have a single pointer (cookie) associated with it.
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.

API Call lcb_set_error_callback (lcb_t instance, lcb_error_callback callback)
Asynchronous no
Description Set the callback function to be used by lcb to report errors back to the client. Due to the asyncronous nature of lcb errors may occur outside of the normal access pattern and such problems will be reported through this error handler.
Returns ()
Arguments
lcb_t instance The handle to the couchbase instance.
lcb_error_callback callback The callback function

API Call lcb_set_flush_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_get_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_remove_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_stat_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_storage_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_tap_deletion_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_tap_flush_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_tap_mutation_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_tap_opaque_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_tap_vbucket_set_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_set_touch_callback (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_store (lcb_t instance, const void* cookie, lcb_storage_t store_operation, const void* key, size_t nkey, const void* bytes, size_t nbytes, flags, time_t exptime, uint64_t cas)
Asynchronous no
Description Spool a store operation to the cluster. The operation may be sent immediately, but you won’t be sure (or get the result) until you run the event loop (or call lcb_wait).
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
lcb_storage_t store_operation The kind of storage operation (set/replace/add etc.)
const void* key An identifier in the database
size_t nkey Number of bytes in the key
const void* bytes A pointer to a memory area containing data
size_t nbytes Number of bytes used
flags
time_t exptime The expiry time for the object. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).
uint64_t cas The cas value for an object 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.

API Call lcb_store_by_key (lcb_t instance, const void* cookie, lcb_storage_t store_operation, const void* hashkey, size_t nhashkey, const void* key, size_t nkey, const void* bytes, size_t nbytes, flags, time_t exptime, uint64_t cas)
Asynchronous no
Description Spool a store operation to the cluster. The operation may be sent immediately, but you won’t be sure (or get the result) until you run the event loop (or call lcb_wait).
Returns lcb_error_t ( lcb instance )
Arguments
lcb_t instance The handle to the couchbase instance.
const void* cookie This is a cookie the client may attach to all requests that will be included in all callbacks. It is not required and may be NULL if you have no need for it.
lcb_storage_t store_operation The kind of storage operation (set/replace/add etc.)
const void* hashkey This alternate hashkey allows a client application to group a set of unique keys together to a given server though the keys themselves may be unique. For example, you may wish to use the hashkey “user” for the two data keys “user:name” and “user:birthdate”. Note that not all clients support this option so it may not be interoperable between clients.
size_t nhashkey The number of bytes in the alternative key
const void* key An identifier in the database
size_t nkey Number of bytes in the key
const void* bytes A pointer to a memory area containing data
size_t nbytes Number of bytes used
flags
time_t exptime The expiry time for the object. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from the epoch).
uint64_t cas The cas value for an object 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.

API Call lcb_strerror (lcb_t instance)
Asynchronous no
Description Convert the error code to human readable form. @todo fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_tap_cluster (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_tap_filter_create (lcb_t instance)
Asynchronous no
Description tap filters are on the client side only, so data still needs to be transferred across the network @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_tap_filter_destroy (lcb_t instance)
Asynchronous no
Description Invalidate the filter.. @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_tap_filter_get_backfill (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_tap_filter_get_keys_only (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_tap_filter_set_backfill (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_tap_filter_set_keys_only (lcb_t instance)
Asynchronous no
Description @fixme
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

API Call lcb_wait (lcb_t instance)
Asynchronous no
Description lcb_wait cause the calling thread to block and wait until all spooled operations (and their callbacks) have completed.
Returns (none)
Arguments
lcb_t instance The handle to the couchbase instance.

Appendix: Release Notes

The following sections provide release notes for individual release versions of Couchbase Client Library C. To browse or submit new issaues, see Couchbase Client Library C Issues Tracker.

Release Notes for Couchbase Client Library C 1.0.7 GA (12 October 2012)

New Features and Behavior Changes in 1.0.7

  • Extract cbc tool into separate package (DEB/RPM) with -bin suffix.

Release Notes for Couchbase Client Library C 1.0.6 GA (30 August 2012)

Fixes in 1.0.6

  • Release ringbuffer in libcouchbase_purge_single_server()

    Issues : CCBC-92

Release Notes for Couchbase Client Library C 1.0.5 GA (15 August 2012)

Fixes in 1.0.5

  • Fix switching to backup node in case of server outage

    Issues : CCBC-91

  • Reset timer for commands with NOT_MY_VBUCKET response

    Issues : CCBC-91

Release Notes for Couchbase Client Library C 1.0.4 GA (01 June 2012)

Fixes in 1.0.4

  • Several fixes related to tests and topology changes in corner conditions were added, in additional to the items described below.

  • A hang could occur in libcouchbase_wait() after the timeout period.

    Issues : CCBC-62

  • Timeouts can occur during topology changes, rather than be correctly retried.

    Issues : CCBC-64

  • A small memory leak can occur with frequent calls to libcouchbase_create() and libcouchbase_destroy()

    Issues : CCBC-65

Release Notes for Couchbase Client Library C 1.0.3 GA (02 May 2012)

Fixes in 1.0.3

  • In addition to the buffer overflow (CCBC-33) fixes for buffer handling in the event of a server being disconnected have been integrated.

  • A fix for a buffer overflow with the supplied password as reported in RCBC-33 has been integrated. While it is a buffer overflow issue, this is not considered to be a possible security issue because the password to the bucket is not commonly supplied by an untrusted source.

    Issues : CCBC-33

Release Notes for Couchbase Client Library C 1.0.2 GA (06 March 2012)

Fixes in 1.0.2

  • The source will now emit deb packages and apt repositories are available.

    Issues : CCBC-31

  • Support for Windows via Microsoft Visual C 9 has been added to this version.

    Support for multiple bootstrap URLs has now been added. This will ensure that if one node of the cluster becomes unaavilable for some reason and the client becomes unavailable, it can still bootstrap off of remaining nodes in the cluster. Host/port combinations are provided to the libcouchbase_create() function semicolon delimited. See the header file in libcouchbase/couchbase.h for more usage information.

    Several fixes and enhancements for the example application, cbc, have been included. Now cbc supports better usage messages, standard out support for cp, and timeouts.

Release Notes for Couchbase Client Library C 1.0.1 GA (13 February 2012)

Fixes in 1.0.1

  • A fix to allow the client library to failover automatically to other nodes when the initial bootstrap node becomes unavailable has been added. All users are recommended to upgrade for this fix.

  • Operations will now timeout rather than hang forever in some failure scenarios.

  • Release 1.0.1 of the Couchbase C Client Library is a rollup maintenance covering issues discovered subsequent to the 1.0.0 release.

    Error handling is better in a number of corner conditions such as during tests, when shutting down, handling timeouts during initial connection, minor memory-handling errors with libevent

    Support for building libcouchbase as static to support embedding has been added. This approach isn’t encouraged, but makes sense in some cases.

    Support for building libcouchbase without a C++ compiler has been added, simplifying some environments where it will only be used from C.

  • A fix address incorrect SASL authentication handling when SASL authentication is already underway was integrated.

  • A fix to allow the client library to handle retrying a given operation in the case that the cluster has gone through a topology change has been integrated. Without this fix, software using this library can receive unexpected errors.

Release Notes for Couchbase Client Library C 1.0.0 GA (22 January 2012)

New Features and Behavior Changes in 1.0.0

  • This is the first stable release of the Couchbase C Client Library. It is a callback based C client library designed to work with Couchbase Server. It is frequently used when building higher level client libraries.

    Known client libraries based on this one include the Couchbase Ruby, the Couchbase PHP library and an experimental Perl library.

  • Add make targets to build RPM and DEB packages

  • Aggregate flush responses

  • Allow libcouchbase build with libevent 1.x (verified for 1.4.14)

  • Allow config for cbc tool to be read from.cbcrc

    Issues : CCBC-37

  • Remove <memcached/vbucket.h> dependency

  • Disable Views support

  • Gracefully update vbucket configuration. This means that the connection listener, could reconfigure data sockets on the fly.

  • Allow the user to specify sync mode on an instance

  • New command cbc. This command intended as the analog of mem* tools from libmemcached distribution. Supported commands:

    • cbc-cat

    • cbc-cp

    • cbc-create

    • cbc-flush

    • cbc-rm

    • cbc-stats

    • cbc-send

    • cbc-receive

  • Add stats command

Fixes in 1.0.0

  • Aggregate flush responses

  • Don’t accept NULL as a valid “callback”

  • Convert flags to network byte order

Known Issues in 1.0.0

  • If the bootstrap node fails, the client library will not automatically fail over to another node in the cluster. This can cause an outage until the bootstrap node is corrected.

    Workaround : The program initializing libcouchbase may check first to see if the bootstrap node is available. If it is not, the program may initialize libcouchbase using a different URI.

  • A cluster being rebalanced or having nodes added can return errors to the client. There is no workaround for this issue, but it has been addressed in version 1.0.1.

Appendix: Licenses

This documentation and associated software is subject to the following licenses.

Documentation License

This documentation in any form, software or printed matter, contains proprietary information that is the exclusive property of Couchbase. Your access to and use of this material is subject to the terms and conditions of your Couchbase Software License and Service Agreement, which has been executed and with which you agree to comply. This document and information contained herein may not be disclosed, copied, reproduced, or distributed to anyone outside Couchbase without prior written consent of Couchbase or as specifically provided below. This document is not part of your license agreement nor can it be incorporated into any contractual agreement with Couchbase or its subsidiaries or affiliates.

Use of this documentation is subject to the following terms:

You may create a printed copy of this documentation solely for your own personal use. Conversion to other formats is allowed as long as the actual content is not altered or edited in any way. You shall not publish or distribute this documentation in any form or on any media, except if you distribute the documentation in a manner similar to how Couchbase disseminates it (that is, electronically for download on a Web site with the software) or on a CD-ROM or similar medium, provided however that the documentation is disseminated together with the software on the same medium. Any other use, such as any dissemination of printed copies or use of this documentation, in whole or in part, in another publication, requires the prior written consent from an authorized representative of Couchbase. Couchbase and/or its affiliates reserve any and all rights to this documentation not expressly granted above.

This documentation may provide access to or information on content, products, and services from third parties. Couchbase Inc. and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Couchbase Inc. and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.

The information contained herein is subject to change without notice and is not warranted to be error free. If you find any errors, please report them to us in writing.