-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
304 lines (259 loc) · 8.58 KB
/
db.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
'use strict';
const { Pool } = require('pg');
const conditionParse = (object, length) => {
let value;
let condition;
let i = length ? length : 1;
if (Object.getOwnPropertyNames(object).length !== 1) {
throw new Error('Must be only 1 condition!')
} else {
const [key, val] = Object.entries(object)[0];
if (val.startsWith('=')) {
condition = `${key} = $${i}`;
value = val.substring(1);
} else if (val.startsWith('>=')) {
condition = `${key} >= $${i}`;
value = val.substring(2);
} else if (val.startsWith('<=')) {
condition = `${key} <= $${i}`;
value = val.substring(2);
} else if (val.startsWith('<>') || val.startsWith('!=')) {
condition = `${key} <> $${i}`;
value = val.substring(2);
} else if (val.startsWith('>')) {
condition = `${key} > $${i}`;
value = val.substring(1);
} else if (val.startsWith('<')) {
condition = `${key} < $${i}`;
value = val.substring(1);
} else if (val.includes('*') || val.includes('?')) {
value = val.replace(/\*/g, '%').replace(/\?/g, '_');
condition = `${key} LIKE $${i}`;
}
}
return { condition, value };
}; //DONE
class Cursor {
constructor(db) {
this.database = db;
this.operation = undefined;
this.sql = undefined;
this.table = undefined;
this.condition = undefined;
this.rowLimit = undefined;
this.offset = undefined;
this.fields = [];
this.orderBy = [];
this.args = [];
this.newTable = undefined;
this.fieldsOptions = {};
} //DONE
select(...fields) {
this.operation = this.selectBuilder;
if (fields[0] === '*' || !fields.length) {
this.fields.push('*');
} else {
for (const field of fields) {
this.fields.push(field);
}
}
return this;
} //DONE
insert(object) {
this.operation = this.insertBuilder;
for (const [key, val] of Object.entries(object)) {
this.fields.push(key);
this.args.push(val);
}
return this;
} //DONE
update(object) {
this.operation = this.updateBuilder;
for (const [key, val] of Object.entries((object))) {
this.fields.push(key);
this.args.push(val);
}
return this;
} //DONE
delete() {
this.operation = this.deleteBuilder;
return this;
} //DONE
createTable(name) {
this.operation = this.createTableBuilder;
this.newTable = name;
return this;
} //DONE
removeTable(...tables) {
this.operation = this.removeTableBuilder;
this.table = tables;
return this;
} //DONE
renameTable(oldTable, newTable) {
this.operation = this.renameTableBuilder;
this.table = oldTable;
this.newTable = newTable;
return this;
} //DONE
withField(object) {
for (const [key, obj] of Object.entries(object)) {
const options = {
primaryKey: false,
type: 'VARCHAR(50)',
unique: false,
notNull: true,
};
for (const option of Object.keys(options)) {
if (obj.hasOwnProperty(option)) {
options[option] = obj[option];
}
}
if (obj.hasOwnProperty('default')) {
options['default'] = obj['default'];
}
this.fieldsOptions[key] = options;
}
return this;
} //DONE
limit(count, offset) {
this.rowLimit = count;
this.offset = offset;
return this;
} //DONE
where(cond) {
const { condition, value } = conditionParse(cond, this.args.length + 1);
this.condition = condition;
this.args.push(value);
return this;
} //DONE
and(cond) {
const { condition, value } = conditionParse(cond, this.args.length + 1);
this.condition += ` AND ${condition}`;
this.args.push(value);
return this;
} //DONE
or(cond) {
const { condition, value } = conditionParse(cond, this.args.length + 1);
this.condition += ` OR ${condition}`;
this.args.push(value);
return this;
} //DONE
inOrder(object) {
for (const [key, val] of Object.entries(object)) {
const mode = val ? val : 'ASC';
this.orderBy.push(`${key} ${mode}`);
}
return this;
} //DONE
inTable(table) {
this.table = table;
return this;
} //DONE
//SQL BUILDERS
selectBuilder() {
const { table, fields, condition, orderBy, rowLimit, offset } = this;
const columns = fields.join(', ');
const ordering = orderBy.join(', ');
this.sql = `SELECT ${columns} FROM "${table}"`;
this.sql += condition ? ` WHERE ${condition}`: '';
this.sql += ordering ? ` ORDER BY ${ordering}` : '';
this.sql += rowLimit ? ` LIMIT ${rowLimit}` : '';
this.sql += offset ? ` OFFSET ${offset}` : '';
} //DONE
insertBuilder() {
const { table, fields } = this;
const values = [];
for (let i = 1; i <= fields.length; i++) {
values.push(`$${i}`);
}
const joinedValues = values.join(', ');
const joinedFields = fields.join(', ')
this.sql = `INSERT INTO "${table}"(${joinedFields}) VALUES (${joinedValues})`;
} //DONE
updateBuilder() {
const { table, fields, condition } = this;
const updatedColumns = [];
for (let i = 0; i < fields.length; i++) {
updatedColumns.push(`${fields[i]} = $${i + 1}`);
}
const updatedColsJoined = updatedColumns.join(',');
this.sql = `UPDATE "${table}" SET ${updatedColsJoined} WHERE ${condition}`;
} //DONE
deleteBuilder() {
const { table, condition } = this;
this.sql = `DELETE FROM "${table}" WHERE ${condition}`;
} //DONE
createTableBuilder() {
const { newTable, fieldsOptions } = this;
const fields = [];
for (const key of Object.keys(fieldsOptions)) {
const options = fieldsOptions[key];
let field = `${key} ${options.type}`;
field += options.primaryKey ? ' PRIMARY KEY' : '';
field += options.unique ? ' UNIQUE' : '';
field += options.notNull ? ' NOT NULL' : '';
field += options.hasOwnProperty('default') ? ` DEFAULT ${options.default}` : '';
fields.push(field);
}
const strFields = fields.join(',\n ');
this.sql = `CREATE TABLE IF NOT EXISTS ${newTable}(\n ${strFields} \n);`;
} //DONE
removeTableBuilder() {
const tables = this.table.join(', ');
this.sql = `DROP TABLE IF EXISTS ${tables}`;
} //DONE
renameTableBuilder() {
const { table, newTable } = this;
this.sql = `ALTER TABLE IF EXISTS "${table}" RENAME TO ${newTable}`;
} //DONE
async exec(callback) {
this.operation();
const { sql, args } = this;
console.log(args);
await this.database.query(sql, args, (err, res) => {
if (callback) {
if (res === undefined) {
callback(err, undefined);
return;
}
this.rows = res.rows;
const { rows, cols } = this;
callback(err, rows);
} else {
throw new Error('Missing callback!');
}
});
} //DONE
}
class Database {
constructor(config, initSql) {
this.pool = new Pool(config);
this.config = config;
console.log('Created pool.');
this.ready = true;
if (initSql) {
this.pool.query(initSql)
.catch(err => console.log(`Database initialization failed: ${err}`));
}
} //TODO
query(sql, values, callback) {
if (typeof (values) === 'function') {
callback = values;
values = [];
}
this.pool.query(sql, values, (err, res) => {
console.group('Created sql request to db:');
console.log(`SQL: \n${sql}`);
console.groupEnd();
callback ? callback(err, res) : undefined;
})
} //TODO
sql() {
return new Cursor(this);
} //DONE
close() {
console.log('Pool was closed!');
this.pool.end();
} //DONE
}
module.exports = Database;