db_dump.cpp 2.37 KB
Newer Older
1
#include <stdlib.h>
2 3 4
#include <assert.h>
#include <db_cxx.h>

5
static void hexdump(Dbt *d) {
6 7 8 9 10 11 12 13
    unsigned char *cp = (unsigned char *) d->get_data();
    int n = d->get_size();
    printf(" ");
    for (int i=0; i<n; i++)
        printf("%2.2x", cp[i]);
    printf("\n");
}

14
static int dbdump(char *dbfile, char *dbname) {
15 16
    int r;

17
#if defined(USE_ENV) && USE_ENV
18 19 20 21 22 23
    DbEnv env(DB_CXX_NO_EXCEPTIONS);
    r = env.open(".", DB_INIT_MPOOL + DB_CREATE + DB_PRIVATE, 0777); assert(r == 0);
    Db db(&env, DB_CXX_NO_EXCEPTIONS);
#else
    Db db(0, DB_CXX_NO_EXCEPTIONS);
#endif
Rich Prohaska's avatar
Rich Prohaska committed
24
    r = db.open(0, dbfile, dbname, DB_UNKNOWN, 0, 0777); 
25
    if (r != 0) {
26
        printf("cant open %s:%s %d:%s\n", dbfile, dbname, r, db_strerror(r));
27
#if defined(USE_ENV) && USE_ENV
28 29 30 31 32
        r = env.close(0); assert(r == 0);
#endif
        return 1;
    }

33 34 35 36 37 38 39 40 41 42 43 44
    u_int32_t dbflags;
    r = db.get_flags(&dbflags); assert(r == 0);
    if (dbflags & DB_DUP)
        printf("duplicates=1\n");
    if (dbflags & DB_DUPSORT)
        printf("dupsort=1\n");
#if 0
    u_int32_t nodesize;
    r = db.get_nodesize(&nodesize); assert(r == 0);
    printf("nodesize=%d\n", nodesize);
#endif

45 46 47
    Dbc *cursor;
    r = db.cursor(0, &cursor, 0); assert(r == 0);

48 49
    Dbt key; key.set_flags(DB_DBT_REALLOC);
    Dbt val; val.set_flags(DB_DBT_REALLOC);
50 51 52 53 54 55 56 57
    for (;;) {
        r = cursor->get(&key, &val, DB_NEXT);
        if (r != 0) break;
        // printf("%.*s\n", key.get_size(), (char *)key.get_data());
        hexdump(&key);
        // printf("%.*s\n", val.get_size(), (char *)val.get_data());
        hexdump(&val);
    }
58 59 60
    if (key.get_data()) free(key.get_data());
    if (val.get_data()) free(val.get_data());

61 62
    r = cursor->close(); assert(r == 0);
    r = db.close(0); assert(r == 0);
63
#if defined(USE_ENV) && USE_ENV
64 65 66 67 68
    r = env.close(0); assert(r == 0);
#endif
    return 0;
}

69
static int usage() {
70 71 72 73 74 75
    printf("db_dump [-s DBNAME] DBFILE\n");
    return 1;
}

int main(int argc, char *argv[]) {
    char *dbname = 0;
76 77

    int i;
78 79 80 81 82
    for (i=1; i<argc; i++) {
        char *arg = argv[i];
        if (0 == strcmp(arg, "-h") || 0 == strcmp(arg, "--help")) 
            return usage();
        if (0 == strcmp(arg, "-s")) {
83
            if (i+1 >= argc)
84
                return usage();
85
            dbname = argv[++i];
86 87 88 89 90 91
            continue;
        }
        break;
    }
    if (i >= argc)
        return usage();
92

93 94 95
    return dbdump(argv[i], dbname);
}