my8bird/node-leveldb — pull request #44 by justmoon (2012-07-27 06:06:54+00:00)
Title: Provide C++ level access to LevelDB objects

I expect this change might be controversial, so I'm going to explain my use case first. I'm maintaining a rather large app called BitcoinJS using LevelDB as it's backend. To initialize it has to load/index a 2.4 GB dataset called the block chain. Right now I'm parsing the block chain in JS and inserting it with individual Batch.put operations. Unfortunately, this results in a huge number of calls across the JS/C++ boundary.

So what I'd like to do instead is pass a whole block to my own C++ code and have it do the parsing and inserting in straight C++.

To do that though, I need to be able to get access to the leveldb::DB and leveldb::WriteBatch handles in my C++ code.

The cleanest way I've found is to pass node-leveldb's internal handles (`self`) to my native object's constructor and unwrap them:

``` cpp
node_leveldb::JHandle* hnd = Unwrap(args[0]->ToObject());
leveldb::DB* ldb = hnd->GetDB();
MyObj* self = new MyObj(ldb);
```

I then also make sure that I keep a persistent handle to `self` so it can't be garbage collected until MyObj is destroyed.

Unfortunately this depends on being able to get the actual LevelDB handle out of node_leveldb::JHandle, which is why I had to add some accessors.

Feel free to tell me if there is a better way of doing this, but this seems reasonably clean and it's obviously for advanced uses only.