// SPDX-License-Identifier: LGPL-3.0-or-later
#include <hkvs.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
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);
}