forked from dresende/node-sql-query
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreate.js
More file actions
112 lines (99 loc) · 2.49 KB
/
Create.js
File metadata and controls
112 lines (99 loc) · 2.49 KB
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
exports.CreateQuery = CreateQuery;
/**
* Really lightweight templating
* @param template
* @param args
* @returns {string}
*/
var tmpl = function (template, args) {
var has = {}.hasOwnProperty;
for (var key in args) {
if (!has.call(args, key)) {
continue;
}
var token = '{{' + key + '}}';
template = template.split(token).join(args[key]);
}
return template;
};
/**
* Builds a list of fields according to the used dialect
* @param dialect
* @param structure
* @returns {string}
*/
var buildFieldsList = function (dialect, structure) {
if (!structure) {
return "";
}
var tpl = "'{{NAME}}' {{TYPE}}", fields = [], has = {}.hasOwnProperty;
for (var field in structure) {
if (has.call(structure, field)) {
fields.push(tmpl(tpl, {
NAME: field,
TYPE: dialect.DataTypes[structure[field]]
}));
}
}
return fields.join(',');
};
/**
* Instantiate a new CREATE-type query builder
* @param Dialect
* @param opts
* @returns {{table: table, field: field, fields: fields, build: build}}
* @constructor
*/
function CreateQuery(Dialect, opts) {
var sql = {};
var tableName = null;
var structure = {};
return {
/**
* Set the table name
* @param table_name
* @returns {*}
*/
table: function (table_name) {
tableName = table_name;
return this;
},
/**
* Add a field
* @param name
* @param type
* @returns {Object}
*/
field: function (name, type) {
structure[name] = type;
return this;
},
/**
* Set all the fields
* @param fields
* @returns {Object}
*/
fields: function (fields) {
if (!fields) {
return structure;
}
structure = fields;
return this;
},
/**
* Build a query from the passed params
* @returns {string}
*/
build: function () {
var query, fieldsList, template = "CREATE TABLE '{{TABLE_NAME}}'({{FIELDS_LIST}})";
if(!tableName){
return '';
}
fieldsList = buildFieldsList(Dialect, structure);
return tmpl(template, {
TABLE_NAME: tableName,
FIELDS_LIST: fieldsList
});
}
};
}