Commit de8888ef by Mohamed Akram

Convert NAN to N-API using tool

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