db2.c
Uses a Cursor to copy one Database to another; this can also be used to copy an In-Memory Database into a file Database and vice versa
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ham/hamsterdb.h>
void
error(const char *foo, ham_status_t st)
{
printf("%s() returned error %d: %s\n", foo, st, ham_strerror(st));
exit(-1);
}
void
usage(void)
{
printf("usage: ./db2 <source> <destination>\n");
exit(-1);
}
void
copy_db(ham_db_t *source, ham_db_t *dest)
{
ham_cursor_t *cursor;
ham_status_t st;
ham_key_t key;
ham_record_t rec;
memset(&key, 0, sizeof(key));
memset(&rec, 0, sizeof(rec));
st=ham_cursor_create(source, 0, 0, &cursor);
if (st)
error("ham_cursor_create", st);
st=ham_cursor_move(cursor, &key, &rec, HAM_CURSOR_FIRST);
if (st==HAM_KEY_NOT_FOUND) {
printf("database is empty!\n");
return;
}
else if (st)
error("ham_cursor_move", st);
do {
st=ham_insert(dest, 0, &key, &rec, HAM_DUPLICATE);
if (st)
error("ham_insert", st);
printf(".");
st=ham_cursor_move(cursor, &key, &rec, HAM_CURSOR_NEXT);
if (st && st!=HAM_KEY_NOT_FOUND)
error("ham_cursor_move", st);
} while (st==0);
ham_cursor_close(cursor);
}
int
main(int argc, char **argv)
{
ham_status_t st;
ham_db_t *src, *dest;
const char *src_path=0, *dest_path=0;
if (argc!=3)
usage();
src_path =argv[1];
dest_path=argv[2];
st=ham_new(&src);
if (st)
error("ham_new", st);
st=ham_open(src, src_path, 0);
if (st)
error("ham_open", st);
st=ham_new(&dest);
if (st)
error("ham_new", st);
st=ham_create(dest, dest_path, HAM_ENABLE_DUPLICATES, 0664);
if (st)
error("ham_create", st);
copy_db(src, dest);
st=ham_close(src, 0);
if (st)
error("ham_close", st);
st=ham_close(dest, 0);
if (st)
error("ham_close", st);
ham_delete(src);
ham_delete(dest);
printf("\nsuccess!\n");
return (0);
}