From cb2a50691fb0cddb64e1b5a9ed242a6a0b42d503 Mon Sep 17 00:00:00 2001 From: Hristo Venev Date: Mon, 22 Jun 2020 12:32:11 +0300 Subject: Initial commit. --- examples/write.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 examples/write.c (limited to 'examples/write.c') diff --git a/examples/write.c b/examples/write.c new file mode 100644 index 0000000..456fb8e --- /dev/null +++ b/examples/write.c @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later + +#include +#include +#include +#include + +int main(int argc, char **argv) { + argc--; + argv++; + if(argc % 2 != 0) { + return 1; + } + + (void)argc; + (void)argv; + + int dfd = open("dbdir", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if(dfd < 0) { + fprintf(stderr, "Failed to open dbdir: %s\n", strerror(errno)); + return 1; + } + + hkvs_io *io = hkvs_io_new_unsafe_dirfd(dfd); + if(!io) { + fprintf(stderr, "Failed to create hkvs_io\n"); + return 1; + } + + hkvs *c; + int r = hkvs_new(&c, io); + if(r < 0) { + fprintf(stderr, "Failed to open database: %s\n", strerror(-r)); + return 1; + } + + hkvs_table *t; + r = hkvs_table_create(c, &t, 42, 4, 1); + if(r < 0) { + fprintf(stderr, "Failed to open table: %s\n", strerror(-r)); + return 1; + } + if(r) { + printf("Created table\n"); + } + + while(argc) { + const char *key = *argv++; + const char *val = *argv++; + argc -= 2; + if(strlen(key) != 4) { + fprintf(stderr, "Bad arg length\n"); + return 1; + } + + hkvs_rid id = hkvs_record_find(c, t, key); + if(hkvs_rid_ok(id)) { + char *cur_val; + size_t cur_len; + r = hkvs_record_value(c, t, id, &cur_val, &cur_len); + if(r < 0) { + fprintf(stderr, "Failed to get record value: %s\n", strerror(-r)); + return 1; + } + printf("%s: id=%llu [%zu] %.*s\n", key, (unsigned long long)id.id, cur_len, (int)cur_len, (const char*)cur_val); + } else { + printf("%s: not found\n", key); + } + + if(!!strcmp(val, "-")) { + r = hkvs_record_update(c, t, &id, key, val, strlen(val)); + if(r < 0) { + fprintf(stderr, "Failed to update record: %s\n", strerror(-r)); + return 1; + } + printf("%s: wrote id=%llu\n", key, (unsigned long long)id.id); + } else if(hkvs_rid_ok(id)) { + hkvs_record_delete(c, t, id); + printf("%s: deleted\n", key); + } + } + + hkvs_free(c); +} -- cgit