forked from grumdrig/node-sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite3_bindings.cc
361 lines (295 loc) · 12.2 KB
/
sqlite3_bindings.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sqlite3.h>
#include <v8.h>
#include <node.h>
#include <node_events.h>
using namespace v8;
using namespace node;
#define CHECK(rc) { if ((rc) != SQLITE_OK) \
return ThrowException(Exception::Error(String::New( \
sqlite3_errmsg(*db)))); }
#define SCHECK(rc) { if ((rc) != SQLITE_OK) \
return ThrowException(Exception::Error(String::New( \
sqlite3_errmsg(sqlite3_db_handle(*stmt))))); }
#define REQ_ARGS(N) \
if (args.Length() < (N)) \
return ThrowException(Exception::TypeError( \
String::New("Expected " #N "arguments")));
#define REQ_STR_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsString()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a string"))); \
String::Utf8Value VAR(args[I]->ToString());
#define REQ_EXT_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsExternal()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " invalid"))); \
Local<External> VAR = Local<External>::Cast(args[I]);
#define OPT_INT_ARG(I, VAR, DEFAULT) \
int VAR; \
if (args.Length() <= (I)) { \
VAR = (DEFAULT); \
} else if (args[I]->IsInt32()) { \
VAR = args[I]->Int32Value(); \
} else { \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be an integer"))); \
}
class Sqlite3Db : public EventEmitter
{
public:
static void Init(v8::Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->Inherit(EventEmitter::constructor_template);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "changes", Changes);
NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
NODE_SET_PROTOTYPE_METHOD(t, "lastInsertRowid", LastInsertRowid);
NODE_SET_PROTOTYPE_METHOD(t, "prepare", Prepare);
target->Set(v8::String::NewSymbol("DatabaseSync"), t->GetFunction());
Statement::Init(target);
}
protected:
Sqlite3Db(sqlite3* db) : db_(db) {
}
~Sqlite3Db() {
sqlite3_close(db_);
}
sqlite3* db_;
operator sqlite3* () const { return db_; }
protected:
static Handle<Value> New(const Arguments& args) {
HandleScope scope;
REQ_STR_ARG(0, filename);
sqlite3* db;
int rc = sqlite3_open(*filename, &db);
if (rc) return ThrowException(Exception::Error(
String::New("Error opening database")));
Sqlite3Db* dbo = new Sqlite3Db(db);
dbo->Wrap(args.This());
sqlite3_commit_hook(db, CommitHook, dbo);
sqlite3_rollback_hook(db, RollbackHook, dbo);
sqlite3_update_hook(db, UpdateHook, dbo);
return args.This();
}
//
// JS DatabaseSync bindings
//
static Handle<Value> Changes(const Arguments& args) {
HandleScope scope;
Sqlite3Db* db = ObjectWrap::Unwrap<Sqlite3Db>(args.This());
Local<Number> result = Integer::New(sqlite3_changes(*db));
return scope.Close(result);
}
static Handle<Value> Close(const Arguments& args) {
HandleScope scope;
Sqlite3Db* db = ObjectWrap::Unwrap<Sqlite3Db>(args.This());
CHECK(sqlite3_close(*db));
db->db_ = NULL;
return Undefined();
}
static Handle<Value> LastInsertRowid(const Arguments& args) {
HandleScope scope;
Sqlite3Db* db = ObjectWrap::Unwrap<Sqlite3Db>(args.This());
Local<Number> result = Integer::New(sqlite3_last_insert_rowid(*db));
return scope.Close(result);
}
static int CommitHook(void* v_this) {
HandleScope scope;
Sqlite3Db* db = static_cast<Sqlite3Db*>(v_this);
db->Emit(String::New("commit"), 0, NULL);
// TODO: allow change in return value to convert to rollback...somehow
return 0;
}
static void RollbackHook(void* v_this) {
HandleScope scope;
Sqlite3Db* db = static_cast<Sqlite3Db*>(v_this);
db->Emit(String::New("rollback"), 0, NULL);
}
static void UpdateHook(void* v_this, int operation, const char* database,
const char* table, sqlite_int64 rowid) {
HandleScope scope;
Sqlite3Db* db = static_cast<Sqlite3Db*>(v_this);
Local<Value> args[] = { Int32::New(operation), String::New(database),
String::New(table), Number::New(rowid) };
db->Emit(String::New("update"), 4, args);
}
/*
static Handle<Value> Open(const Arguments& args) {
HandleScope scope;
Sqlite3Db* db = ObjectWrap::Unwrap<Sqlite3Db>(args.This());
REQ_STR_ARG(0, filename);
Close(args); // ignores args anyway, except This
CHECK(sqlite3_open(*filename, &db->db_));
sqlite3_commit_hook(*db, CommitHook, db);
sqlite3_rollback_hook(*db, RollbackHook, db);
sqlite3_update_hook(*db, UpdateHook, db);
return args.This();
}
*/
static Handle<Value> Prepare(const Arguments& args) {
HandleScope scope;
Sqlite3Db* db = ObjectWrap::Unwrap<Sqlite3Db>(args.This());
REQ_STR_ARG(0, sql);
sqlite3_stmt* stmt = NULL;
const char* tail = NULL;
CHECK(sqlite3_prepare_v2(*db, *sql, -1, &stmt, &tail));
if (!stmt)
return Null();
Local<Value> arg = External::New(stmt);
Persistent<Object> statement(Statement::constructor_template->
GetFunction()->NewInstance(1, &arg));
if (tail)
statement->Set(String::New("tail"), String::New(tail));
return scope.Close(statement);
}
class Statement : public EventEmitter
{
public:
static Persistent<FunctionTemplate> constructor_template;
static void Init(v8::Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
t->Inherit(EventEmitter::constructor_template);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "bind", Bind);
NODE_SET_PROTOTYPE_METHOD(t, "clearBindings", ClearBindings);
NODE_SET_PROTOTYPE_METHOD(t, "finalize", Finalize);
NODE_SET_PROTOTYPE_METHOD(t, "bindParameterCount", BindParameterCount);
NODE_SET_PROTOTYPE_METHOD(t, "reset", Reset);
NODE_SET_PROTOTYPE_METHOD(t, "step", Step);
//target->Set(v8::String::NewSymbol("SQLStatement"), t->GetFunction());
}
static Handle<Value> New(const Arguments& args) {
HandleScope scope;
int I = 0;
REQ_EXT_ARG(0, stmt);
(new Statement((sqlite3_stmt*)stmt->Value()))->Wrap(args.This());
return args.This();
}
protected:
Statement(sqlite3_stmt* stmt) : stmt_(stmt) {}
~Statement() { if (stmt_) sqlite3_finalize(stmt_); }
sqlite3_stmt* stmt_;
operator sqlite3_stmt* () const { return stmt_; }
//
// JS prepared statement bindings
//
static Handle<Value> Bind(const Arguments& args) {
HandleScope scope;
Statement* stmt = ObjectWrap::Unwrap<Statement>(args.This());
REQ_ARGS(2);
if (!args[0]->IsString() && !args[0]->IsInt32())
return ThrowException(Exception::TypeError(
String::New("First argument must be a string or integer")));
int index = args[0]->IsString() ?
sqlite3_bind_parameter_index(*stmt, *String::Utf8Value(args[0])) :
args[0]->Int32Value();
if (args[1]->IsInt32()) {
sqlite3_bind_int(*stmt, index, args[1]->Int32Value());
} else if (args[1]->IsNumber()) {
sqlite3_bind_double(*stmt, index, args[1]->NumberValue());
} else if (args[1]->IsString()) {
String::Utf8Value text(args[1]);
sqlite3_bind_text(*stmt, index, *text, text.length(),SQLITE_TRANSIENT);
} else if (args[1]->IsNull() || args[1]->IsUndefined()) {
sqlite3_bind_null(*stmt, index);
} else {
return ThrowException(Exception::TypeError(
String::New("Unable to bind value of this type")));
}
return args.This();
}
static Handle<Value> BindParameterCount(const Arguments& args) {
HandleScope scope;
Statement* stmt = ObjectWrap::Unwrap<Statement>(args.This());
Local<Number> result = Integer::New(sqlite3_bind_parameter_count(*stmt));
return scope.Close(result);
}
static Handle<Value> ClearBindings(const Arguments& args) {
HandleScope scope;
Statement* stmt = ObjectWrap::Unwrap<Statement>(args.This());
SCHECK(sqlite3_clear_bindings(*stmt));
return Undefined();
}
static Handle<Value> Finalize(const Arguments& args) {
HandleScope scope;
Statement* stmt = ObjectWrap::Unwrap<Statement>(args.This());
SCHECK(sqlite3_finalize(*stmt));
stmt->stmt_ = NULL;
//args.This().MakeWeak();
return Undefined();
}
static Handle<Value> Reset(const Arguments& args) {
HandleScope scope;
Statement* stmt = ObjectWrap::Unwrap<Statement>(args.This());
SCHECK(sqlite3_reset(*stmt));
return Undefined();
}
static Handle<Value> Step(const Arguments& args) {
HandleScope scope;
Statement* stmt = ObjectWrap::Unwrap<Statement>(args.This());
int rc = sqlite3_step(*stmt);
if (rc == SQLITE_ROW) {
Local<Object> row = Object::New();
for (int c = 0; c < sqlite3_column_count(*stmt); ++c) {
Handle<Value> value;
switch (sqlite3_column_type(*stmt, c)) {
case SQLITE_INTEGER:
value = Integer::New(sqlite3_column_int(*stmt, c));
break;
case SQLITE_FLOAT:
value = Number::New(sqlite3_column_double(*stmt, c));
break;
case SQLITE_TEXT:
value = String::New((const char*) sqlite3_column_text(*stmt, c));
break;
case SQLITE_NULL:
default: // We don't handle any other types just now
value = Undefined();
break;
}
row->Set(String::NewSymbol(sqlite3_column_name(*stmt, c)),
value);
}
return row;
} else if (rc == SQLITE_DONE) {
return Null();
} else {
return ThrowException(Exception::Error(String::New(
sqlite3_errmsg(sqlite3_db_handle(*stmt)))));
}
}
/*
Handle<Object> Cast() {
HandleScope scope;
Local<ObjectTemplate> t(ObjectTemplate::New());
t->SetInternalFieldCount(1);
Local<Object> thus = t->NewInstance();
thus->SetInternalField(0, External::New(this));
//Wrap(thus);
return thus;
}
*/
};
};
Persistent<FunctionTemplate> Sqlite3Db::Statement::constructor_template;
extern "C" void init (v8::Handle<Object> target)
{
Sqlite3Db::Init(target);
}