| 1 | #include "xtdb.hh" |
|---|
| 2 | #include "pdns/lock.hh" |
|---|
| 3 | #include <tdb.h> |
|---|
| 4 | #include <errno.h> |
|---|
| 5 | #include <string.h> |
|---|
| 6 | #include <sys/types.h> |
|---|
| 7 | #include <sys/stat.h> |
|---|
| 8 | #include <fcntl.h> |
|---|
| 9 | #include <iostream> |
|---|
| 10 | |
|---|
| 11 | |
|---|
| 12 | #include "pdns/namespaces.hh" |
|---|
| 13 | |
|---|
| 14 | TDB_CONTEXT *XTDBWrapper::s_db; |
|---|
| 15 | int XTDBWrapper::s_usecount; |
|---|
| 16 | pthread_mutex_t XTDBWrapper::s_lock=PTHREAD_MUTEX_INITIALIZER; |
|---|
| 17 | |
|---|
| 18 | XTDBWrapper::XTDBWrapper(const string &fname) |
|---|
| 19 | { |
|---|
| 20 | Lock l(&s_lock); |
|---|
| 21 | if(!s_db) { |
|---|
| 22 | s_db = tdb_open(const_cast<char *>(fname.c_str()), 5213331, |
|---|
| 23 | TDB_NOLOCK, |
|---|
| 24 | O_RDWR | O_CREAT , 0600); |
|---|
| 25 | if(!s_db) |
|---|
| 26 | throw XDBException("Unable to open database: "+string(strerror(errno))); |
|---|
| 27 | } |
|---|
| 28 | s_usecount++; |
|---|
| 29 | |
|---|
| 30 | } |
|---|
| 31 | |
|---|
| 32 | XTDBWrapper::~XTDBWrapper() |
|---|
| 33 | { |
|---|
| 34 | if(!--s_usecount) { |
|---|
| 35 | tdb_close(s_db); |
|---|
| 36 | cerr<<"closed"<<endl; |
|---|
| 37 | } |
|---|
| 38 | } |
|---|
| 39 | |
|---|
| 40 | bool XTDBWrapper::get(const string &key, string &value) |
|---|
| 41 | { |
|---|
| 42 | |
|---|
| 43 | TDB_DATA kdatum={const_cast<char *>(key.c_str()),key.size()+1}; |
|---|
| 44 | TDB_DATA vdatum; |
|---|
| 45 | |
|---|
| 46 | { |
|---|
| 47 | //Lock l(&s_lock); |
|---|
| 48 | vdatum=tdb_fetch(s_db,kdatum); |
|---|
| 49 | } |
|---|
| 50 | if(!vdatum.dptr) |
|---|
| 51 | return false; |
|---|
| 52 | value.assign(vdatum.dptr,vdatum.dsize); |
|---|
| 53 | free(vdatum.dptr); |
|---|
| 54 | return true; |
|---|
| 55 | } |
|---|
| 56 | |
|---|
| 57 | void XTDBWrapper::put(const string &key, const string &value) |
|---|
| 58 | { |
|---|
| 59 | TDB_DATA kdatum={const_cast<char *>(key.c_str()),key.size()+1}; |
|---|
| 60 | TDB_DATA vdatum={const_cast<char *>(value.c_str()),value.size()}; |
|---|
| 61 | if(tdb_store(s_db, kdatum, vdatum,TDB_REPLACE)<0) |
|---|
| 62 | throw XDBException("Error storing key: "+string(strerror(errno))); |
|---|
| 63 | |
|---|
| 64 | } |
|---|
| 65 | |
|---|
| 66 | void XTDBWrapper::del(const string &key) |
|---|
| 67 | { |
|---|
| 68 | } |
|---|
| 69 | |
|---|
| 70 | #ifdef TESTDRIVER |
|---|
| 71 | main() |
|---|
| 72 | { |
|---|
| 73 | XDBWrapper *xdb=new XTDBWrapper("wuh"); |
|---|
| 74 | xdb->put("ahu","toffe gast"); |
|---|
| 75 | xdb->append("ahu",", echt waar!"); |
|---|
| 76 | |
|---|
| 77 | string tst; |
|---|
| 78 | xdb->get("ahu",tst); |
|---|
| 79 | cout<<"Database zegt over ahu: '"<<tst<<"'"<<endl; |
|---|
| 80 | |
|---|
| 81 | xdb->append("ahu"," Toch niet!"); |
|---|
| 82 | xdb->get("ahu",tst); |
|---|
| 83 | cout<<"Database zegt over ahu: '"<<tst<<"'"<<endl; |
|---|
| 84 | |
|---|
| 85 | } |
|---|
| 86 | #endif |
|---|