/
sqlite3.js
437 lines (378 loc) · 12.3 KB
/
sqlite3.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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
var safeRequire = require('../utils').safeRequire;
/**
* Module dependencies
*/
var sqlite3 = safeRequire('sqlite3');
exports.initialize = function initializeSchema(schema, callback) {
if (!sqlite3) return;
var s = schema.settings;
var Database = sqlite3.verbose().Database;
var db = new Database(s.database);
schema.client = db;
schema.adapter = new SQLite3(schema.client);
if (s.database === ':memory:') {
schema.adapter.automigrate(callback);
} else {
process.nextTick(callback);
}
};
function SQLite3(client) {
this._models = {};
this.client = client;
}
SQLite3.prototype.define = function (descr) {
this._models[descr.model.modelName] = descr;
};
SQLite3.prototype.defineProperty = function (model, prop, params) {
this._models[model].properties[prop] = params;
};
SQLite3.prototype.command = function () {
this.query('run', [].slice.call(arguments));
};
SQLite3.prototype.queryAll = function () {
this.query('all', [].slice.call(arguments));
};
SQLite3.prototype.queryOne = function () {
this.query('get', [].slice.call(arguments));
};
SQLite3.prototype.query = function (method, args) {
var time = Date.now();
var log = this.log;
var cb = args.pop();
if (typeof cb === 'function') {
args.push(function (err, data) {
log(args[0], time);
cb.call(this, err, data);
});
} else {
args.push(cb);
args.push(function (err, data) {
log(args[0], time);
});
}
this.client[method].apply(this.client, args);
};
SQLite3.prototype.save = function (model, data, callback) {
var queryParams = [];
var sql = 'UPDATE ' + model + ' SET ' +
Object.keys(data).map(function (key) {
queryParams.push(data[key]);
return key + ' = ?';
}).join(', ') + ' WHERE id = ' + data.id;
this.command(sql, queryParams, function (err) {
callback(err);
});
};
/**
* Must invoke callback(err, id)
*/
SQLite3.prototype.create = function (model, data, callback) {
data = data || {};
var questions = [];
var values = Object.keys(data).map(function (key) {
questions.push('?');
return data[key];
});
var sql = 'INSERT INTO ' + model + ' (' + Object.keys(data).join(',') + ') VALUES ('
sql += questions.join(',');
sql += ')';
this.command(sql, values, function (err) {
callback(err, this && this.lastID);
});
};
SQLite3.prototype.toFields = function (model, data) {
var fields = [];
var props = this._models[model].properties;
Object.keys(data).forEach(function (key) {
if (props[key]) {
fields.push('`' + key.replace(/\./g, '`.`') + '` = ' + this.toDatabase(props[key], data[key]));
}
}.bind(this));
return fields.join(',');
};
function dateToMysql(val) {
return val.getUTCFullYear() + '-' +
fillZeros(val.getUTCMonth() + 1) + '-' +
fillZeros(val.getUTCDate()) + ' ' +
fillZeros(val.getUTCHours()) + ':' +
fillZeros(val.getUTCMinutes()) + ':' +
fillZeros(val.getUTCSeconds());
function fillZeros(v) {
return v < 10 ? '0' + v : v;
}
}
SQLite3.prototype.toDatabase = function (prop, val) {
if (prop.type.name === 'Number') return val;
if (val === null) return 'NULL';
if (prop.type.name === 'Date') {
if (!val) return 'NULL';
if (!val.toUTCString) {
val = new Date(val);
}
return val;
}
if (prop.type.name == "Boolean") return val ? 1 : 0;
return val.toString();
};
SQLite3.prototype.fromDatabase = function (model, data) {
if (!data) return null;
var props = this._models[model].properties;
Object.keys(data).forEach(function (key) {
var val = data[key];
if (props[key]) {
if (props[key].type.name === 'Date') {
val = new Date(parseInt(val));
}
}
data[key] = val;
});
return data;
};
SQLite3.prototype.exists = function (model, id, callback) {
var sql = 'SELECT 1 FROM ' + model + ' WHERE id = ' + id + ' LIMIT 1';
this.queryOne(sql, function (err, data) {
if (err) return callback(err);
callback(null, data && data['1'] === 1);
});
};
SQLite3.prototype.find = function find(model, id, callback) {
var sql = 'SELECT * FROM ' + model + ' WHERE id = ' + id + ' LIMIT 1';
this.queryOne(sql, function (err, data) {
if (data) {
data.id = id;
} else {
data = null;
}
callback(err, this.fromDatabase(model, data));
}.bind(this));
};
SQLite3.prototype.destroy = function destroy(model, id, callback) {
var sql = 'DELETE FROM ' + model + ' WHERE id = ' + id;
this.command(sql, function (err) {
callback(err);
});
};
SQLite3.prototype.all = function all(model, filter, callback) {
var sql = 'SELECT * FROM ' + model;
var self = this;
var props = this._models[model].properties;
var queryParams = [];
if (filter) {
if (filter.where) {
sql += ' ' + buildWhere(filter.where);
}
if (filter.order) {
sql += ' ' + buildOrderBy(filter.order);
}
if (filter.limit) {
sql += ' ' + buildLimit(filter.limit, filter.offset || 0);
}
}
this.queryAll(sql, queryParams, function (err, data) {
if (err) {
return callback(err, []);
}
callback(null, data.map(function (obj) {
return self.fromDatabase(model, obj);
}));
}.bind(this));
return sql;
function buildWhere(conds) {
var cs = [];
Object.keys(conds).forEach(function (key) {
var keyEscaped = '`' + key.replace(/\./g, '`.`') + '`'
if (conds[key] === null) {
cs.push(keyEscaped + ' IS NULL');
} else if (conds[key].constructor.name === 'Object') {
var condType = Object.keys(conds[key])[0];
var sqlCond = keyEscaped;
switch (condType) {
case 'gt':
sqlCond += ' > ';
break;
case 'gte':
sqlCond += ' >= ';
break;
case 'lt':
sqlCond += ' < ';
break;
case 'lte':
sqlCond += ' <= ';
break;
case 'between':
sqlCond += ' BETWEEN ? AND ?';
queryParams.push(conds[key][condType][0]);
queryParams.push(conds[key][condType][1]);
break;
}
if (condType !== 'between') {
sqlCond += '?';
queryParams.push(conds[key][condType]);
}
cs.push(sqlCond);
} else {
cs.push(keyEscaped + ' = ?');
queryParams.push(self.toDatabase(props[key], conds[key]));
}
});
return 'WHERE ' + cs.join(' AND ');
}
function buildOrderBy(order) {
if (typeof order === 'string') order = [order];
return 'ORDER BY ' + order.join(', ');
}
function buildLimit(limit, offset) {
return 'LIMIT ' + (offset ? (offset + ', ' + limit) : limit);
}
};
SQLite3.prototype.destroyAll = function destroyAll(model, callback) {
this.command('DELETE FROM ' + model, function (err) {
if (err) {
return callback(err, []);
}
callback(err);
}.bind(this));
};
SQLite3.prototype.count = function count(model, callback, where) {
var self = this;
var props = this._models[model].properties;
var queryParams = [];
this.queryOne('SELECT count(*) as cnt FROM ' + model + buildWhere(where), queryParams, function (err, res) {
callback(err, err ? null : res.cnt);
});
function buildWhere(conds) {
var cs = [];
Object.keys(conds || {}).forEach(function (key) {
var keyEscaped = '`' + key.replace(/\./g, '`.`') + '`'
if (conds[key] === null) {
cs.push(keyEscaped + ' IS NULL');
} else {
cs.push(keyEscaped + ' = ?');
queryParams.push(self.toDatabase(props[key], conds[key]));
}
});
return cs.length ? ' WHERE ' + cs.join(' AND ') : '';
}
};
SQLite3.prototype.updateAttributes = function updateAttrs(model, id, data, cb) {
data.id = id;
this.save(model, data, cb);
};
SQLite3.prototype.disconnect = function disconnect() {
this.client.close();
};
SQLite3.prototype.automigrate = function (cb) {
var self = this;
var wait = 0;
Object.keys(this._models).forEach(function (model) {
wait += 1;
self.dropTable(model, function () {
self.createTable(model, function (err) {
if (err) console.log(err);
done();
});
});
});
function done() {
if (--wait === 0 && cb) {
cb();
}
}
};
SQLite3.prototype.autoupdate = function (cb) {
var self = this;
var wait = 0;
Object.keys(this._models).forEach(function (model) {
wait += 1;
self.queryAll('SHOW FIELDS FROM ' + model, function (err, fields) {
self.alterTable(model, fields, done);
});
});
function done(err) {
if (err) {
console.log(err);
}
if (--wait === 0 && cb) {
cb();
}
}
};
SQLite3.prototype.alterTable = function (model, actualFields, done) {
var self = this;
var m = this._models[model];
var propNames = Object.keys(m.properties);
var sql = [];
// change/add new fields
propNames.forEach(function (propName) {
var found;
actualFields.forEach(function (f) {
if (f.Field === propName) {
found = f;
}
});
if (found) {
actualize(propName, found);
} else {
sql.push('ADD COLUMN `' + propName + '` ' + self.propertySettingsSQL(model, propName));
}
});
// drop columns
actualFields.forEach(function (f) {
var notFound = !~propNames.indexOf(f.Field);
if (f.Field === 'id') return;
if (notFound || !m.properties[f.Field]) {
sql.push('DROP COLUMN `' + f.Field + '`');
}
});
if (sql.length) {
this.command('ALTER TABLE `' + model + '` ' + sql.join(',\n'), done);
} else {
done();
}
function actualize(propName, oldSettings) {
var newSettings = m.properties[propName];
if (newSettings && changed(newSettings, oldSettings)) {
sql.push('CHANGE COLUMN `' + propName + '` `' + propName + '` ' + self.propertySettingsSQL(model, propName));
}
}
function changed(newSettings, oldSettings) {
if (oldSettings.Null === 'YES' && (newSettings.allowNull === false || newSettings.null === false)) return true;
if (oldSettings.Null === 'NO' && !(newSettings.allowNull === false || newSettings.null === false)) return true;
if (oldSettings.Type.toUpperCase() !== datatype(newSettings)) return true;
return false;
}
};
SQLite3.prototype.dropTable = function (model, cb) {
this.command('DROP TABLE IF EXISTS ' + model, cb);
};
SQLite3.prototype.createTable = function (model, cb) {
this.command('CREATE TABLE ' + model +
' (\n ' + this.propertiesSQL(model) + '\n)', cb);
};
SQLite3.prototype.propertiesSQL = function (model) {
var self = this;
var sql = ['`id` INTEGER PRIMARY KEY'];
Object.keys(this._models[model].properties).forEach(function (prop) {
sql.push('`' + prop + '` ' + self.propertySettingsSQL(model, prop));
});
return sql.join(',\n ');
};
SQLite3.prototype.propertySettingsSQL = function (model, prop) {
var p = this._models[model].properties[prop];
return datatype(p) + ' ' +
(p.allowNull === false || p['null'] === false ? 'NOT NULL' : 'NULL');
};
function datatype(p) {
switch (p.type.name) {
case 'String':
return 'VARCHAR(' + (p.limit || 255) + ')';
case 'Text':
return 'TEXT';
case 'Number':
return 'INT(11)';
case 'Date':
return 'DATETIME';
case 'Boolean':
return 'TINYINT(1)';
}
}