Commit de8888ef by Mohamed Akram

Convert NAN to N-API using tool

parent fdceaef8
...@@ -7,10 +7,21 @@ ...@@ -7,10 +7,21 @@
"targets": [ "targets": [
{ {
"target_name": "<(module_name)", "target_name": "<(module_name)",
"include_dirs": ["<!(node -e \"require('nan')\")"], "cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"xcode_settings": { "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
"CLANG_CXX_LIBRARY": "libc++",
"MACOSX_DEPLOYMENT_TARGET": "10.7",
},
"msvs_settings": {
"VCCLCompilerTool": { "ExceptionHandling": 1 },
},
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")","<!(node -e \"require('nan')\")"],
"conditions": [ "conditions": [
["sqlite != 'internal'", { ["sqlite != 'internal'", {
"include_dirs": [ "<(sqlite)/include" ], "include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")", "<(sqlite)/include" ],
"libraries": [ "libraries": [
"-l<(sqlite_libname)" "-l<(sqlite_libname)"
], ],
...@@ -26,6 +37,7 @@ ...@@ -26,6 +37,7 @@
}, },
{ {
"dependencies": [ "dependencies": [
"<!(node -p 'require(\"node-addon-api\").gyp')",
"deps/sqlite3.gyp:sqlite3" "deps/sqlite3.gyp:sqlite3"
] ]
} }
...@@ -40,8 +52,18 @@ ...@@ -40,8 +52,18 @@
}, },
{ {
"target_name": "action_after_build", "target_name": "action_after_build",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"xcode_settings": { "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
"CLANG_CXX_LIBRARY": "libc++",
"MACOSX_DEPLOYMENT_TARGET": "10.7",
},
"msvs_settings": {
"VCCLCompilerTool": { "ExceptionHandling": 1 },
},
"type": "none", "type": "none",
"dependencies": [ "<(module_name)" ], "dependencies": [
"<!(node -p 'require(\"node-addon-api\").gyp')", "<(module_name)" ],
"copies": [ "copies": [
{ {
"files": [ "<(PRODUCT_DIR)/<(module_name).node" ], "files": [ "<(PRODUCT_DIR)/<(module_name).node" ],
......
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
"url": "git://github.com/mapbox/node-sqlite3.git" "url": "git://github.com/mapbox/node-sqlite3.git"
}, },
"dependencies": { "dependencies": {
"nan": "^2.12.1", "node-addon-api": "2.0.0",
"node-pre-gyp": "^0.11.0" "node-pre-gyp": "^0.11.0"
}, },
"devDependencies": { "devDependencies": {
......
#include <string.h> #include <string.h>
#include <node.h> #include <napi.h>
#include <uv.h>
#include <node_buffer.h> #include <node_buffer.h>
#include <node_version.h> #include <node_version.h>
...@@ -9,19 +10,19 @@ ...@@ -9,19 +10,19 @@
using namespace node_sqlite3; using namespace node_sqlite3;
Nan::Persistent<FunctionTemplate> Backup::constructor_template; Napi::FunctionReference Backup::constructor;
NAN_MODULE_INIT(Backup::Init) { Napi::Object Backup::Init(Napi::Env env, Napi::Object exports) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); Napi::FunctionReference t = Napi::Function::New(env, New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Backup").ToLocalChecked());
Nan::SetPrototypeMethod(t, "step", Step); t->SetClassName(Napi::String::New(env, "Backup"));
Nan::SetPrototypeMethod(t, "finish", Finish);
InstanceMethod("step", &Step),
InstanceMethod("finish", &Finish),
NODE_SET_GETTER(t, "idle", IdleGetter); NODE_SET_GETTER(t, "idle", IdleGetter);
NODE_SET_GETTER(t, "completed", CompletedGetter); NODE_SET_GETTER(t, "completed", CompletedGetter);
...@@ -31,9 +32,9 @@ NAN_MODULE_INIT(Backup::Init) { ...@@ -31,9 +32,9 @@ NAN_MODULE_INIT(Backup::Init) {
NODE_SET_SETTER(t, "retryErrors", RetryErrorGetter, RetryErrorSetter); NODE_SET_SETTER(t, "retryErrors", RetryErrorGetter, RetryErrorSetter);
constructor_template.Reset(t); constructor.Reset(t);
Nan::Set(target, Nan::New("Backup").ToLocalChecked(), (target).Set(Napi::String::New(env, "Backup"),
Nan::GetFunction(t).ToLocalChecked()); Napi::GetFunction(t));
} }
void Backup::Process() { void Backup::Process() {
...@@ -64,33 +65,33 @@ void Backup::Schedule(Work_Callback callback, Baton* baton) { ...@@ -64,33 +65,33 @@ void Backup::Schedule(Work_Callback callback, Baton* baton) {
} }
template <class T> void Backup::Error(T* baton) { template <class T> void Backup::Error(T* baton) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Backup* backup = baton->backup; Backup* backup = baton->backup;
// Fail hard on logic errors. // Fail hard on logic errors.
assert(backup->status != 0); assert(backup->status != 0);
EXCEPTION(backup->message, backup->status, exception); EXCEPTION(backup->message, backup->status, exception);
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
TRY_CATCH_CALL(backup->handle(), cb, 1, argv); TRY_CATCH_CALL(backup->handle(), cb, 1, argv);
} }
else { else {
Local<Value> argv[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value argv[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(backup->handle(), 2, argv); EMIT_EVENT(backup->handle(), 2, argv);
} }
} }
void Backup::CleanQueue() { void Backup::CleanQueue() {
Nan::HandleScope scope; Napi::HandleScope scope(env);
if (inited && !queue.empty()) { if (inited && !queue.empty()) {
// This backup has already been initialized and is now finished. // This backup has already been initialized and is now finished.
// Fire error for all remaining items in the queue. // Fire error for all remaining items in the queue.
EXCEPTION("Backup is already finished", SQLITE_MISUSE, exception); EXCEPTION("Backup is already finished", SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
bool called = false; bool called = false;
// Clear out the queue so that this object can get GC'ed. // Clear out the queue so that this object can get GC'ed.
...@@ -98,7 +99,7 @@ void Backup::CleanQueue() { ...@@ -98,7 +99,7 @@ void Backup::CleanQueue() {
Call* call = queue.front(); Call* call = queue.front();
queue.pop(); queue.pop();
Local<Function> cb = Nan::New(call->baton->callback); Napi::Function cb = Napi::New(env, call->baton->callback);
if (inited && !cb.IsEmpty() && if (inited && !cb.IsEmpty() &&
cb->IsFunction()) { cb->IsFunction()) {
...@@ -115,7 +116,7 @@ void Backup::CleanQueue() { ...@@ -115,7 +116,7 @@ void Backup::CleanQueue() {
// When we couldn't call a callback function, emit an error on the // When we couldn't call a callback function, emit an error on the
// Backup object. // Backup object.
if (!called) { if (!called) {
Local<Value> info[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value info[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(handle(), 2, info); EMIT_EVENT(handle(), 2, info);
} }
} }
...@@ -132,54 +133,61 @@ void Backup::CleanQueue() { ...@@ -132,54 +133,61 @@ void Backup::CleanQueue() {
} }
} }
NAN_METHOD(Backup::New) { Napi::Value Backup::New(const Napi::CallbackInfo& info) {
if (!info.IsConstructCall()) { if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to create new Backup objects"); Napi::TypeError::New(env, "Use the new operator to create new Backup objects").ThrowAsJavaScriptException();
return env.Null();
} }
int length = info.Length(); int length = info.Length();
if (length <= 0 || !Database::HasInstance(info[0])) { if (length <= 0 || !Database::HasInstance(info[0])) {
return Nan::ThrowTypeError("Database object expected"); Napi::TypeError::New(env, "Database object expected").ThrowAsJavaScriptException();
return env.Null();
} }
else if (length <= 1 || !info[1]->IsString()) { else if (length <= 1 || !info[1].IsString()) {
return Nan::ThrowTypeError("Filename expected"); Napi::TypeError::New(env, "Filename expected").ThrowAsJavaScriptException();
return env.Null();
} }
else if (length <= 2 || !info[2]->IsString()) { else if (length <= 2 || !info[2].IsString()) {
return Nan::ThrowTypeError("Source database name expected"); Napi::TypeError::New(env, "Source database name expected").ThrowAsJavaScriptException();
return env.Null();
} }
else if (length <= 3 || !info[3]->IsString()) { else if (length <= 3 || !info[3].IsString()) {
return Nan::ThrowTypeError("Destination database name expected"); Napi::TypeError::New(env, "Destination database name expected").ThrowAsJavaScriptException();
return env.Null();
} }
else if (length <= 4 || !info[4]->IsBoolean()) { else if (length <= 4 || !info[4].IsBoolean()) {
return Nan::ThrowTypeError("Direction flag expected"); Napi::TypeError::New(env, "Direction flag expected").ThrowAsJavaScriptException();
return env.Null();
} }
else if (length > 5 && !info[5]->IsUndefined() && !info[5]->IsFunction()) { else if (length > 5 && !info[5].IsUndefined() && !info[5].IsFunction()) {
return Nan::ThrowTypeError("Callback expected"); Napi::TypeError::New(env, "Callback expected").ThrowAsJavaScriptException();
return env.Null();
} }
Database* db = Nan::ObjectWrap::Unwrap<Database>(info[0].As<Object>()); Database* db = info[0].As<Napi::Object>().Unwrap<Database>();
Local<String> filename = Local<String>::Cast(info[1]); Napi::String filename = info[1].As<Napi::String>();
Local<String> sourceName = Local<String>::Cast(info[2]); Napi::String sourceName = info[2].As<Napi::String>();
Local<String> destName = Local<String>::Cast(info[3]); Napi::String destName = info[3].As<Napi::String>();
Local<Boolean> filenameIsDest = Local<Boolean>::Cast(info[4]); Napi::Boolean filenameIsDest = info[4].As<Napi::Boolean>();
Nan::ForceSet(info.This(), Nan::New("filename").ToLocalChecked(), filename, ReadOnly); info.This().DefineProperty(Napi::String::New(env, "filename"), filename, ReadOnly);
Nan::ForceSet(info.This(), Nan::New("sourceName").ToLocalChecked(), sourceName, ReadOnly); info.This().DefineProperty(Napi::String::New(env, "sourceName"), sourceName, ReadOnly);
Nan::ForceSet(info.This(), Nan::New("destName").ToLocalChecked(), destName, ReadOnly); info.This().DefineProperty(Napi::String::New(env, "destName"), destName, ReadOnly);
Nan::ForceSet(info.This(), Nan::New("filenameIsDest").ToLocalChecked(), filenameIsDest, ReadOnly); info.This().DefineProperty(Napi::String::New(env, "filenameIsDest"), filenameIsDest, ReadOnly);
Backup* backup = new Backup(db); Backup* backup = new Backup(db);
backup->Wrap(info.This()); backup->Wrap(info.This());
InitializeBaton* baton = new InitializeBaton(db, Local<Function>::Cast(info[5]), backup); InitializeBaton* baton = new InitializeBaton(db, info[5].As<Napi::Function>(), backup);
baton->filename = std::string(*Nan::Utf8String(filename)); baton->filename = std::string(filename->As<Napi::String>().Utf8Value().c_str());
baton->sourceName = std::string(*Nan::Utf8String(sourceName)); baton->sourceName = std::string(sourceName->As<Napi::String>().Utf8Value().c_str());
baton->destName = std::string(*Nan::Utf8String(destName)); baton->destName = std::string(destName->As<Napi::String>().Utf8Value().c_str());
baton->filenameIsDest = Nan::To<bool>(filenameIsDest).FromJust(); baton->filenameIsDest = filenameIsDest.As<Napi::Boolean>().Value();
db->Schedule(Work_BeginInitialize, baton); db->Schedule(Work_BeginInitialize, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Backup::Work_BeginInitialize(Database::Baton* baton) { void Backup::Work_BeginInitialize(Database::Baton* baton) {
...@@ -220,7 +228,7 @@ void Backup::Work_Initialize(uv_work_t* req) { ...@@ -220,7 +228,7 @@ void Backup::Work_Initialize(uv_work_t* req) {
} }
void Backup::Work_AfterInitialize(uv_work_t* req) { void Backup::Work_AfterInitialize(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
BACKUP_INIT(InitializeBaton); BACKUP_INIT(InitializeBaton);
...@@ -230,17 +238,17 @@ void Backup::Work_AfterInitialize(uv_work_t* req) { ...@@ -230,17 +238,17 @@ void Backup::Work_AfterInitialize(uv_work_t* req) {
} }
else { else {
backup->inited = true; backup->inited = true;
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(backup->handle(), cb, 1, argv); TRY_CATCH_CALL(backup->handle(), cb, 1, argv);
} }
} }
BACKUP_END(); BACKUP_END();
} }
NAN_METHOD(Backup::Step) { Napi::Value Backup::Step(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
REQUIRE_ARGUMENT_INTEGER(0, pages); REQUIRE_ARGUMENT_INTEGER(0, pages);
OPTIONAL_ARGUMENT_FUNCTION(1, callback); OPTIONAL_ARGUMENT_FUNCTION(1, callback);
...@@ -248,7 +256,7 @@ NAN_METHOD(Backup::Step) { ...@@ -248,7 +256,7 @@ NAN_METHOD(Backup::Step) {
StepBaton* baton = new StepBaton(backup, callback, pages); StepBaton* baton = new StepBaton(backup, callback, pages);
backup->GetRetryErrors(baton->retryErrorsSet); backup->GetRetryErrors(baton->retryErrorsSet);
backup->Schedule(Work_BeginStep, baton); backup->Schedule(Work_BeginStep, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Backup::Work_BeginStep(Baton* baton) { void Backup::Work_BeginStep(Baton* baton) {
...@@ -280,7 +288,7 @@ void Backup::Work_Step(uv_work_t* req) { ...@@ -280,7 +288,7 @@ void Backup::Work_Step(uv_work_t* req) {
} }
void Backup::Work_AfterStep(uv_work_t* req) { void Backup::Work_AfterStep(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
BACKUP_INIT(StepBaton); BACKUP_INIT(StepBaton);
...@@ -295,9 +303,9 @@ void Backup::Work_AfterStep(uv_work_t* req) { ...@@ -295,9 +303,9 @@ void Backup::Work_AfterStep(uv_work_t* req) {
} }
else { else {
// Fire callbacks. // Fire callbacks.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null(), Nan::New(backup->status == SQLITE_DONE) }; Napi::Value argv[] = { env.Null(), Napi::New(env, backup->status == SQLITE_DONE) };
TRY_CATCH_CALL(backup->handle(), cb, 2, argv); TRY_CATCH_CALL(backup->handle(), cb, 2, argv);
} }
} }
...@@ -305,14 +313,14 @@ void Backup::Work_AfterStep(uv_work_t* req) { ...@@ -305,14 +313,14 @@ void Backup::Work_AfterStep(uv_work_t* req) {
BACKUP_END(); BACKUP_END();
} }
NAN_METHOD(Backup::Finish) { Napi::Value Backup::Finish(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
OPTIONAL_ARGUMENT_FUNCTION(0, callback); OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(backup, callback); Baton* baton = new Baton(backup, callback);
backup->Schedule(Work_BeginFinish, baton); backup->Schedule(Work_BeginFinish, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Backup::Work_BeginFinish(Baton* baton) { void Backup::Work_BeginFinish(Baton* baton) {
...@@ -325,13 +333,13 @@ void Backup::Work_Finish(uv_work_t* req) { ...@@ -325,13 +333,13 @@ void Backup::Work_Finish(uv_work_t* req) {
} }
void Backup::Work_AfterFinish(uv_work_t* req) { void Backup::Work_AfterFinish(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
BACKUP_INIT(Baton); BACKUP_INIT(Baton);
backup->FinishAll(); backup->FinishAll();
// Fire callback in case there was one. // Fire callback in case there was one.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(backup->handle(), cb, 0, NULL); TRY_CATCH_CALL(backup->handle(), cb, 0, NULL);
} }
...@@ -362,54 +370,55 @@ void Backup::FinishSqlite() { ...@@ -362,54 +370,55 @@ void Backup::FinishSqlite() {
_destDb = NULL; _destDb = NULL;
} }
NAN_GETTER(Backup::IdleGetter) { Napi::Value Backup::IdleGetter(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
bool idle = backup->inited && !backup->locked && backup->queue.empty(); bool idle = backup->inited && !backup->locked && backup->queue.empty();
info.GetReturnValue().Set(idle); return idle;
} }
NAN_GETTER(Backup::CompletedGetter) { Napi::Value Backup::CompletedGetter(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
info.GetReturnValue().Set(backup->completed); return backup->completed;
} }
NAN_GETTER(Backup::FailedGetter) { Napi::Value Backup::FailedGetter(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
info.GetReturnValue().Set(backup->failed); return backup->failed;
} }
NAN_GETTER(Backup::RemainingGetter) { Napi::Value Backup::RemainingGetter(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
info.GetReturnValue().Set(backup->remaining); return backup->remaining;
} }
NAN_GETTER(Backup::PageCountGetter) { Napi::Value Backup::PageCountGetter(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
info.GetReturnValue().Set(backup->pageCount); return backup->pageCount;
} }
NAN_GETTER(Backup::RetryErrorGetter) { Napi::Value Backup::RetryErrorGetter(const Napi::CallbackInfo& info) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
info.GetReturnValue().Set(Nan::New(backup->retryErrors)); return Napi::New(env, backup->retryErrors);
} }
NAN_SETTER(Backup::RetryErrorSetter) { void Backup::RetryErrorSetter(const Napi::CallbackInfo& info, const Napi::Value& value) {
Backup* backup = Nan::ObjectWrap::Unwrap<Backup>(info.This()); Backup* backup = this;
if (!value->IsArray()) { if (!value->IsArray()) {
return Nan::ThrowError("retryErrors must be an array"); Napi::Error::New(env, "retryErrors must be an array").ThrowAsJavaScriptException();
return env.Null();
} }
Local<Array> array = Local<Array>::Cast(value); Napi::Array array = value.As<Napi::Array>();
backup->retryErrors.Reset(array); backup->retryErrors.Reset(array);
} }
void Backup::GetRetryErrors(std::set<int>& retryErrorsSet) { void Backup::GetRetryErrors(std::set<int>& retryErrorsSet) {
retryErrorsSet.clear(); retryErrorsSet.clear();
Local<Array> array = Nan::New(retryErrors); Napi::Array array = Napi::New(env, retryErrors);
int length = array->Length(); int length = array->Length();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
Local<Value> code = Nan::Get(array, i).ToLocalChecked(); Napi::Value code = (array).Get(i);
if (code->IsInt32()) { if (code.IsNumber()) {
retryErrorsSet.insert(Nan::To<int32_t>(code).FromJust()); retryErrorsSet.insert(code.As<Napi::Number>().Int32Value());
} }
} }
} }
......
...@@ -8,10 +8,11 @@ ...@@ -8,10 +8,11 @@
#include <set> #include <set>
#include <sqlite3.h> #include <sqlite3.h>
#include <nan.h> #include <napi.h>
#include <uv.h>
using namespace v8; using namespace Napi;
using namespace node; using namespace Napi;
namespace node_sqlite3 { namespace node_sqlite3 {
...@@ -92,19 +93,19 @@ namespace node_sqlite3 { ...@@ -92,19 +93,19 @@ namespace node_sqlite3 {
* backup.finish(); * backup.finish();
* *
*/ */
class Backup : public Nan::ObjectWrap { class Backup : public Napi::ObjectWrap<Backup> {
public: public:
static Nan::Persistent<FunctionTemplate> constructor_template; static Napi::FunctionReference constructor;
static NAN_MODULE_INIT(Init); static Napi::Object Init(Napi::Env env, Napi::Object exports);
static NAN_METHOD(New); static Napi::Value New(const Napi::CallbackInfo& info);
struct Baton { struct Baton {
uv_work_t request; uv_work_t request;
Backup* backup; Backup* backup;
Nan::Persistent<Function> callback; Napi::FunctionReference callback;
Baton(Backup* backup_, Local<Function> cb_) : backup(backup_) { Baton(Backup* backup_, Napi::Function cb_) : backup(backup_) {
backup->Ref(); backup->Ref();
request.data = this; request.data = this;
callback.Reset(cb_); callback.Reset(cb_);
...@@ -121,7 +122,7 @@ public: ...@@ -121,7 +122,7 @@ public:
std::string sourceName; std::string sourceName;
std::string destName; std::string destName;
bool filenameIsDest; bool filenameIsDest;
InitializeBaton(Database* db_, Local<Function> cb_, Backup* backup_) : InitializeBaton(Database* db_, Napi::Function cb_, Backup* backup_) :
Baton(db_, cb_), backup(backup_), filenameIsDest(true) { Baton(db_, cb_), backup(backup_), filenameIsDest(true) {
backup->Ref(); backup->Ref();
} }
...@@ -137,7 +138,7 @@ public: ...@@ -137,7 +138,7 @@ public:
struct StepBaton : Baton { struct StepBaton : Baton {
int pages; int pages;
std::set<int> retryErrorsSet; std::set<int> retryErrorsSet;
StepBaton(Backup* backup_, Local<Function> cb_, int pages_) : StepBaton(Backup* backup_, Napi::Function cb_, int pages_) :
Baton(backup_, cb_), pages(pages_) {} Baton(backup_, cb_), pages(pages_) {}
}; };
...@@ -149,7 +150,7 @@ public: ...@@ -149,7 +150,7 @@ public:
Baton* baton; Baton* baton;
}; };
Backup(Database* db_) : Nan::ObjectWrap(), Backup(Database* db_) : Napi::ObjectWrap<Backup>(),
db(db_), db(db_),
_handle(NULL), _handle(NULL),
_otherDb(NULL), _otherDb(NULL),
...@@ -173,16 +174,16 @@ public: ...@@ -173,16 +174,16 @@ public:
WORK_DEFINITION(Step); WORK_DEFINITION(Step);
WORK_DEFINITION(Finish); WORK_DEFINITION(Finish);
static NAN_GETTER(IdleGetter); Napi::Value IdleGetter(const Napi::CallbackInfo& info);
static NAN_GETTER(CompletedGetter); Napi::Value CompletedGetter(const Napi::CallbackInfo& info);
static NAN_GETTER(FailedGetter); Napi::Value FailedGetter(const Napi::CallbackInfo& info);
static NAN_GETTER(PageCountGetter); Napi::Value PageCountGetter(const Napi::CallbackInfo& info);
static NAN_GETTER(RemainingGetter); Napi::Value RemainingGetter(const Napi::CallbackInfo& info);
static NAN_GETTER(FatalErrorGetter); Napi::Value FatalErrorGetter(const Napi::CallbackInfo& info);
static NAN_GETTER(RetryErrorGetter); Napi::Value RetryErrorGetter(const Napi::CallbackInfo& info);
static NAN_SETTER(FatalErrorSetter); void FatalErrorSetter(const Napi::CallbackInfo& info, const Napi::Value& value);
static NAN_SETTER(RetryErrorSetter); void RetryErrorSetter(const Napi::CallbackInfo& info, const Napi::Value& value);
protected: protected:
static void Work_BeginInitialize(Database::Baton* baton); static void Work_BeginInitialize(Database::Baton* baton);
...@@ -215,7 +216,7 @@ protected: ...@@ -215,7 +216,7 @@ protected:
bool finished; bool finished;
std::queue<Call*> queue; std::queue<Call*> queue;
Nan::Persistent<Array> retryErrors; Napi::Persistent<Array> retryErrors;
}; };
} }
......
...@@ -6,45 +6,45 @@ ...@@ -6,45 +6,45 @@
using namespace node_sqlite3; using namespace node_sqlite3;
Nan::Persistent<FunctionTemplate> Database::constructor_template; Napi::FunctionReference Database::constructor;
NAN_MODULE_INIT(Database::Init) { Napi::Object Database::Init(Napi::Env env, Napi::Object exports) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); Napi::FunctionReference t = Napi::Function::New(env, New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Database").ToLocalChecked());
Nan::SetPrototypeMethod(t, "close", Close); t->SetClassName(Napi::String::New(env, "Database"));
Nan::SetPrototypeMethod(t, "exec", Exec);
Nan::SetPrototypeMethod(t, "wait", Wait); InstanceMethod("close", &Close),
Nan::SetPrototypeMethod(t, "loadExtension", LoadExtension); InstanceMethod("exec", &Exec),
Nan::SetPrototypeMethod(t, "serialize", Serialize); InstanceMethod("wait", &Wait),
Nan::SetPrototypeMethod(t, "parallelize", Parallelize); InstanceMethod("loadExtension", &LoadExtension),
Nan::SetPrototypeMethod(t, "configure", Configure); InstanceMethod("serialize", &Serialize),
Nan::SetPrototypeMethod(t, "interrupt", Interrupt); InstanceMethod("parallelize", &Parallelize),
InstanceMethod("configure", &Configure),
InstanceMethod("interrupt", &Interrupt),
NODE_SET_GETTER(t, "open", OpenGetter); NODE_SET_GETTER(t, "open", OpenGetter);
constructor_template.Reset(t); constructor.Reset(t);
Nan::Set(target, Nan::New("Database").ToLocalChecked(), (target).Set(Napi::String::New(env, "Database"),
Nan::GetFunction(t).ToLocalChecked()); Napi::GetFunction(t));
} }
void Database::Process() { void Database::Process() {
Nan::HandleScope scope; Napi::HandleScope scope(env);
if (!open && locked && !queue.empty()) { if (!open && locked && !queue.empty()) {
EXCEPTION("Database handle is closed", SQLITE_MISUSE, exception); EXCEPTION("Database handle is closed", SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
bool called = false; bool called = false;
// Call all callbacks with the error object. // Call all callbacks with the error object.
while (!queue.empty()) { while (!queue.empty()) {
Call* call = queue.front(); Call* call = queue.front();
Local<Function> cb = Nan::New(call->baton->callback); Napi::Function cb = Napi::New(env, call->baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(this->handle(), cb, 1, argv); TRY_CATCH_CALL(this->handle(), cb, 1, argv);
called = true; called = true;
...@@ -59,7 +59,7 @@ void Database::Process() { ...@@ -59,7 +59,7 @@ void Database::Process() {
// When we couldn't call a callback function, emit an error on the // When we couldn't call a callback function, emit an error on the
// Database object. // Database object.
if (!called) { if (!called) {
Local<Value> info[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value info[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(handle(), 2, info); EMIT_EVENT(handle(), 2, info);
} }
return; return;
...@@ -82,17 +82,17 @@ void Database::Process() { ...@@ -82,17 +82,17 @@ void Database::Process() {
} }
void Database::Schedule(Work_Callback callback, Baton* baton, bool exclusive) { void Database::Schedule(Work_Callback callback, Baton* baton, bool exclusive) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
if (!open && locked) { if (!open && locked) {
EXCEPTION("Database is closed", SQLITE_MISUSE, exception); EXCEPTION("Database is closed", SQLITE_MISUSE, exception);
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
TRY_CATCH_CALL(handle(), cb, 1, argv); TRY_CATCH_CALL(handle(), cb, 1, argv);
} }
else { else {
Local<Value> argv[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value argv[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(handle(), 2, argv); EMIT_EVENT(handle(), 2, argv);
} }
return; return;
...@@ -107,37 +107,38 @@ void Database::Schedule(Work_Callback callback, Baton* baton, bool exclusive) { ...@@ -107,37 +107,38 @@ void Database::Schedule(Work_Callback callback, Baton* baton, bool exclusive) {
} }
} }
NAN_METHOD(Database::New) { Napi::Value Database::New(const Napi::CallbackInfo& info) {
if (!info.IsConstructCall()) { if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to create new Database objects"); Napi::TypeError::New(env, "Use the new operator to create new Database objects").ThrowAsJavaScriptException();
return env.Null();
} }
REQUIRE_ARGUMENT_STRING(0, filename); REQUIRE_ARGUMENT_STRING(0, filename);
int pos = 1; int pos = 1;
int mode; int mode;
if (info.Length() >= pos && info[pos]->IsInt32()) { if (info.Length() >= pos && info[pos].IsNumber()) {
mode = Nan::To<int>(info[pos++]).FromJust(); mode = info[pos++].As<Napi::Number>().Int32Value();
} else { } else {
mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
} }
Local<Function> callback; Napi::Function callback;
if (info.Length() >= pos && info[pos]->IsFunction()) { if (info.Length() >= pos && info[pos].IsFunction()) {
callback = Local<Function>::Cast(info[pos++]); callback = info[pos++].As<Napi::Function>();
} }
Database* db = new Database(); Database* db = new Database();
db->Wrap(info.This()); db->Wrap(info.This());
Nan::ForceSet(info.This(), Nan::New("filename").ToLocalChecked(), info[0].As<String>(), ReadOnly); info.This().DefineProperty(Napi::String::New(env, "filename"), info[0].As<Napi::String>(), ReadOnly);
Nan::ForceSet(info.This(), Nan::New("mode").ToLocalChecked(), Nan::New(mode), ReadOnly); info.This().DefineProperty(Napi::String::New(env, "mode"), Napi::New(env, mode), ReadOnly);
// Start opening the database. // Start opening the database.
OpenBaton* baton = new OpenBaton(db, callback, *filename, mode); OpenBaton* baton = new OpenBaton(db, callback, *filename, mode);
Work_BeginOpen(baton); Work_BeginOpen(baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Database::Work_BeginOpen(Baton* baton) { void Database::Work_BeginOpen(Baton* baton) {
...@@ -169,33 +170,33 @@ void Database::Work_Open(uv_work_t* req) { ...@@ -169,33 +170,33 @@ void Database::Work_Open(uv_work_t* req) {
} }
void Database::Work_AfterOpen(uv_work_t* req) { void Database::Work_AfterOpen(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
OpenBaton* baton = static_cast<OpenBaton*>(req->data); OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db; Database* db = baton->db;
Local<Value> argv[1]; Napi::Value argv[1];
if (baton->status != SQLITE_OK) { if (baton->status != SQLITE_OK) {
EXCEPTION(baton->message, baton->status, exception); EXCEPTION(baton->message, baton->status, exception);
argv[0] = exception; argv[0] = exception;
} }
else { else {
db->open = true; db->open = true;
argv[0] = Nan::Null(); argv[0] = env.Null();
} }
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(db->handle(), cb, 1, argv); TRY_CATCH_CALL(db->handle(), cb, 1, argv);
} }
else if (!db->open) { else if (!db->open) {
Local<Value> info[] = { Nan::New("error").ToLocalChecked(), argv[0] }; Napi::Value info[] = { Napi::String::New(env, "error"), argv[0] };
EMIT_EVENT(db->handle(), 2, info); EMIT_EVENT(db->handle(), 2, info);
} }
if (db->open) { if (db->open) {
Local<Value> info[] = { Nan::New("open").ToLocalChecked() }; Napi::Value info[] = { Napi::String::New(env, "open") };
EMIT_EVENT(db->handle(), 1, info); EMIT_EVENT(db->handle(), 1, info);
db->Process(); db->Process();
} }
...@@ -203,19 +204,19 @@ void Database::Work_AfterOpen(uv_work_t* req) { ...@@ -203,19 +204,19 @@ void Database::Work_AfterOpen(uv_work_t* req) {
delete baton; delete baton;
} }
NAN_GETTER(Database::OpenGetter) { Napi::Value Database::OpenGetter(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
info.GetReturnValue().Set(db->open); return db->open;
} }
NAN_METHOD(Database::Close) { Napi::Value Database::Close(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
OPTIONAL_ARGUMENT_FUNCTION(0, callback); OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback); Baton* baton = new Baton(db, callback);
db->Schedule(Work_BeginClose, baton, true); db->Schedule(Work_BeginClose, baton, true);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Database::Work_BeginClose(Baton* baton) { void Database::Work_BeginClose(Baton* baton) {
...@@ -247,14 +248,14 @@ void Database::Work_Close(uv_work_t* req) { ...@@ -247,14 +248,14 @@ void Database::Work_Close(uv_work_t* req) {
} }
void Database::Work_AfterClose(uv_work_t* req) { void Database::Work_AfterClose(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Baton* baton = static_cast<Baton*>(req->data); Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db; Database* db = baton->db;
db->closing = false; db->closing = false;
Local<Value> argv[1]; Napi::Value argv[1];
if (baton->status != SQLITE_OK) { if (baton->status != SQLITE_OK) {
EXCEPTION(baton->message, baton->status, exception); EXCEPTION(baton->message, baton->status, exception);
argv[0] = exception; argv[0] = exception;
...@@ -263,22 +264,22 @@ void Database::Work_AfterClose(uv_work_t* req) { ...@@ -263,22 +264,22 @@ void Database::Work_AfterClose(uv_work_t* req) {
db->open = false; db->open = false;
// Leave db->locked to indicate that this db object has reached // Leave db->locked to indicate that this db object has reached
// the end of its life. // the end of its life.
argv[0] = Nan::Null(); argv[0] = env.Null();
} }
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
// Fire callbacks. // Fire callbacks.
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(db->handle(), cb, 1, argv); TRY_CATCH_CALL(db->handle(), cb, 1, argv);
} }
else if (db->open) { else if (db->open) {
Local<Value> info[] = { Nan::New("error").ToLocalChecked(), argv[0] }; Napi::Value info[] = { Napi::String::New(env, "error"), argv[0] };
EMIT_EVENT(db->handle(), 2, info); EMIT_EVENT(db->handle(), 2, info);
} }
if (!db->open) { if (!db->open) {
Local<Value> info[] = { Nan::New("close").ToLocalChecked(), argv[0] }; Napi::Value info[] = { Napi::String::New(env, "close"), argv[0] };
EMIT_EVENT(db->handle(), 1, info); EMIT_EVENT(db->handle(), 1, info);
db->Process(); db->Process();
} }
...@@ -286,8 +287,8 @@ void Database::Work_AfterClose(uv_work_t* req) { ...@@ -286,8 +287,8 @@ void Database::Work_AfterClose(uv_work_t* req) {
delete baton; delete baton;
} }
NAN_METHOD(Database::Serialize) { Napi::Value Database::Serialize(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
OPTIONAL_ARGUMENT_FUNCTION(0, callback); OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize; bool before = db->serialize;
...@@ -300,11 +301,11 @@ NAN_METHOD(Database::Serialize) { ...@@ -300,11 +301,11 @@ NAN_METHOD(Database::Serialize) {
db->Process(); db->Process();
info.GetReturnValue().Set(info.This()); return info.This();
} }
NAN_METHOD(Database::Parallelize) { Napi::Value Database::Parallelize(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
OPTIONAL_ARGUMENT_FUNCTION(0, callback); OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize; bool before = db->serialize;
...@@ -317,61 +318,64 @@ NAN_METHOD(Database::Parallelize) { ...@@ -317,61 +318,64 @@ NAN_METHOD(Database::Parallelize) {
db->Process(); db->Process();
info.GetReturnValue().Set(info.This()); return info.This();
} }
NAN_METHOD(Database::Configure) { Napi::Value Database::Configure(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
REQUIRE_ARGUMENTS(2); REQUIRE_ARGUMENTS(2);
if (Nan::Equals(info[0], Nan::New("trace").ToLocalChecked()).FromJust()) { if (info[0].StrictEquals( Napi::String::New(env, "trace"))) {
Local<Function> handle; Napi::Function handle;
Baton* baton = new Baton(db, handle); Baton* baton = new Baton(db, handle);
db->Schedule(RegisterTraceCallback, baton); db->Schedule(RegisterTraceCallback, baton);
} }
else if (Nan::Equals(info[0], Nan::New("profile").ToLocalChecked()).FromJust()) { else if (info[0].StrictEquals( Napi::String::New(env, "profile"))) {
Local<Function> handle; Napi::Function handle;
Baton* baton = new Baton(db, handle); Baton* baton = new Baton(db, handle);
db->Schedule(RegisterProfileCallback, baton); db->Schedule(RegisterProfileCallback, baton);
} }
else if (Nan::Equals(info[0], Nan::New("busyTimeout").ToLocalChecked()).FromJust()) { else if (info[0].StrictEquals( Napi::String::New(env, "busyTimeout"))) {
if (!info[1]->IsInt32()) { if (!info[1].IsNumber()) {
return Nan::ThrowTypeError("Value must be an integer"); Napi::TypeError::New(env, "Value must be an integer").ThrowAsJavaScriptException();
return env.Null();
} }
Local<Function> handle; Napi::Function handle;
Baton* baton = new Baton(db, handle); Baton* baton = new Baton(db, handle);
baton->status = Nan::To<int>(info[1]).FromJust(); baton->status = info[1].As<Napi::Number>().Int32Value();
db->Schedule(SetBusyTimeout, baton); db->Schedule(SetBusyTimeout, baton);
} }
else { else {
return Nan::ThrowError(Exception::Error(String::Concat( return Napi::ThrowError(Exception::Error(String::Concat(
#if V8_MAJOR_VERSION > 6 #if V8_MAJOR_VERSION > 6
info.GetIsolate(), info.GetIsolate(),
#endif #endif
Nan::To<String>(info[0]).ToLocalChecked(), info[0].To<Napi::String>(),
Nan::New(" is not a valid configuration option").ToLocalChecked() Napi::String::New(env, " is not a valid configuration option")
))); )));
} }
db->Process(); db->Process();
info.GetReturnValue().Set(info.This()); return info.This();
} }
NAN_METHOD(Database::Interrupt) { Napi::Value Database::Interrupt(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
if (!db->open) { if (!db->open) {
return Nan::ThrowError("Database is not open"); Napi::Error::New(env, "Database is not open").ThrowAsJavaScriptException();
return env.Null();
} }
if (db->closing) { if (db->closing) {
return Nan::ThrowError("Database is closing"); Napi::Error::New(env, "Database is closing").ThrowAsJavaScriptException();
return env.Null();
} }
sqlite3_interrupt(db->_handle); sqlite3_interrupt(db->_handle);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Database::SetBusyTimeout(Baton* baton) { void Database::SetBusyTimeout(Baton* baton) {
...@@ -412,11 +416,11 @@ void Database::TraceCallback(void* db, const char* sql) { ...@@ -412,11 +416,11 @@ void Database::TraceCallback(void* db, const char* sql) {
void Database::TraceCallback(Database* db, std::string* sql) { void Database::TraceCallback(Database* db, std::string* sql) {
// Note: This function is called in the main V8 thread. // Note: This function is called in the main V8 thread.
Nan::HandleScope scope; Napi::HandleScope scope(env);
Local<Value> argv[] = { Napi::Value argv[] = {
Nan::New("trace").ToLocalChecked(), Napi::String::New(env, "trace"),
Nan::New(sql->c_str()).ToLocalChecked() Napi::New(env, sql->c_str())
}; };
EMIT_EVENT(db->handle(), 2, argv); EMIT_EVENT(db->handle(), 2, argv);
delete sql; delete sql;
...@@ -452,12 +456,12 @@ void Database::ProfileCallback(void* db, const char* sql, sqlite3_uint64 nsecs) ...@@ -452,12 +456,12 @@ void Database::ProfileCallback(void* db, const char* sql, sqlite3_uint64 nsecs)
} }
void Database::ProfileCallback(Database *db, ProfileInfo* info) { void Database::ProfileCallback(Database *db, ProfileInfo* info) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Local<Value> argv[] = { Napi::Value argv[] = {
Nan::New("profile").ToLocalChecked(), Napi::String::New(env, "profile"),
Nan::New(info->sql.c_str()).ToLocalChecked(), Napi::New(env, info->sql.c_str()),
Nan::New<Number>((double)info->nsecs / 1000000.0) Napi::Number::New(env, (double)info->nsecs / 1000000.0)
}; };
EMIT_EVENT(db->handle(), 3, argv); EMIT_EVENT(db->handle(), 3, argv);
delete info; delete info;
...@@ -496,20 +500,20 @@ void Database::UpdateCallback(void* db, int type, const char* database, ...@@ -496,20 +500,20 @@ void Database::UpdateCallback(void* db, int type, const char* database,
} }
void Database::UpdateCallback(Database *db, UpdateInfo* info) { void Database::UpdateCallback(Database *db, UpdateInfo* info) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Local<Value> argv[] = { Napi::Value argv[] = {
Nan::New(sqlite_authorizer_string(info->type)).ToLocalChecked(), Napi::New(env, sqlite_authorizer_string(info->type)),
Nan::New(info->database.c_str()).ToLocalChecked(), Napi::New(env, info->database.c_str()),
Nan::New(info->table.c_str()).ToLocalChecked(), Napi::New(env, info->table.c_str()),
Nan::New<Number>(info->rowid), Napi::Number::New(env, info->rowid),
}; };
EMIT_EVENT(db->handle(), 4, argv); EMIT_EVENT(db->handle(), 4, argv);
delete info; delete info;
} }
NAN_METHOD(Database::Exec) { Napi::Value Database::Exec(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
REQUIRE_ARGUMENT_STRING(0, sql); REQUIRE_ARGUMENT_STRING(0, sql);
OPTIONAL_ARGUMENT_FUNCTION(1, callback); OPTIONAL_ARGUMENT_FUNCTION(1, callback);
...@@ -517,7 +521,7 @@ NAN_METHOD(Database::Exec) { ...@@ -517,7 +521,7 @@ NAN_METHOD(Database::Exec) {
Baton* baton = new ExecBaton(db, callback, *sql); Baton* baton = new ExecBaton(db, callback, *sql);
db->Schedule(Work_BeginExec, baton, true); db->Schedule(Work_BeginExec, baton, true);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Database::Work_BeginExec(Baton* baton) { void Database::Work_BeginExec(Baton* baton) {
...@@ -549,27 +553,27 @@ void Database::Work_Exec(uv_work_t* req) { ...@@ -549,27 +553,27 @@ void Database::Work_Exec(uv_work_t* req) {
} }
void Database::Work_AfterExec(uv_work_t* req) { void Database::Work_AfterExec(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
ExecBaton* baton = static_cast<ExecBaton*>(req->data); ExecBaton* baton = static_cast<ExecBaton*>(req->data);
Database* db = baton->db; Database* db = baton->db;
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (baton->status != SQLITE_OK) { if (baton->status != SQLITE_OK) {
EXCEPTION(baton->message, baton->status, exception); EXCEPTION(baton->message, baton->status, exception);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
TRY_CATCH_CALL(db->handle(), cb, 1, argv); TRY_CATCH_CALL(db->handle(), cb, 1, argv);
} }
else { else {
Local<Value> info[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value info[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(db->handle(), 2, info); EMIT_EVENT(db->handle(), 2, info);
} }
} }
else if (!cb.IsEmpty() && cb->IsFunction()) { else if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(db->handle(), cb, 1, argv); TRY_CATCH_CALL(db->handle(), cb, 1, argv);
} }
...@@ -578,28 +582,28 @@ void Database::Work_AfterExec(uv_work_t* req) { ...@@ -578,28 +582,28 @@ void Database::Work_AfterExec(uv_work_t* req) {
delete baton; delete baton;
} }
NAN_METHOD(Database::Wait) { Napi::Value Database::Wait(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
OPTIONAL_ARGUMENT_FUNCTION(0, callback); OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback); Baton* baton = new Baton(db, callback);
db->Schedule(Work_Wait, baton, true); db->Schedule(Work_Wait, baton, true);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Database::Work_Wait(Baton* baton) { void Database::Work_Wait(Baton* baton) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
assert(baton->db->locked); assert(baton->db->locked);
assert(baton->db->open); assert(baton->db->open);
assert(baton->db->_handle); assert(baton->db->_handle);
assert(baton->db->pending == 0); assert(baton->db->pending == 0);
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(baton->db->handle(), cb, 1, argv); TRY_CATCH_CALL(baton->db->handle(), cb, 1, argv);
} }
...@@ -608,8 +612,8 @@ void Database::Work_Wait(Baton* baton) { ...@@ -608,8 +612,8 @@ void Database::Work_Wait(Baton* baton) {
delete baton; delete baton;
} }
NAN_METHOD(Database::LoadExtension) { Napi::Value Database::LoadExtension(const Napi::CallbackInfo& info) {
Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); Database* db = this;
REQUIRE_ARGUMENT_STRING(0, filename); REQUIRE_ARGUMENT_STRING(0, filename);
OPTIONAL_ARGUMENT_FUNCTION(1, callback); OPTIONAL_ARGUMENT_FUNCTION(1, callback);
...@@ -617,7 +621,7 @@ NAN_METHOD(Database::LoadExtension) { ...@@ -617,7 +621,7 @@ NAN_METHOD(Database::LoadExtension) {
Baton* baton = new LoadExtensionBaton(db, callback, *filename); Baton* baton = new LoadExtensionBaton(db, callback, *filename);
db->Schedule(Work_BeginLoadExtension, baton, true); db->Schedule(Work_BeginLoadExtension, baton, true);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Database::Work_BeginLoadExtension(Baton* baton) { void Database::Work_BeginLoadExtension(Baton* baton) {
...@@ -652,26 +656,26 @@ void Database::Work_LoadExtension(uv_work_t* req) { ...@@ -652,26 +656,26 @@ void Database::Work_LoadExtension(uv_work_t* req) {
} }
void Database::Work_AfterLoadExtension(uv_work_t* req) { void Database::Work_AfterLoadExtension(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data); LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data);
Database* db = baton->db; Database* db = baton->db;
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (baton->status != SQLITE_OK) { if (baton->status != SQLITE_OK) {
EXCEPTION(baton->message, baton->status, exception); EXCEPTION(baton->message, baton->status, exception);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
TRY_CATCH_CALL(db->handle(), cb, 1, argv); TRY_CATCH_CALL(db->handle(), cb, 1, argv);
} }
else { else {
Local<Value> info[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value info[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(db->handle(), 2, info); EMIT_EVENT(db->handle(), 2, info);
} }
} }
else if (!cb.IsEmpty() && cb->IsFunction()) { else if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(db->handle(), cb, 1, argv); TRY_CATCH_CALL(db->handle(), cb, 1, argv);
} }
......
...@@ -7,37 +7,39 @@ ...@@ -7,37 +7,39 @@
#include <queue> #include <queue>
#include <sqlite3.h> #include <sqlite3.h>
#include <nan.h> #include <napi.h>
#include <uv.h>
#include "async.h" #include "async.h"
using namespace v8; using namespace Napi;
namespace node_sqlite3 { namespace node_sqlite3 {
class Database; class Database;
class Database : public Nan::ObjectWrap { class Database : public Napi::ObjectWrap<Database> {
public: public:
static Nan::Persistent<FunctionTemplate> constructor_template; static Napi::FunctionReference constructor;
static NAN_MODULE_INIT(Init); static Napi::Object Init(Napi::Env env, Napi::Object exports);
static inline bool HasInstance(Local<Value> val) { static inline bool HasInstance(Napi::Value val) {
Nan::HandleScope scope; Napi::Env env = val.Env();
if (!val->IsObject()) return false; Napi::HandleScope scope(env);
Local<Object> obj = val.As<Object>(); if (!val.IsObject()) return false;
return Nan::New(constructor_template)->HasInstance(obj); Napi::Object obj = val.As<Napi::Object>();
return Napi::New(env, constructor)->HasInstance(obj);
} }
struct Baton { struct Baton {
uv_work_t request; uv_work_t request;
Database* db; Database* db;
Nan::Persistent<Function> callback; Napi::FunctionReference callback;
int status; int status;
std::string message; std::string message;
Baton(Database* db_, Local<Function> cb_) : Baton(Database* db_, Napi::Function cb_) :
db(db_), status(SQLITE_OK) { db(db_), status(SQLITE_OK) {
db->Ref(); db->Ref();
request.data = this; request.data = this;
...@@ -52,19 +54,19 @@ public: ...@@ -52,19 +54,19 @@ public:
struct OpenBaton : Baton { struct OpenBaton : Baton {
std::string filename; std::string filename;
int mode; int mode;
OpenBaton(Database* db_, Local<Function> cb_, const char* filename_, int mode_) : OpenBaton(Database* db_, Napi::Function cb_, const char* filename_, int mode_) :
Baton(db_, cb_), filename(filename_), mode(mode_) {} Baton(db_, cb_), filename(filename_), mode(mode_) {}
}; };
struct ExecBaton : Baton { struct ExecBaton : Baton {
std::string sql; std::string sql;
ExecBaton(Database* db_, Local<Function> cb_, const char* sql_) : ExecBaton(Database* db_, Napi::Function cb_, const char* sql_) :
Baton(db_, cb_), sql(sql_) {} Baton(db_, cb_), sql(sql_) {}
}; };
struct LoadExtensionBaton : Baton { struct LoadExtensionBaton : Baton {
std::string filename; std::string filename;
LoadExtensionBaton(Database* db_, Local<Function> cb_, const char* filename_) : LoadExtensionBaton(Database* db_, Napi::Function cb_, const char* filename_) :
Baton(db_, cb_), filename(filename_) {} Baton(db_, cb_), filename(filename_) {}
}; };
...@@ -101,7 +103,7 @@ public: ...@@ -101,7 +103,7 @@ public:
friend class Backup; friend class Backup;
protected: protected:
Database() : Nan::ObjectWrap(), Database() : Napi::ObjectWrap<Database>(),
_handle(NULL), _handle(NULL),
open(false), open(false),
closing(false), closing(false),
...@@ -120,40 +122,40 @@ protected: ...@@ -120,40 +122,40 @@ protected:
open = false; open = false;
} }
static NAN_METHOD(New); static Napi::Value New(const Napi::CallbackInfo& info);
static void Work_BeginOpen(Baton* baton); static void Work_BeginOpen(Baton* baton);
static void Work_Open(uv_work_t* req); static void Work_Open(uv_work_t* req);
static void Work_AfterOpen(uv_work_t* req); static void Work_AfterOpen(uv_work_t* req);
static NAN_GETTER(OpenGetter); Napi::Value OpenGetter(const Napi::CallbackInfo& info);
void Schedule(Work_Callback callback, Baton* baton, bool exclusive = false); void Schedule(Work_Callback callback, Baton* baton, bool exclusive = false);
void Process(); void Process();
static NAN_METHOD(Exec); static Napi::Value Exec(const Napi::CallbackInfo& info);
static void Work_BeginExec(Baton* baton); static void Work_BeginExec(Baton* baton);
static void Work_Exec(uv_work_t* req); static void Work_Exec(uv_work_t* req);
static void Work_AfterExec(uv_work_t* req); static void Work_AfterExec(uv_work_t* req);
static NAN_METHOD(Wait); static Napi::Value Wait(const Napi::CallbackInfo& info);
static void Work_Wait(Baton* baton); static void Work_Wait(Baton* baton);
static NAN_METHOD(Close); static Napi::Value Close(const Napi::CallbackInfo& info);
static void Work_BeginClose(Baton* baton); static void Work_BeginClose(Baton* baton);
static void Work_Close(uv_work_t* req); static void Work_Close(uv_work_t* req);
static void Work_AfterClose(uv_work_t* req); static void Work_AfterClose(uv_work_t* req);
static NAN_METHOD(LoadExtension); static Napi::Value LoadExtension(const Napi::CallbackInfo& info);
static void Work_BeginLoadExtension(Baton* baton); static void Work_BeginLoadExtension(Baton* baton);
static void Work_LoadExtension(uv_work_t* req); static void Work_LoadExtension(uv_work_t* req);
static void Work_AfterLoadExtension(uv_work_t* req); static void Work_AfterLoadExtension(uv_work_t* req);
static NAN_METHOD(Serialize); static Napi::Value Serialize(const Napi::CallbackInfo& info);
static NAN_METHOD(Parallelize); static Napi::Value Parallelize(const Napi::CallbackInfo& info);
static NAN_METHOD(Configure); static Napi::Value Configure(const Napi::CallbackInfo& info);
static NAN_METHOD(Interrupt); static Napi::Value Interrupt(const Napi::CallbackInfo& info);
static void SetBusyTimeout(Baton* baton); static void SetBusyTimeout(Baton* baton);
......
...@@ -7,43 +7,49 @@ const char* sqlite_authorizer_string(int type); ...@@ -7,43 +7,49 @@ const char* sqlite_authorizer_string(int type);
#define REQUIRE_ARGUMENTS(n) \ #define REQUIRE_ARGUMENTS(n) \
if (info.Length() < (n)) { \ if (info.Length() < (n)) { \
return Nan::ThrowTypeError("Expected " #n "arguments"); \ Napi::TypeError::New(env, "Expected " #n "arguments").ThrowAsJavaScriptException();
return env.Null(); \
} }
#define REQUIRE_ARGUMENT_EXTERNAL(i, var) \ #define REQUIRE_ARGUMENT_EXTERNAL(i, var) \
if (info.Length() <= (i) || !info[i]->IsExternal()) { \ if (info.Length() <= (i) || !info[i].IsExternal()) { \
return Nan::ThrowTypeError("Argument " #i " invalid"); \ Napi::TypeError::New(env, "Argument " #i " invalid").ThrowAsJavaScriptException();
return env.Null(); \
} \ } \
Local<External> var = Local<External>::Cast(info[i]); Napi::External var = info[i].As<Napi::External>();
#define REQUIRE_ARGUMENT_FUNCTION(i, var) \ #define REQUIRE_ARGUMENT_FUNCTION(i, var) \
if (info.Length() <= (i) || !info[i]->IsFunction()) { \ if (info.Length() <= (i) || !info[i].IsFunction()) { \
return Nan::ThrowTypeError("Argument " #i " must be a function"); \ Napi::TypeError::New(env, "Argument " #i " must be a function").ThrowAsJavaScriptException();
return env.Null(); \
} \ } \
Local<Function> var = Local<Function>::Cast(info[i]); Napi::Function var = info[i].As<Napi::Function>();
#define REQUIRE_ARGUMENT_STRING(i, var) \ #define REQUIRE_ARGUMENT_STRING(i, var) \
if (info.Length() <= (i) || !info[i]->IsString()) { \ if (info.Length() <= (i) || !info[i].IsString()) { \
return Nan::ThrowTypeError("Argument " #i " must be a string"); \ Napi::TypeError::New(env, "Argument " #i " must be a string").ThrowAsJavaScriptException();
return env.Null(); \
} \ } \
Nan::Utf8String var(info[i]); std::string var = info[i].As<Napi::String>();
#define REQUIRE_ARGUMENT_INTEGER(i, var) \ #define REQUIRE_ARGUMENT_INTEGER(i, var) \
if (info.Length() <= (i) || !info[i]->IsInt32()) { \ if (info.Length() <= (i) || !info[i].IsNumber()) { \
return Nan::ThrowTypeError("Argument " #i " must be an integer"); \ Napi::TypeError::New(env, "Argument " #i " must be an integer").ThrowAsJavaScriptException();
return env.Null(); \
} \ } \
int var(Nan::To<int32_t>(info[i]).FromJust()); int var(info[i].As<Napi::Number>().Int32Value());
#define OPTIONAL_ARGUMENT_FUNCTION(i, var) \ #define OPTIONAL_ARGUMENT_FUNCTION(i, var) \
Local<Function> var; \ Napi::Function var; \
if (info.Length() > i && !info[i]->IsUndefined()) { \ if (info.Length() > i && !info[i].IsUndefined()) { \
if (!info[i]->IsFunction()) { \ if (!info[i].IsFunction()) { \
return Nan::ThrowTypeError("Argument " #i " must be a function"); \ Napi::TypeError::New(env, "Argument " #i " must be a function").ThrowAsJavaScriptException();
return env.Null(); \
} \ } \
var = Local<Function>::Cast(info[i]); \ var = info[i].As<Napi::Function>(); \
} }
...@@ -52,67 +58,68 @@ const char* sqlite_authorizer_string(int type); ...@@ -52,67 +58,68 @@ const char* sqlite_authorizer_string(int type);
if (info.Length() <= (i)) { \ if (info.Length() <= (i)) { \
var = (default); \ var = (default); \
} \ } \
else if (info[i]->IsInt32()) { \ else if (info[i].IsNumber()) { \
var = Nan::To<int32_t>(info[i]).FromJust(); \ var = info[i].As<Napi::Number>().Int32Value(); \
} \ } \
else { \ else { \
return Nan::ThrowTypeError("Argument " #i " must be an integer"); \ Napi::TypeError::New(env, "Argument " #i " must be an integer").ThrowAsJavaScriptException();
return env.Null(); \
} }
#define DEFINE_CONSTANT_INTEGER(target, constant, name) \ #define DEFINE_CONSTANT_INTEGER(target, constant, name) \
Nan::ForceSet(target, \ target->DefineProperty( \
Nan::New(#name).ToLocalChecked(), \ Napi::New(env, #name), \
Nan::New<Integer>(constant), \ Napi::Number::New(env, constant), \
static_cast<PropertyAttribute>(ReadOnly | DontDelete) \ static_cast<napi_property_attributes>(napi_enumerable | napi_configurable) \
); );
#define DEFINE_CONSTANT_STRING(target, constant, name) \ #define DEFINE_CONSTANT_STRING(target, constant, name) \
Nan::ForceSet(target, \ target->DefineProperty( \
Nan::New(#name).ToLocalChecked(), \ Napi::New(env, #name), \
Nan::New(constant).ToLocalChecked(), \ Napi::New(env, constant), \
static_cast<PropertyAttribute>(ReadOnly | DontDelete) \ static_cast<napi_property_attributes>(napi_enumerable | napi_configurable) \
); );
#define NODE_SET_GETTER(target, name, function) \ #define NODE_SET_GETTER(target, name, function) \
Nan::SetAccessor((target)->InstanceTemplate(), \ Napi::SetAccessor((target)->InstanceTemplate(), \
Nan::New(name).ToLocalChecked(), (function)); Napi::New(env, name), (function));
#define NODE_SET_SETTER(target, name, getter, setter) \ #define NODE_SET_SETTER(target, name, getter, setter) \
Nan::SetAccessor((target)->InstanceTemplate(), \ Napi::SetAccessor((target)->InstanceTemplate(), \
Nan::New(name).ToLocalChecked(), getter, setter); Napi::New(env, name), getter, setter);
#define GET_STRING(source, name, property) \ #define GET_STRING(source, name, property) \
Nan::Utf8String name(Nan::Get(source, \ std::string name = (source).Get(\
Nan::New(prop).ToLocalChecked()).ToLocalChecked()); Napi::New(env, prop.As<Napi::String>()));
#define GET_INTEGER(source, name, prop) \ #define GET_INTEGER(source, name, prop) \
int name = Nan::To<int>(Nan::Get(source, \ int name = Napi::To<int>((source).Get(\
Nan::New(property).ToLocalChecked()).ToLocalChecked()).FromJust(); Napi::New(env, property)));
#define EXCEPTION(msg, errno, name) \ #define EXCEPTION(msg, errno, name) \
Local<Value> name = Exception::Error(Nan::New( \ Napi::Value name = Exception::Error(Napi::New(env, \
std::string(sqlite_code_string(errno)) + \ std::string(sqlite_code_string(errno)) + \
std::string(": ") + std::string(msg) \ std::string(": ") + std::string(msg) \
).ToLocalChecked()); \ )); \
Local<Object> name ##_obj = name.As<Object>(); \ Napi::Object name ##_obj = name.As<Napi::Object>(); \
Nan::Set(name ##_obj, Nan::New("errno").ToLocalChecked(), Nan::New(errno));\ (name ##_obj).Set(Napi::String::New(env, "errno"), Napi::New(env, errno));\
Nan::Set(name ##_obj, Nan::New("code").ToLocalChecked(), \ (name ##_obj).Set(Napi::String::New(env, "code"), \
Nan::New(sqlite_code_string(errno)).ToLocalChecked()); Napi::New(env, sqlite_code_string(errno)));
#define EMIT_EVENT(obj, argc, argv) \ #define EMIT_EVENT(obj, argc, argv) \
TRY_CATCH_CALL((obj), \ TRY_CATCH_CALL((obj), \
Nan::Get(obj, \ (obj).Get(\
Nan::New("emit").ToLocalChecked()).ToLocalChecked().As<Function>(),\ Napi::String::New(env, "emit")).As<Napi::Function>(),\
argc, argv \ argc, argv \
); );
#define TRY_CATCH_CALL(context, callback, argc, argv) \ #define TRY_CATCH_CALL(context, callback, argc, argv) \
Nan::MakeCallback((context), (callback), (argc), (argv)) (callback).MakeCallback((context), (argc), (argv))
#define WORK_DEFINITION(name) \ #define WORK_DEFINITION(name) \
static NAN_METHOD(name); \ static Napi::Value name(const Napi::CallbackInfo& info); \
static void Work_Begin##name(Baton* baton); \ static void Work_Begin##name(Baton* baton); \
static void Work_##name(uv_work_t* req); \ static void Work_##name(uv_work_t* req); \
static void Work_After##name(uv_work_t* req); static void Work_After##name(uv_work_t* req);
......
...@@ -13,12 +13,12 @@ using namespace node_sqlite3; ...@@ -13,12 +13,12 @@ using namespace node_sqlite3;
namespace { namespace {
NAN_MODULE_INIT(RegisterModule) { Napi::Object RegisterModule(Napi::Env env, Napi::Object exports) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Database::Init(target); Database::Init(env, target, module);
Statement::Init(target); Statement::Init(env, target, module);
Backup::Init(target); Backup::Init(env, target, module);
DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READONLY, OPEN_READONLY); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READONLY, OPEN_READONLY);
DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READWRITE, OPEN_READWRITE); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READWRITE, OPEN_READWRITE);
...@@ -108,4 +108,4 @@ const char* sqlite_authorizer_string(int type) { ...@@ -108,4 +108,4 @@ const char* sqlite_authorizer_string(int type) {
} }
} }
NODE_MODULE(node_sqlite3, RegisterModule) NODE_API_MODULE(node_sqlite3, RegisterModule)
#include <string.h> #include <string.h>
#include <node.h> #include <napi.h>
#include <uv.h>
#include <node_buffer.h> #include <node_buffer.h>
#include <node_version.h> #include <node_version.h>
...@@ -9,27 +10,27 @@ ...@@ -9,27 +10,27 @@
using namespace node_sqlite3; using namespace node_sqlite3;
Nan::Persistent<FunctionTemplate> Statement::constructor_template; Napi::FunctionReference Statement::constructor;
NAN_MODULE_INIT(Statement::Init) { Napi::Object Statement::Init(Napi::Env env, Napi::Object exports) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); Napi::FunctionReference t = Napi::Function::New(env, New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Statement").ToLocalChecked());
Nan::SetPrototypeMethod(t, "bind", Bind); t->SetClassName(Napi::String::New(env, "Statement"));
Nan::SetPrototypeMethod(t, "get", Get);
Nan::SetPrototypeMethod(t, "run", Run);
Nan::SetPrototypeMethod(t, "all", All);
Nan::SetPrototypeMethod(t, "each", Each);
Nan::SetPrototypeMethod(t, "reset", Reset);
Nan::SetPrototypeMethod(t, "finalize", Finalize);
constructor_template.Reset(t); InstanceMethod("bind", &Bind),
Nan::Set(target, Nan::New("Statement").ToLocalChecked(), InstanceMethod("get", &Get),
Nan::GetFunction(t).ToLocalChecked()); InstanceMethod("run", &Run),
InstanceMethod("all", &All),
InstanceMethod("each", &Each),
InstanceMethod("reset", &Reset),
InstanceMethod("finalize", &Finalize),
constructor.Reset(t);
(target).Set(Napi::String::New(env, "Statement"),
Napi::GetFunction(t));
} }
void Statement::Process() { void Statement::Process() {
...@@ -60,56 +61,60 @@ void Statement::Schedule(Work_Callback callback, Baton* baton) { ...@@ -60,56 +61,60 @@ void Statement::Schedule(Work_Callback callback, Baton* baton) {
} }
template <class T> void Statement::Error(T* baton) { template <class T> void Statement::Error(T* baton) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Statement* stmt = baton->stmt; Statement* stmt = baton->stmt;
// Fail hard on logic errors. // Fail hard on logic errors.
assert(stmt->status != 0); assert(stmt->status != 0);
EXCEPTION(stmt->message, stmt->status, exception); EXCEPTION(stmt->message, stmt->status, exception);
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
TRY_CATCH_CALL(stmt->handle(), cb, 1, argv); TRY_CATCH_CALL(stmt->handle(), cb, 1, argv);
} }
else { else {
Local<Value> argv[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value argv[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(stmt->handle(), 2, argv); EMIT_EVENT(stmt->handle(), 2, argv);
} }
} }
// { Database db, String sql, Array params, Function callback } // { Database db, String sql, Array params, Function callback }
NAN_METHOD(Statement::New) { Napi::Value Statement::New(const Napi::CallbackInfo& info) {
if (!info.IsConstructCall()) { if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to create new Statement objects"); Napi::TypeError::New(env, "Use the new operator to create new Statement objects").ThrowAsJavaScriptException();
return env.Null();
} }
int length = info.Length(); int length = info.Length();
if (length <= 0 || !Database::HasInstance(info[0])) { if (length <= 0 || !Database::HasInstance(info[0])) {
return Nan::ThrowTypeError("Database object expected"); Napi::TypeError::New(env, "Database object expected").ThrowAsJavaScriptException();
return env.Null();
} }
else if (length <= 1 || !info[1]->IsString()) { else if (length <= 1 || !info[1].IsString()) {
return Nan::ThrowTypeError("SQL query expected"); Napi::TypeError::New(env, "SQL query expected").ThrowAsJavaScriptException();
return env.Null();
} }
else if (length > 2 && !info[2]->IsUndefined() && !info[2]->IsFunction()) { else if (length > 2 && !info[2].IsUndefined() && !info[2].IsFunction()) {
return Nan::ThrowTypeError("Callback expected"); Napi::TypeError::New(env, "Callback expected").ThrowAsJavaScriptException();
return env.Null();
} }
Database* db = Nan::ObjectWrap::Unwrap<Database>(info[0].As<Object>()); Database* db = info[0].As<Napi::Object>().Unwrap<Database>();
Local<String> sql = Local<String>::Cast(info[1]); Napi::String sql = info[1].As<Napi::String>();
Nan::ForceSet(info.This(),Nan::New("sql").ToLocalChecked(), sql, ReadOnly); info.This().DefineProperty(Napi::String::New(env, "sql"), sql, ReadOnly);
Statement* stmt = new Statement(db); Statement* stmt = new Statement(db);
stmt->Wrap(info.This()); stmt->Wrap(info.This());
PrepareBaton* baton = new PrepareBaton(db, Local<Function>::Cast(info[2]), stmt); PrepareBaton* baton = new PrepareBaton(db, info[2].As<Napi::Function>(), stmt);
baton->sql = std::string(*Nan::Utf8String(sql)); baton->sql = std::string(sql->As<Napi::String>().Utf8Value().c_str());
db->Schedule(Work_BeginPrepare, baton); db->Schedule(Work_BeginPrepare, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Statement::Work_BeginPrepare(Database::Baton* baton) { void Statement::Work_BeginPrepare(Database::Baton* baton) {
...@@ -145,7 +150,7 @@ void Statement::Work_Prepare(uv_work_t* req) { ...@@ -145,7 +150,7 @@ void Statement::Work_Prepare(uv_work_t* req) {
} }
void Statement::Work_AfterPrepare(uv_work_t* req) { void Statement::Work_AfterPrepare(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
STATEMENT_INIT(PrepareBaton); STATEMENT_INIT(PrepareBaton);
...@@ -155,9 +160,9 @@ void Statement::Work_AfterPrepare(uv_work_t* req) { ...@@ -155,9 +160,9 @@ void Statement::Work_AfterPrepare(uv_work_t* req) {
} }
else { else {
stmt->prepared = true; stmt->prepared = true;
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(stmt->handle(), cb, 1, argv); TRY_CATCH_CALL(stmt->handle(), cb, 1, argv);
} }
} }
...@@ -166,77 +171,77 @@ void Statement::Work_AfterPrepare(uv_work_t* req) { ...@@ -166,77 +171,77 @@ void Statement::Work_AfterPrepare(uv_work_t* req) {
} }
template <class T> Values::Field* template <class T> Values::Field*
Statement::BindParameter(const Local<Value> source, T pos) { Statement::BindParameter(const Napi::Value source, T pos) {
if (source->IsString() || source->IsRegExp()) { if (source.IsString() || source->IsRegExp()) {
Nan::Utf8String val(source); std::string val = source.As<Napi::String>();
return new Values::Text(pos, val.length(), *val); return new Values::Text(pos, val.Length(), *val);
} }
else if (source->IsInt32()) { else if (source.IsNumber()) {
return new Values::Integer(pos, Nan::To<int32_t>(source).FromJust()); return new Values::Integer(pos, source.As<Napi::Number>().Int32Value());
} }
else if (source->IsNumber()) { else if (source.IsNumber()) {
return new Values::Float(pos, Nan::To<double>(source).FromJust()); return new Values::Float(pos, source.As<Napi::Number>().DoubleValue());
} }
else if (source->IsBoolean()) { else if (source->IsBoolean()) {
return new Values::Integer(pos, Nan::To<bool>(source).FromJust() ? 1 : 0); return new Values::Integer(pos, source.As<Napi::Boolean>().Value() ? 1 : 0);
} }
else if (source->IsNull()) { else if (source->IsNull()) {
return new Values::Null(pos); return new Values::Null(pos);
} }
else if (Buffer::HasInstance(source)) { else if (source.IsBuffer()) {
Local<Object> buffer = Nan::To<Object>(source).ToLocalChecked(); Napi::Object buffer = source.To<Napi::Object>();
return new Values::Blob(pos, Buffer::Length(buffer), Buffer::Data(buffer)); return new Values::Blob(pos, Buffer::Length(buffer), Buffer::Data(buffer));
} }
else if (source->IsDate()) { else if (source->IsDate()) {
return new Values::Float(pos, Nan::To<double>(source).FromJust()); return new Values::Float(pos, source.As<Napi::Number>().DoubleValue());
} }
else { else {
return NULL; return NULL;
} }
} }
template <class T> T* Statement::Bind(Nan::NAN_METHOD_ARGS_TYPE info, int start, int last) { template <class T> T* Statement::Bind(const Napi::CallbackInfo& info, int start, int last) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
if (last < 0) last = info.Length(); if (last < 0) last = info.Length();
Local<Function> callback; Napi::Function callback;
if (last > start && info[last - 1]->IsFunction()) { if (last > start && info[last - 1]->IsFunction()) {
callback = Local<Function>::Cast(info[last - 1]); callback = info[last - 1].As<Napi::Function>();
last--; last--;
} }
T* baton = new T(this, callback); T* baton = new T(this, callback);
if (start < last) { if (start < last) {
if (info[start]->IsArray()) { if (info[start].IsArray()) {
Local<Array> array = Local<Array>::Cast(info[start]); Napi::Array array = info[start].As<Napi::Array>();
int length = array->Length(); int length = array->Length();
// Note: bind parameters start with 1. // Note: bind parameters start with 1.
for (int i = 0, pos = 1; i < length; i++, pos++) { for (int i = 0, pos = 1; i < length; i++, pos++) {
baton->parameters.push_back(BindParameter(Nan::Get(array, i).ToLocalChecked(), pos)); baton->parameters.push_back(BindParameter((array).Get(i), pos));
} }
} }
else if (!info[start]->IsObject() || info[start]->IsRegExp() || info[start]->IsDate() || Buffer::HasInstance(info[start])) { else if (!info[start].IsObject() || info[start].IsRegExp() || info[start].IsDate() || info[start].IsBuffer()) {
// Parameters directly in array. // Parameters directly in array.
// Note: bind parameters start with 1. // Note: bind parameters start with 1.
for (int i = start, pos = 1; i < last; i++, pos++) { for (int i = start, pos = 1; i < last; i++, pos++) {
baton->parameters.push_back(BindParameter(info[i], pos)); baton->parameters.push_back(BindParameter(info[i], pos));
} }
} }
else if (info[start]->IsObject()) { else if (info[start].IsObject()) {
Local<Object> object = Local<Object>::Cast(info[start]); Napi::Object object = info[start].As<Napi::Object>();
Local<Array> array = Nan::GetPropertyNames(object).ToLocalChecked(); Napi::Array array = Napi::GetPropertyNames(object);
int length = array->Length(); int length = array->Length();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
Local<Value> name = Nan::Get(array, i).ToLocalChecked(); Napi::Value name = (array).Get(i);
if (name->IsInt32()) { if (name.IsNumber()) {
baton->parameters.push_back( baton->parameters.push_back(
BindParameter(Nan::Get(object, name).ToLocalChecked(), Nan::To<int32_t>(name).FromJust())); BindParameter((object).Get(name), name.As<Napi::Number>().Int32Value()));
} }
else { else {
baton->parameters.push_back(BindParameter(Nan::Get(object, name).ToLocalChecked(), baton->parameters.push_back(BindParameter((object).Get(name),
*Nan::Utf8String(name))); name->As<Napi::String>().Utf8Value().c_str()));
} }
} }
} }
...@@ -305,16 +310,17 @@ bool Statement::Bind(const Parameters & parameters) { ...@@ -305,16 +310,17 @@ bool Statement::Bind(const Parameters & parameters) {
return true; return true;
} }
NAN_METHOD(Statement::Bind) { Napi::Value Statement::Bind(const Napi::CallbackInfo& info) {
Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This()); Statement* stmt = this;
Baton* baton = stmt->Bind<Baton>(info); Baton* baton = stmt->Bind<Baton>(info);
if (baton == NULL) { if (baton == NULL) {
return Nan::ThrowTypeError("Data type is not supported"); Napi::TypeError::New(env, "Data type is not supported").ThrowAsJavaScriptException();
return env.Null();
} }
else { else {
stmt->Schedule(Work_BeginBind, baton); stmt->Schedule(Work_BeginBind, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
} }
...@@ -332,7 +338,7 @@ void Statement::Work_Bind(uv_work_t* req) { ...@@ -332,7 +338,7 @@ void Statement::Work_Bind(uv_work_t* req) {
} }
void Statement::Work_AfterBind(uv_work_t* req) { void Statement::Work_AfterBind(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
STATEMENT_INIT(Baton); STATEMENT_INIT(Baton);
...@@ -341,9 +347,9 @@ void Statement::Work_AfterBind(uv_work_t* req) { ...@@ -341,9 +347,9 @@ void Statement::Work_AfterBind(uv_work_t* req) {
} }
else { else {
// Fire callbacks. // Fire callbacks.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(stmt->handle(), cb, 1, argv); TRY_CATCH_CALL(stmt->handle(), cb, 1, argv);
} }
} }
...@@ -353,16 +359,17 @@ void Statement::Work_AfterBind(uv_work_t* req) { ...@@ -353,16 +359,17 @@ void Statement::Work_AfterBind(uv_work_t* req) {
NAN_METHOD(Statement::Get) { Napi::Value Statement::Get(const Napi::CallbackInfo& info) {
Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This()); Statement* stmt = this;
Baton* baton = stmt->Bind<RowBaton>(info); Baton* baton = stmt->Bind<RowBaton>(info);
if (baton == NULL) { if (baton == NULL) {
return Nan::ThrowError("Data type is not supported"); Napi::Error::New(env, "Data type is not supported").ThrowAsJavaScriptException();
return env.Null();
} }
else { else {
stmt->Schedule(Work_BeginGet, baton); stmt->Schedule(Work_BeginGet, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
} }
...@@ -395,7 +402,7 @@ void Statement::Work_Get(uv_work_t* req) { ...@@ -395,7 +402,7 @@ void Statement::Work_Get(uv_work_t* req) {
} }
void Statement::Work_AfterGet(uv_work_t* req) { void Statement::Work_AfterGet(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
STATEMENT_INIT(RowBaton); STATEMENT_INIT(RowBaton);
...@@ -404,15 +411,15 @@ void Statement::Work_AfterGet(uv_work_t* req) { ...@@ -404,15 +411,15 @@ void Statement::Work_AfterGet(uv_work_t* req) {
} }
else { else {
// Fire callbacks. // Fire callbacks.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
if (stmt->status == SQLITE_ROW) { if (stmt->status == SQLITE_ROW) {
// Create the result array from the data we acquired. // Create the result array from the data we acquired.
Local<Value> argv[] = { Nan::Null(), RowToJS(&baton->row) }; Napi::Value argv[] = { env.Null(), RowToJS(&baton->row) };
TRY_CATCH_CALL(stmt->handle(), cb, 2, argv); TRY_CATCH_CALL(stmt->handle(), cb, 2, argv);
} }
else { else {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(stmt->handle(), cb, 1, argv); TRY_CATCH_CALL(stmt->handle(), cb, 1, argv);
} }
} }
...@@ -421,16 +428,17 @@ void Statement::Work_AfterGet(uv_work_t* req) { ...@@ -421,16 +428,17 @@ void Statement::Work_AfterGet(uv_work_t* req) {
STATEMENT_END(); STATEMENT_END();
} }
NAN_METHOD(Statement::Run) { Napi::Value Statement::Run(const Napi::CallbackInfo& info) {
Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This()); Statement* stmt = this;
Baton* baton = stmt->Bind<RunBaton>(info); Baton* baton = stmt->Bind<RunBaton>(info);
if (baton == NULL) { if (baton == NULL) {
return Nan::ThrowError("Data type is not supported"); Napi::Error::New(env, "Data type is not supported").ThrowAsJavaScriptException();
return env.Null();
} }
else { else {
stmt->Schedule(Work_BeginRun, baton); stmt->Schedule(Work_BeginRun, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
} }
...@@ -465,7 +473,7 @@ void Statement::Work_Run(uv_work_t* req) { ...@@ -465,7 +473,7 @@ void Statement::Work_Run(uv_work_t* req) {
} }
void Statement::Work_AfterRun(uv_work_t* req) { void Statement::Work_AfterRun(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
STATEMENT_INIT(RunBaton); STATEMENT_INIT(RunBaton);
...@@ -474,12 +482,12 @@ void Statement::Work_AfterRun(uv_work_t* req) { ...@@ -474,12 +482,12 @@ void Statement::Work_AfterRun(uv_work_t* req) {
} }
else { else {
// Fire callbacks. // Fire callbacks.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Nan::Set(stmt->handle(), Nan::New("lastID").ToLocalChecked(), Nan::New<Number>(baton->inserted_id)); (stmt->handle()).Set(Napi::String::New(env, "lastID"), Napi::Number::New(env, baton->inserted_id));
Nan::Set(stmt->handle(), Nan::New("changes").ToLocalChecked(), Nan::New(baton->changes)); (stmt->handle()).Set(Napi::String::New(env, "changes"), Napi::New(env, baton->changes));
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(stmt->handle(), cb, 1, argv); TRY_CATCH_CALL(stmt->handle(), cb, 1, argv);
} }
} }
...@@ -487,16 +495,17 @@ void Statement::Work_AfterRun(uv_work_t* req) { ...@@ -487,16 +495,17 @@ void Statement::Work_AfterRun(uv_work_t* req) {
STATEMENT_END(); STATEMENT_END();
} }
NAN_METHOD(Statement::All) { Napi::Value Statement::All(const Napi::CallbackInfo& info) {
Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This()); Statement* stmt = this;
Baton* baton = stmt->Bind<RowsBaton>(info); Baton* baton = stmt->Bind<RowsBaton>(info);
if (baton == NULL) { if (baton == NULL) {
return Nan::ThrowError("Data type is not supported"); Napi::Error::New(env, "Data type is not supported").ThrowAsJavaScriptException();
return env.Null();
} }
else { else {
stmt->Schedule(Work_BeginAll, baton); stmt->Schedule(Work_BeginAll, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
} }
...@@ -531,7 +540,7 @@ void Statement::Work_All(uv_work_t* req) { ...@@ -531,7 +540,7 @@ void Statement::Work_All(uv_work_t* req) {
} }
void Statement::Work_AfterAll(uv_work_t* req) { void Statement::Work_AfterAll(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
STATEMENT_INIT(RowsBaton); STATEMENT_INIT(RowsBaton);
...@@ -540,26 +549,26 @@ void Statement::Work_AfterAll(uv_work_t* req) { ...@@ -540,26 +549,26 @@ void Statement::Work_AfterAll(uv_work_t* req) {
} }
else { else {
// Fire callbacks. // Fire callbacks.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
if (baton->rows.size()) { if (baton->rows.size()) {
// Create the result array from the data we acquired. // Create the result array from the data we acquired.
Local<Array> result(Nan::New<Array>(baton->rows.size())); Napi::Array result(Napi::Array::New(env, baton->rows.size()));
Rows::const_iterator it = baton->rows.begin(); Rows::const_iterator it = baton->rows.begin();
Rows::const_iterator end = baton->rows.end(); Rows::const_iterator end = baton->rows.end();
for (int i = 0; it < end; ++it, i++) { for (int i = 0; it < end; ++it, i++) {
Nan::Set(result, i, RowToJS(*it)); (result).Set(i, RowToJS(*it));
delete *it; delete *it;
} }
Local<Value> argv[] = { Nan::Null(), result }; Napi::Value argv[] = { env.Null(), result };
TRY_CATCH_CALL(stmt->handle(), cb, 2, argv); TRY_CATCH_CALL(stmt->handle(), cb, 2, argv);
} }
else { else {
// There were no result rows. // There were no result rows.
Local<Value> argv[] = { Napi::Value argv[] = {
Nan::Null(), env.Null(),
Nan::New<Array>(0) Napi::Array::New(env, 0)
}; };
TRY_CATCH_CALL(stmt->handle(), cb, 2, argv); TRY_CATCH_CALL(stmt->handle(), cb, 2, argv);
} }
...@@ -569,24 +578,25 @@ void Statement::Work_AfterAll(uv_work_t* req) { ...@@ -569,24 +578,25 @@ void Statement::Work_AfterAll(uv_work_t* req) {
STATEMENT_END(); STATEMENT_END();
} }
NAN_METHOD(Statement::Each) { Napi::Value Statement::Each(const Napi::CallbackInfo& info) {
Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This()); Statement* stmt = this;
int last = info.Length(); int last = info.Length();
Local<Function> completed; Napi::Function completed;
if (last >= 2 && info[last - 1]->IsFunction() && info[last - 2]->IsFunction()) { if (last >= 2 && info[last - 1]->IsFunction() && info[last - 2]->IsFunction()) {
completed = Local<Function>::Cast(info[--last]); completed = info[--last].As<Napi::Function>();
} }
EachBaton* baton = stmt->Bind<EachBaton>(info, 0, last); EachBaton* baton = stmt->Bind<EachBaton>(info, 0, last);
if (baton == NULL) { if (baton == NULL) {
return Nan::ThrowError("Data type is not supported"); Napi::Error::New(env, "Data type is not supported").ThrowAsJavaScriptException();
return env.Null();
} }
else { else {
baton->completed.Reset(completed); baton->completed.Reset(completed);
stmt->Schedule(Work_BeginEach, baton); stmt->Schedule(Work_BeginEach, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
} }
...@@ -652,7 +662,7 @@ void Statement::CloseCallback(uv_handle_t* handle) { ...@@ -652,7 +662,7 @@ void Statement::CloseCallback(uv_handle_t* handle) {
} }
void Statement::AsyncEach(uv_async_t* handle, int status) { void Statement::AsyncEach(uv_async_t* handle, int status) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
Async* async = static_cast<Async*>(handle->data); Async* async = static_cast<Async*>(handle->data);
...@@ -667,10 +677,10 @@ void Statement::AsyncEach(uv_async_t* handle, int status) { ...@@ -667,10 +677,10 @@ void Statement::AsyncEach(uv_async_t* handle, int status) {
break; break;
} }
Local<Function> cb = Nan::New(async->item_cb); Napi::Function cb = Napi::New(env, async->item_cb);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[2]; Napi::Value argv[2];
argv[0] = Nan::Null(); argv[0] = env.Null();
Rows::const_iterator it = rows.begin(); Rows::const_iterator it = rows.begin();
Rows::const_iterator end = rows.end(); Rows::const_iterator end = rows.end();
...@@ -683,13 +693,13 @@ void Statement::AsyncEach(uv_async_t* handle, int status) { ...@@ -683,13 +693,13 @@ void Statement::AsyncEach(uv_async_t* handle, int status) {
} }
} }
Local<Function> cb = Nan::New(async->completed_cb); Napi::Function cb = Napi::New(env, async->completed_cb);
if (async->completed) { if (async->completed) {
if (!cb.IsEmpty() && if (!cb.IsEmpty() &&
cb->IsFunction()) { cb->IsFunction()) {
Local<Value> argv[] = { Napi::Value argv[] = {
Nan::Null(), env.Null(),
Nan::New(async->retrieved) Napi::New(env, async->retrieved)
}; };
TRY_CATCH_CALL(async->stmt->handle(), cb, 2, argv); TRY_CATCH_CALL(async->stmt->handle(), cb, 2, argv);
} }
...@@ -698,7 +708,7 @@ void Statement::AsyncEach(uv_async_t* handle, int status) { ...@@ -698,7 +708,7 @@ void Statement::AsyncEach(uv_async_t* handle, int status) {
} }
void Statement::Work_AfterEach(uv_work_t* req) { void Statement::Work_AfterEach(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
STATEMENT_INIT(EachBaton); STATEMENT_INIT(EachBaton);
...@@ -709,15 +719,15 @@ void Statement::Work_AfterEach(uv_work_t* req) { ...@@ -709,15 +719,15 @@ void Statement::Work_AfterEach(uv_work_t* req) {
STATEMENT_END(); STATEMENT_END();
} }
NAN_METHOD(Statement::Reset) { Napi::Value Statement::Reset(const Napi::CallbackInfo& info) {
Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This()); Statement* stmt = this;
OPTIONAL_ARGUMENT_FUNCTION(0, callback); OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(stmt, callback); Baton* baton = new Baton(stmt, callback);
stmt->Schedule(Work_BeginReset, baton); stmt->Schedule(Work_BeginReset, baton);
info.GetReturnValue().Set(info.This()); return info.This();
} }
void Statement::Work_BeginReset(Baton* baton) { void Statement::Work_BeginReset(Baton* baton) {
...@@ -732,51 +742,51 @@ void Statement::Work_Reset(uv_work_t* req) { ...@@ -732,51 +742,51 @@ void Statement::Work_Reset(uv_work_t* req) {
} }
void Statement::Work_AfterReset(uv_work_t* req) { void Statement::Work_AfterReset(uv_work_t* req) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
STATEMENT_INIT(Baton); STATEMENT_INIT(Baton);
// Fire callbacks. // Fire callbacks.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { Nan::Null() }; Napi::Value argv[] = { env.Null() };
TRY_CATCH_CALL(stmt->handle(), cb, 1, argv); TRY_CATCH_CALL(stmt->handle(), cb, 1, argv);
} }
STATEMENT_END(); STATEMENT_END();
} }
Local<Object> Statement::RowToJS(Row* row) { Napi::Object Statement::RowToJS(Row* row) {
Nan::EscapableHandleScope scope; Napi::EscapableHandleScope scope(env);
Local<Object> result = Nan::New<Object>(); Napi::Object result = Napi::Object::New(env);
Row::const_iterator it = row->begin(); Row::const_iterator it = row->begin();
Row::const_iterator end = row->end(); Row::const_iterator end = row->end();
for (int i = 0; it < end; ++it, i++) { for (int i = 0; it < end; ++it, i++) {
Values::Field* field = *it; Values::Field* field = *it;
Local<Value> value; Napi::Value value;
switch (field->type) { switch (field->type) {
case SQLITE_INTEGER: { case SQLITE_INTEGER: {
value = Nan::New<Number>(((Values::Integer*)field)->value); value = Napi::Number::New(env, ((Values::Integer*)field)->value);
} break; } break;
case SQLITE_FLOAT: { case SQLITE_FLOAT: {
value = Nan::New<Number>(((Values::Float*)field)->value); value = Napi::Number::New(env, ((Values::Float*)field)->value);
} break; } break;
case SQLITE_TEXT: { case SQLITE_TEXT: {
value = Nan::New<String>(((Values::Text*)field)->value.c_str(), ((Values::Text*)field)->value.size()).ToLocalChecked(); value = Napi::String::New(env, ((Values::Text*)field)->value.c_str(), ((Values::Text*)field)->value.size());
} break; } break;
case SQLITE_BLOB: { case SQLITE_BLOB: {
value = Nan::CopyBuffer(((Values::Blob*)field)->value, ((Values::Blob*)field)->length).ToLocalChecked(); value = Napi::Buffer::Copy(env, ((Values::Blob*)field)->value, ((Values::Blob*)field)->length);
} break; } break;
case SQLITE_NULL: { case SQLITE_NULL: {
value = Nan::Null(); value = env.Null();
} break; } break;
} }
Nan::Set(result, Nan::New(field->name.c_str()).ToLocalChecked(), value); (result).Set(Napi::New(env, field->name.c_str()), value);
DELETE_FIELD(field); DELETE_FIELD(field);
} }
...@@ -816,23 +826,23 @@ void Statement::GetRow(Row* row, sqlite3_stmt* stmt) { ...@@ -816,23 +826,23 @@ void Statement::GetRow(Row* row, sqlite3_stmt* stmt) {
} }
} }
NAN_METHOD(Statement::Finalize) { Napi::Value Statement::Finalize(const Napi::CallbackInfo& info) {
Statement* stmt = Nan::ObjectWrap::Unwrap<Statement>(info.This()); Statement* stmt = this;
OPTIONAL_ARGUMENT_FUNCTION(0, callback); OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(stmt, callback); Baton* baton = new Baton(stmt, callback);
stmt->Schedule(Finalize, baton); stmt->Schedule(Finalize, baton);
info.GetReturnValue().Set(stmt->db->handle()); return stmt->db->handle();
} }
void Statement::Finalize(Baton* baton) { void Statement::Finalize(Baton* baton) {
Nan::HandleScope scope; Napi::HandleScope scope(env);
baton->stmt->Finalize(); baton->stmt->Finalize();
// Fire callback in case there was one. // Fire callback in case there was one.
Local<Function> cb = Nan::New(baton->callback); Napi::Function cb = Napi::New(env, baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) { if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(baton->stmt->handle(), cb, 0, NULL); TRY_CATCH_CALL(baton->stmt->handle(), cb, 0, NULL);
} }
...@@ -852,13 +862,13 @@ void Statement::Finalize() { ...@@ -852,13 +862,13 @@ void Statement::Finalize() {
} }
void Statement::CleanQueue() { void Statement::CleanQueue() {
Nan::HandleScope scope; Napi::HandleScope scope(env);
if (prepared && !queue.empty()) { if (prepared && !queue.empty()) {
// This statement has already been prepared and is now finalized. // This statement has already been prepared and is now finalized.
// Fire error for all remaining items in the queue. // Fire error for all remaining items in the queue.
EXCEPTION("Statement is already finalized", SQLITE_MISUSE, exception); EXCEPTION("Statement is already finalized", SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception }; Napi::Value argv[] = { exception };
bool called = false; bool called = false;
// Clear out the queue so that this object can get GC'ed. // Clear out the queue so that this object can get GC'ed.
...@@ -866,7 +876,7 @@ void Statement::CleanQueue() { ...@@ -866,7 +876,7 @@ void Statement::CleanQueue() {
Call* call = queue.front(); Call* call = queue.front();
queue.pop(); queue.pop();
Local<Function> cb = Nan::New(call->baton->callback); Napi::Function cb = Napi::New(env, call->baton->callback);
if (prepared && !cb.IsEmpty() && if (prepared && !cb.IsEmpty() &&
cb->IsFunction()) { cb->IsFunction()) {
...@@ -883,7 +893,7 @@ void Statement::CleanQueue() { ...@@ -883,7 +893,7 @@ void Statement::CleanQueue() {
// When we couldn't call a callback function, emit an error on the // When we couldn't call a callback function, emit an error on the
// Statement object. // Statement object.
if (!called) { if (!called) {
Local<Value> info[] = { Nan::New("error").ToLocalChecked(), exception }; Napi::Value info[] = { Napi::String::New(env, "error"), exception };
EMIT_EVENT(handle(), 2, info); EMIT_EVENT(handle(), 2, info);
} }
} }
......
...@@ -12,10 +12,11 @@ ...@@ -12,10 +12,11 @@
#include <vector> #include <vector>
#include <sqlite3.h> #include <sqlite3.h>
#include <nan.h> #include <napi.h>
#include <uv.h>
using namespace v8; using namespace Napi;
using namespace node; using namespace Napi;
namespace node_sqlite3 { namespace node_sqlite3 {
...@@ -71,20 +72,20 @@ typedef Row Parameters; ...@@ -71,20 +72,20 @@ typedef Row Parameters;
class Statement : public Nan::ObjectWrap { class Statement : public Napi::ObjectWrap<Statement> {
public: public:
static Nan::Persistent<FunctionTemplate> constructor_template; static Napi::FunctionReference constructor;
static NAN_MODULE_INIT(Init); static Napi::Object Init(Napi::Env env, Napi::Object exports);
static NAN_METHOD(New); static Napi::Value New(const Napi::CallbackInfo& info);
struct Baton { struct Baton {
uv_work_t request; uv_work_t request;
Statement* stmt; Statement* stmt;
Nan::Persistent<Function> callback; Napi::FunctionReference callback;
Parameters parameters; Parameters parameters;
Baton(Statement* stmt_, Local<Function> cb_) : stmt(stmt_) { Baton(Statement* stmt_, Napi::Function cb_) : stmt(stmt_) {
stmt->Ref(); stmt->Ref();
request.data = this; request.data = this;
callback.Reset(cb_); callback.Reset(cb_);
...@@ -100,20 +101,20 @@ public: ...@@ -100,20 +101,20 @@ public:
}; };
struct RowBaton : Baton { struct RowBaton : Baton {
RowBaton(Statement* stmt_, Local<Function> cb_) : RowBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_) {} Baton(stmt_, cb_) {}
Row row; Row row;
}; };
struct RunBaton : Baton { struct RunBaton : Baton {
RunBaton(Statement* stmt_, Local<Function> cb_) : RunBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_), inserted_id(0), changes(0) {} Baton(stmt_, cb_), inserted_id(0), changes(0) {}
sqlite3_int64 inserted_id; sqlite3_int64 inserted_id;
int changes; int changes;
}; };
struct RowsBaton : Baton { struct RowsBaton : Baton {
RowsBaton(Statement* stmt_, Local<Function> cb_) : RowsBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_) {} Baton(stmt_, cb_) {}
Rows rows; Rows rows;
}; };
...@@ -121,10 +122,10 @@ public: ...@@ -121,10 +122,10 @@ public:
struct Async; struct Async;
struct EachBaton : Baton { struct EachBaton : Baton {
Nan::Persistent<Function> completed; Napi::FunctionReference completed;
Async* async; // Isn't deleted when the baton is deleted. Async* async; // Isn't deleted when the baton is deleted.
EachBaton(Statement* stmt_, Local<Function> cb_) : EachBaton(Statement* stmt_, Napi::Function cb_) :
Baton(stmt_, cb_) {} Baton(stmt_, cb_) {}
virtual ~EachBaton() { virtual ~EachBaton() {
completed.Reset(); completed.Reset();
...@@ -134,7 +135,7 @@ public: ...@@ -134,7 +135,7 @@ public:
struct PrepareBaton : Database::Baton { struct PrepareBaton : Database::Baton {
Statement* stmt; Statement* stmt;
std::string sql; std::string sql;
PrepareBaton(Database* db_, Local<Function> cb_, Statement* stmt_) : PrepareBaton(Database* db_, Napi::Function cb_, Statement* stmt_) :
Baton(db_, cb_), stmt(stmt_) { Baton(db_, cb_), stmt(stmt_) {
stmt->Ref(); stmt->Ref();
} }
...@@ -166,8 +167,8 @@ public: ...@@ -166,8 +167,8 @@ public:
// Store the callbacks here because we don't have // Store the callbacks here because we don't have
// access to the baton in the async callback. // access to the baton in the async callback.
Nan::Persistent<Function> item_cb; Napi::FunctionReference item_cb;
Nan::Persistent<Function> completed_cb; Napi::FunctionReference completed_cb;
Async(Statement* st, uv_async_cb async_cb) : Async(Statement* st, uv_async_cb async_cb) :
stmt(st), completed(false), retrieved(0) { stmt(st), completed(false), retrieved(0) {
...@@ -185,7 +186,7 @@ public: ...@@ -185,7 +186,7 @@ public:
} }
}; };
Statement(Database* db_) : Nan::ObjectWrap(), Statement(Database* db_) : Napi::ObjectWrap<Statement>(),
db(db_), db(db_),
_handle(NULL), _handle(NULL),
status(SQLITE_OK), status(SQLITE_OK),
...@@ -206,7 +207,7 @@ public: ...@@ -206,7 +207,7 @@ public:
WORK_DEFINITION(Each); WORK_DEFINITION(Each);
WORK_DEFINITION(Reset); WORK_DEFINITION(Reset);
static NAN_METHOD(Finalize); static Napi::Value Finalize(const Napi::CallbackInfo& info);
protected: protected:
static void Work_BeginPrepare(Database::Baton* baton); static void Work_BeginPrepare(Database::Baton* baton);
...@@ -219,12 +220,12 @@ protected: ...@@ -219,12 +220,12 @@ protected:
static void Finalize(Baton* baton); static void Finalize(Baton* baton);
void Finalize(); void Finalize();
template <class T> inline Values::Field* BindParameter(const Local<Value> source, T pos); template <class T> inline Values::Field* BindParameter(const Napi::Value source, T pos);
template <class T> T* Bind(Nan::NAN_METHOD_ARGS_TYPE info, int start = 0, int end = -1); template <class T> T* Bind(const Napi::CallbackInfo& info, int start = 0, int end = -1);
bool Bind(const Parameters &parameters); bool Bind(const Parameters &parameters);
static void GetRow(Row* row, sqlite3_stmt* stmt); static void GetRow(Row* row, sqlite3_stmt* stmt);
static Local<Object> RowToJS(Row* row); static Napi::Object RowToJS(Row* row);
void Schedule(Work_Callback callback, Baton* baton); void Schedule(Work_Callback callback, Baton* baton);
void Process(); void Process();
void CleanQueue(); void CleanQueue();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment