-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql-spite.js
93 lines (81 loc) · 2.13 KB
/
sql-spite.js
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
var spite = {
model: model,
register: register,
connect: connect,
schemas: schemas,
disconnect: disconnect,
db: null
};
module.exports = spite;
var ClassModelGenerator = require("./class-model-generator.js");
var sqlite3 = require("sqlite3").verbose();
var Schema = require("./schema");
var makePromiseOrCall = require("./util/make-promise-or-call");
var registered = {};
function connect (name, cb)
{
return makePromiseOrCall(_connect, { name: name }, cb);
}
function _connect (args, cb)
{
spite.db = new sqlite3.Database(args.name + ".sqlite3", function (err) {
cb(err);
});
}
function disconnect ()
{
registered = {};
spite.db = null;
}
function schemas ()
{
var schemas_ = [];
for (var key in registered) {
schemas_.push(registered[key].schema);
}
return schemas_;
}
function model (name)
{
if (registered[name]) {
return registered[name];
}
throw ReferenceError("Model \"" + name + "\" does not exist");
}
function register (options, schema, cb)
{
return makePromiseOrCall(_register, { options: options, schema: schema }, cb);
}
function _register (args, cb)
{
var options = args.options;
var schema = args.schema;
if (!options || ! schema) {
throw Error("Schema Required to Register Model");
}
if (typeof options.model !== "string" || typeof options.table !== "string") {
throw Error("model and table name are required to register model");
}
if (registered[options.model]) {
throw ReferenceError("Model \"" + options + "\" already exists");
}
schema = new Schema(options, schema);
var str = "CREATE TABLE IF NOT EXISTS " + schema.table + " ( ";
var first = true;
for (var i = 0; i < schema.columns.length; i++) {
var col = schema.columns[i];
if (!first) {
str += ", ";
}
first = false;
str += col.name + " " + col.type;
}
str += ")";
var model = new ClassModelGenerator(schema).model;
spite.db.run(str, function (err) {
if (!err) {
registered[options.model] = model;
}
cb(err);
});
}