Couchbase C Client  2.10.7
Asynchronous C Client for Couchbase
example/minimal/query.c

Shows N1QL query API. Also because queries executed in a loop, the sample might be used as simple benchmark (more sofisticated shipped with cbc tools, as cbc-n1qlback)

/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2018 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.
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <libcouchbase/n1ql.h>
#include <libcouchbase/ixmgmt.h>
static void check(lcb_error_t err, const char *msg)
{
if (err != LCB_SUCCESS) {
fprintf(stderr, "[\x1b[31mERROR\x1b[0m] %s: %s\n", msg, lcb_strerror_short(err));
exit(EXIT_FAILURE);
}
}
static int err2color(lcb_error_t err)
{
switch (err) {
return 32;
return 33;
default:
return 31;
}
}
static void ln2space(const void *buf, size_t nbuf)
{
size_t ii;
char *str = (char *)buf;
for (ii = 0; ii < nbuf; ii++) {
if (str[ii] == '\n') {
str[ii] = ' ';
}
}
}
static void row_callback(lcb_t instance, int type, const lcb_RESPN1QL *resp)
{
ln2space(resp->row, resp->nrow);
fprintf(stderr, "[\x1b[%dmQUERY\x1b[0m] %s, (%d) %.*s\n", err2color(resp->rc), lcb_strerror_short(resp->rc),
(int)resp->nrow, (int)resp->nrow, (char *)resp->row);
if (resp->rflags & LCB_RESP_F_FINAL) {
fprintf(stderr, "\n");
}
}
static void idx_callback(lcb_t instance, int type, const lcb_RESPN1XMGMT *resp)
{
const lcb_RESPN1QL *inner = resp->inner;
ln2space(inner->row, inner->nrow);
fprintf(stderr, "[\x1b[%dmINDEX\x1b[0m] %s, (%d) %.*s\n", err2color(resp->rc), lcb_strerror_short(resp->rc),
(int)inner->nrow, (int)inner->nrow, (char *)inner->row);
}
static void kv_callback(lcb_t instance, int type, const lcb_RESPBASE *resp)
{
fprintf(stderr, "[\x1b[%dm%-5s\x1b[0m] %s, key=%.*s\n", err2color(resp->rc), lcb_strcbtype(type),
lcb_strerror_short(resp->rc), (int)resp->nkey, resp->key);
}
static int running = 1;
static void sigint_handler(int unused)
{
running = 0;
}
int main(int argc, char *argv[])
{
lcb_t instance;
char *bucket = NULL;
const char *key = "user:king_arthur";
const char *val = "{"
" \"email\": \"kingarthur@couchbase.com\","
" \"interests\": [\"Holy Grail\", \"African Swallows\"]"
"}";
if (argc < 2) {
fprintf(stderr, "Usage: %s couchbase://host/bucket [ password [ username ] ]\n", argv[0]);
exit(EXIT_FAILURE);
}
{
struct lcb_create_st create_options = {0};
create_options.version = 3;
create_options.v.v3.connstr = argv[1];
if (argc > 2) {
create_options.v.v3.passwd = argv[2];
}
if (argc > 3) {
create_options.v.v3.username = argv[3];
}
check(lcb_create(&instance, &create_options), "create couchbase handle");
check(lcb_connect(instance), "schedule connection");
lcb_wait(instance);
check(lcb_get_bootstrap_status(instance), "bootstrap from cluster");
check(lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_BUCKETNAME, &bucket), "get bucket name");
lcb_install_callback3(instance, LCB_CALLBACK_GET, kv_callback);
lcb_install_callback3(instance, LCB_CALLBACK_STORE, kv_callback);
}
{
lcb_CMDSTORE cmd = {0};
LCB_CMD_SET_KEY(&cmd, key, strlen(key));
LCB_CMD_SET_VALUE(&cmd, val, strlen(val));
check(lcb_store3(instance, NULL, &cmd), "schedule STORE operation");
lcb_wait(instance);
}
{
lcb_CMDGET cmd = {0};
LCB_CMD_SET_KEY(&cmd, key, strlen(key));
check(lcb_get3(instance, NULL, &cmd), "schedule GET operation");
lcb_wait(instance);
}
{
lcb_CMDN1XMGMT cmd = {0};
cmd.callback = idx_callback;
cmd.spec.flags = LCB_N1XSPEC_F_PRIMARY;
cmd.spec.ixtype = LCB_N1XSPEC_T_GSI;
check(lcb_n1x_create(instance, NULL, &cmd), "schedule N1QL index creation operation");
lcb_wait(instance);
}
/* setup CTRL-C handler */
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_handler = sigint_handler;
action.sa_flags = 0;
sigaction(SIGINT, &action, NULL);
while (running) {
lcb_CMDN1QL cmd = {0};
char query[1024] = {0};
const char *param = "\"African Swallows\"";
snprintf(query, sizeof(query), "SELECT * FROM `%s` WHERE $1 in interests LIMIT 1", bucket);
check(lcb_n1p_setstmtz(builder, query), "set QUERY statement");
check(lcb_n1p_posparam(builder, param, strlen(param)), "set QUERY positional parameter");
check(lcb_n1p_setopt(builder, "pretty", strlen("pretty"), "false", strlen("false")),
"set QUERY 'pretty' option");
check(lcb_n1p_mkcmd(builder, &cmd), "build QUERY command structure");
cmd.callback = row_callback;
check(lcb_n1ql_query(instance, NULL, &cmd), "schedule QUERY operation");
lcb_n1p_free(builder);
lcb_wait(instance);
}
/* Now that we're all done, close down the connection handle */
lcb_destroy(instance);
return 0;
}
lcb_CMDGET
Command for retrieving a single item.
Definition: couchbase.h:840
lcb_wait
lcb_error_t lcb_wait(lcb_t instance)
Wait for the execution of all batched requests.
lcb_RESPBASE::nkey
lcb_SIZE nkey
Size of key.
Definition: couchbase.h:626
lcb_n1p_setopt
lcb_error_t lcb_n1p_setopt(lcb_N1QLPARAMS *params, const char *name, size_t n_name, const char *value, size_t n_value)
Set a query option.
lcb_RESPN1QL::row
const char * row
Current result row.
Definition: n1ql.h:438
LCB_CNTL_BUCKETNAME
#define LCB_CNTL_BUCKETNAME
Get the name of the bucket This returns the name of the bucket this instance is connected to,...
Definition: cntl.h:177
lcb_n1p_posparam
lcb_error_t lcb_n1p_posparam(lcb_N1QLPARAMS *params, const char *value, size_t n_value)
Adds a positional argument for the query.
lcb_create_st3::passwd
const char * passwd
Password for bucket.
Definition: couchbase.h:293
lcb_get_bootstrap_status
lcb_error_t lcb_get_bootstrap_status(lcb_t instance)
Gets the initial bootstrap status.
lcb_RESPN1QL::rflags
lcb_U16 rflags
Flags for response structure.
Definition: n1ql.h:430
lcb_create_st3::connstr
const char * connstr
Connection string.
Definition: couchbase.h:282
lcb_connect
lcb_error_t lcb_connect(lcb_t instance)
Schedule the initial connection This function will schedule the initial connection for the handle.
LCB_CNTL_GET
#define LCB_CNTL_GET
Retrieve a setting.
Definition: cntl.h:125
lcb_create_st3::username
const char * username
Username to use for authentication.
Definition: couchbase.h:288
lcb_RESPN1QL
Response for a N1QL query.
Definition: n1ql.h:426
lcb_n1ql_query
lcb_error_t lcb_n1ql_query(lcb_t instance, const void *cookie, const lcb_CMDN1QL *cmd)
LCB_KEY_EEXISTS
@ LCB_KEY_EEXISTS
The key already exists in the cluster.
Definition: error.h:478
lcb_n1p_new
lcb_N1QLPARAMS * lcb_n1p_new(void)
Create a new N1QL Parameters object.
LCB_SET
@ LCB_SET
Unconditionally store the item in the cluster.
Definition: couchbase.h:1055
lcb_error_t
lcb_error_t
Error codes returned by the library.
Definition: error.h:476
lcb_store3
lcb_error_t lcb_store3(lcb_t instance, const void *cookie, const lcb_CMDSTORE *cmd)
Schedule a single storage request.
LCB_CALLBACK_STORE
@ LCB_CALLBACK_STORE
lcb_store3()
Definition: couchbase.h:698
lcb_N1QLPARAMS
struct lcb_N1QLPARAMS_st lcb_N1QLPARAMS
Opaque object representing N1QL parameters.
Definition: n1ql.h:109
lcb_RESPBASE::rc
lcb_error_t rc
Status code.
Definition: couchbase.h:626
lcb_create_st::lcb_CRST_u::v3
struct lcb_create_st3 v3
Use this field.
Definition: couchbase.h:338
lcb_get3
lcb_error_t lcb_get3(lcb_t instance, const void *cookie, const lcb_CMDGET *cmd)
Spool a single get operation.
lcb_strcbtype
const char * lcb_strcbtype(int cbtype)
Returns the type of the callback as a string.
lcb_create_st
Wrapper structure for lcb_create()
Definition: couchbase.h:328
lcb_n1p_mkcmd
lcb_error_t lcb_n1p_mkcmd(lcb_N1QLPARAMS *params, lcb_CMDN1QL *cmd)
Populates the given low-level lcb_CMDN1QL structure with the relevant fields from the params structur...
lcb_CMDN1XMGMT::spec
lcb_N1XSPEC spec
The index to operate on.
Definition: ixmgmt.h:145
LCB_CMD_SET_KEY
#define LCB_CMD_SET_KEY(cmd, keybuf, keylen)
Set the key for the command.
Definition: couchbase.h:556
lcb_t
struct lcb_st * lcb_t
Definition: couchbase.h:41
LCB_CALLBACK_GET
@ LCB_CALLBACK_GET
lcb_get3()
Definition: couchbase.h:697
lcb_N1XSPEC::flags
unsigned flags
Modifiers for the index itself.
Definition: ixmgmt.h:95
lcb_create
lcb_error_t lcb_create(lcb_t *instance, const struct lcb_create_st *options)
Create an instance of lcb.
couchbase.h
lcb_CMDN1XMGMT
Definition: ixmgmt.h:138
LCB_SUCCESS
@ LCB_SUCCESS
Success.
Definition: error.h:478
lcb_RESPN1QL::nrow
size_t nrow
Length of the row.
Definition: n1ql.h:440
lcb_RESPBASE
Base response structure for callbacks.
Definition: couchbase.h:625
lcb_destroy
void lcb_destroy(lcb_t instance)
Destroy (and release all allocated resources) an instance of lcb.
lcb_CMDN1QL::callback
lcb_N1QLCALLBACK callback
Callback to be invoked for each row.
Definition: n1ql.h:414
lcb_CMDSTORE::operation
lcb_storage_t operation
Controls how the operation is perfomed.
Definition: couchbase.h:1113
lcb_n1p_free
void lcb_n1p_free(lcb_N1QLPARAMS *params)
Free the parameters structure.
lcb_CMDN1QL
Command structure for N1QL queries.
Definition: n1ql.h:385
lcb_N1XSPEC::ixtype
unsigned ixtype
Type of this index, Can be LCB_N1XSPEC_T_DEFAULT for the default server type, or an explicit LCB_N1XS...
Definition: ixmgmt.h:102
LCB_CMD_SET_VALUE
#define LCB_CMD_SET_VALUE(scmd, valbuf, vallen)
Set the value buffer for the command. This may be used when the new value is a single contiguous buff...
Definition: couchbase.h:1139
lcb_create_st::version
int version
Indicates which field in the lcb_CRST_u union should be used.
Definition: couchbase.h:330
lcb_n1p_setstmtz
#define lcb_n1p_setstmtz(params, qstr)
Shortcut to set NUL-terminated string as statement via lcb_n1p_setquery.
Definition: n1ql.h:159
LCB_RESP_F_FINAL
@ LCB_RESP_F_FINAL
No more responses are to be received for this request.
Definition: couchbase.h:658
lcb_install_callback3
lcb_RESPCALLBACK lcb_install_callback3(lcb_t instance, int cbtype, lcb_RESPCALLBACK cb)
lcb_CMDSTORE
Command for storing an item to the server.
Definition: couchbase.h:1090
lcb_RESPBASE::key
const void * key
Key for request.
Definition: couchbase.h:626
lcb_CMDN1XMGMT::callback
lcb_N1XMGMTCALLBACK callback
Callback to be invoked when operation is complete.
Definition: ixmgmt.h:150
lcb_strerror_short
const LCB_INTERNAL_API char * lcb_strerror_short(lcb_error_t error)
Get a shorter textual description of an error message.
lcb_cntl
lcb_error_t lcb_cntl(lcb_t instance, int mode, int cmd, void *arg)
This function exposes an ioctl/fcntl-like interface to read and write various configuration propertie...