Permalink
Browse files

Merge pull request #28 from samcday/json-schema-support

Add support for Schema.JSON type.
  • Loading branch information...
2 parents a3af752 + 78d3cae commit 833df9fdc269c0ba248956fd2e48e6ea6ff3cbbc @1602 1602 committed Mar 4, 2014
Showing with 15 additions and 6 deletions.
  1. +15 −6 lib/sqlite3.js
View
@@ -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 += ')';
@@ -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 += ')';
@@ -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') {
@@ -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') {
@@ -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;
@@ -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)';

0 comments on commit 833df9f

Please sign in to comment.