-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
111 lines (89 loc) · 2.46 KB
/
index.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
var util = require('util');
function Val(val) {
this.val = val;
}
Val.prototype = {
isEmpty: function () {
if (this.val == null) {
return true;
}
switch (this.val.constructor.name) {
case 'Boolean':
return false;
case 'Array':
return this.val.length == 0;
default:
return !Boolean(this.val);
}
},
toString: function () {
return this.isEmpty() ? '' : this._toCode();
},
_toCode: function () {
return this.toCode ? this.toCode() : this.val;
}
};
function QuotedVal(val) {
Val.call(this, val);
}
util.inherits(QuotedVal, Val);
QuotedVal.prototype.toCode = function () {
return "'" + this.val + "'";
};
function LengthVal(val) {
Val.call(this, val);
}
util.inherits(LengthVal, Val);
LengthVal.prototype.toCode = function () {
return '( ' + this.val + ' )';
};
function ValuesVal(val) {
Val.call(this, val);
}
util.inherits(ValuesVal, Val);
ValuesVal.prototype.toCode = function () {
return '( ' + JSON.stringify(this.val).slice(1, -1) + ' )';
};
function Field(attr) {
var options = attr.type.options || {};
this.type = attr.type.key;
this.name = attr.field;
this.autoIncrement = new Val(attr.autoIncrement);
this.allowNull = new Val(attr.allowNull);
this.defaultValue = new Val(attr.defaultValue);
this.primaryKey = new Val(attr.primaryKey);
this.onDelete = new QuotedVal(attr.onDelete);
this.onUpdate = new QuotedVal(attr.onUpdate);
this.references = attr.references;
this.unsigned = options.unsigned;
this.values = new ValuesVal(options.values);
this.length = new LengthVal(options.length);
}
Field.create = function (attr) {
return new Field(attr);
};
Field.opts = [
'autoIncrement',
'allowNull',
'defaultValue',
'primaryKey',
'onDelete',
'onUpdate'
];
exports.Field = Field;
function Model(model) {
this.tableName = model.tableName;
this.uniqueKeys = model.uniqueKeys;
this.fields = Model.getReOrderedFields(model.attributes);
}
Model.getReOrderedFields = function (attsObj) {
var fieldNames = Object.keys(attsObj);
var indexOfIdField = fieldNames.indexOf('id');
if (indexOfIdField > -1) {
fieldNames = fieldNames.splice(indexOfIdField, 1).concat(fieldNames);
}
return fieldNames.map(function (name) {
return Field.create(attsObj[name]);
});
};
exports.Model = Model;