Skip to content

Commit

Permalink
Add support for Schema.JSON type.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam Day committed Mar 3, 2014
1 parent a3af752 commit 78d3cae
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/sqlite3.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,11 @@ SQLite3.prototype.save = function (model, data, callback) {
SQLite3.prototype.create = function (model, data, callback) {
data = data || {};
var questions = [];
var props = this._models[model].properties;
var values = Object.keys(data).map(function (key) {
questions.push('?');
return data[key];
});
return this.toDatabase(props[key], data[key]);
}.bind(this));
var sql = 'INSERT INTO ' + this.tableEscaped(model) + ' (`' + Object.keys(data).join('`, `') + '`) VALUES ('
sql += questions.join(',');
sql += ')';
Expand All @@ -94,11 +95,12 @@ SQLite3.prototype.create = function (model, data, callback) {

SQLite3.prototype.updateOrCreate = function (model, data, callback) {
data = data || {};
var props = this._models[model].properties;
var questions = [];
var values = Object.keys(data).map(function (key) {
questions.push('?');
return data[key];
});
return this.toDatabase(props[key], data[key]);
}.bind(this));
var sql = 'INSERT OR REPLACE INTO ' + this.tableEscaped(model) + ' (`' + Object.keys(data).join('`, `') + '`) VALUES ('
sql += questions.join(',');
sql += ')';
Expand Down Expand Up @@ -181,7 +183,10 @@ SQLite3.prototype.escape = function(val, stringifyObjects) {
};

SQLite3.prototype.toDatabase = function (prop, val) {
if (val.constructor.name === 'Object') {
if (prop && prop.type.name === 'JSON') {
return JSON.stringify(val);
}
if (val && val.constructor.name === 'Object') {
var operator = Object.keys(val)[0]
val = val[operator];
if (operator === 'between') {
Expand All @@ -199,7 +204,7 @@ SQLite3.prototype.toDatabase = function (prop, val) {
}
}
}
if (!prop) return val;
if (!prop || "undefined" === typeof val) return val;
if (prop.type.name === 'Number') return val;
if (val === null) return 'NULL';
if (prop.type.name === 'Date') {
Expand All @@ -223,6 +228,9 @@ SQLite3.prototype.fromDatabase = function (model, data) {
}
if (props[key]) {
switch (props[key].type.name) {
case 'JSON':
val = JSON.parse(val);
break;
case 'Date':
val = new Date(parseInt(val));
break;
Expand Down Expand Up @@ -552,6 +560,7 @@ function datatype(p) {
case 'String':
return 'VARCHAR(' + (p.limit || 255) + ')';
case 'Text':
case 'JSON':
return 'TEXT';
case 'Number':
return 'INT(11)';
Expand Down

0 comments on commit 78d3cae

Please sign in to comment.