-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquerybuilder2.js
346 lines (264 loc) · 10.7 KB
/
querybuilder2.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
const { Pool } = require('pg');
const utils = require('./utils');
class QueryBuilder {
pool = null;
_config = {};
constructor(config) {
this._config = config;
this.pool = new Pool({
user: config.connection.user,
host: config.connection.host,
database: config.connection.database,
password: config.connection.password,
port: config.connection.port
});
}
async count(type, filters, conn) {
if(!conn)
conn = this.pool;
let parsed_filters = this.parseFilters(filters);
const query_str = 'SELECT COUNT(*) as "count" FROM ' + type + ' WHERE ' + parsed_filters.clauses.join(' AND ');
return (await this.query(query_str, parsed_filters.params, conn)).rows[0].count;
}
async sum(type, sum_column, filters, conn) {
if(!conn)
conn = this.pool;
let parsed_filters = this.parseFilters(filters);
const query_str = 'SELECT SUM(' + sum_column + ') as "sum" FROM ' + type + ' WHERE ' + parsed_filters.clauses.join(' AND ');
return (await this.query(query_str, parsed_filters.params, conn)).rows[0].sum;
}
parseFilters(filters, start) {
return { params: this.parseParams(filters), clauses: this.parseClauses(filters, start) };
}
parseClauses(filters, start, param_index) {
if(!start)
start = 0;
if(!param_index)
param_index = 0;
return Object.keys(filters).map(f => {
if(filters[f] == null)
return f + ' IS NULL';
else if(f.startsWith('_') && filters[f] != null && typeof filters[f] == 'object') {
return '(' + this.parseClauses(filters[f], start, param_index).join(' OR ') + ')';
} else if(Array.isArray(filters[f])) {
var val = f + ' IN ' + utils.inClause(start + ++param_index, filters[f]);
param_index += filters[f].length - 1;
return val
} else if(typeof filters[f] == 'object' && filters[f].op) {
return `${f} ${filters[f].op} $${start + ++param_index}`;
} else
return f + ' = $' + (start + ++param_index);
});
}
parseParams(filters) {
let params = [];
Object.keys(filters).forEach(f => {
if(Array.isArray(filters[f]))
params = params.concat(filters[f]);
else if(f.startsWith('_') && filters[f] != null && typeof filters[f] == 'object') {
params = params.concat(this.parseParams(filters[f]));
} else if(filters[f] != null && typeof filters[f] == 'object' && filters[f].op) {
params.push(filters[f].value);
} else if(filters[f] != null)
params.push(filters[f])
});
return params;
}
async lookup(type, options, conn) {
try {
if (!conn) conn = this.pool;
if (!options) options = {};
let params = [];
const columns = options.columns && Array.isArray(options.columns) ? options.columns.join(', ') : '*';
let query_str = `SELECT ${columns} FROM ${type}`;
if (options.filters && Object.keys(options.filters).length > 0) {
const filters = this.parseFilters(options.filters);
params = filters.params;
query_str += ` WHERE ${filters.clauses.join(' AND ')}`;
}
if (options.sort_by) {
query_str += ` ORDER BY ${options.sort_by}`;
if (options.sort_descending) query_str += ' DESC';
}
if (options.limit) query_str += ` LIMIT ${options.limit}`;
if (options.offset) query_str += ` OFFSET ${options.offset}`;
if (options.lockLevel) {
if (options.lockLevel) query_str += ` FOR ${options.lockLevel}`;
if (options.nowait) query_str += ' NOWAIT';
else if (options.skip_locked) query_str += ' SKIP LOCKED';
}
return (await this.query_internal(query_str, params, conn)).rows;
} catch (err) {
utils.log(err.message, 1, 'Red');
utils.log(err.stack, 1, 'Red');
}
}
async lookupSingle(type, filters, conn, options) {
const records = await this.lookup(type, { filters, ...options }, conn);
return records && records.length > 0 ? records[0] : null;
}
async insert(type, data, conn, no_return, on_conflict_clause) {
if (!conn) conn = this.pool;
const fields = Object.keys(data);
const params = fields.map((f) => data[f]);
const indices = fields.map((f, i) => `$${i + 1}`);
let query_str = `INSERT INTO ${type}(${fields.join(',')}) VALUES (${indices.join(',')})`;
if (!no_return) query_str += RETURNING_STR;
if (on_conflict_clause) query_str += ` ${on_conflict_clause}`;
const ret_val = await this.query_internal(query_str, params, conn);
return no_return ? ret_val.rowCount : ret_val.rows.length > 0 ? ret_val.rows[0] : null;
}
async insertMultiple(type, data, conn, no_return) {
if (!conn) conn = this.pool;
const fields = Object.keys(data[0]);
let params = [];
let values = '';
for (let i = 0; i < data.length; i++) {
const obj = data[i];
params = params.concat(fields.map((f) => obj[f]));
const indices = fields.map((f, d) => `$${i * fields.length + d + 1}`);
values += `${i > 0 ? ',' : ''}(${indices.join(',')})`;
}
let query_str = `INSERT INTO ${type}(${fields.join(',')}) VALUES ${values}`;
if (!no_return) query_str += RETURNING_STR;
const ret_val = await this.query_internal(query_str, params, conn);
return no_return ? ret_val.rowCount : ret_val.rows;
}
async deleteRows(type, filters, conn, no_return) {
if (!conn) conn = this.pool;
const parsed_filters = this.parseFilters(filters);
let query_str = `DELETE FROM ${type} WHERE ${parsed_filters.clauses.join(' AND ')}`;
if (!no_return) query_str += RETURNING_STR;
return (await this.query_internal(query_str, parsed_filters.params, conn)).rows;
}
async deleteSingle(type, filters, conn, no_return) {
const deleted = await this.deleteRows(type, filters, conn, no_return);
return deleted && deleted.length > 0 ? deleted[0] : null;
}
async update(type, data, filters, conn, no_return) {
if (!conn) conn = this.pool;
const data_fields = Object.keys(data);
const data_clauses = data_fields.map((f, i) => `${f} = $${i + 1}`);
const parsed_filters = this.parseFilters(filters, data_fields.length);
const params = data_fields.map((f) => data[f]).concat(parsed_filters.params);
let query_str = `UPDATE ${type} SET ${data_clauses.join(',')} WHERE ${parsed_filters.clauses.join(' AND ')}`;
if (!no_return) {
query_str += RETURNING_STR;
}
return (await this.query_internal(query_str, params, conn)).rows;
}
async updateSingle(type, data, filters, conn, no_return) {
const updated = await this.update(type, data, filters, conn, no_return);
return updated && updated.length > 0 ? updated[0] : null;
}
async upsert(type, keys, values, conn, no_return) {
if (!conn) conn = this.pool;
const key_fields = Object.keys(keys);
const value_fields = Object.keys(values);
const all_fields = [...key_fields, ...value_fields];
const params = [...key_fields.map((f) => keys[f]), ...value_fields.map((f) => values[f])];
const indices = all_fields.map((f, i) => `$${i + 1}`);
const value_clauses = value_fields.map((f, i) => `${f} = $${i + key_fields.length + 1}`);
const unique_fields = [...new Set(all_fields)];
let query_str = `INSERT INTO ${type}(${unique_fields.join(',')}) VALUES (${indices.slice(0, unique_fields.length).join(',')}) ON CONFLICT(${key_fields.join(',')}) DO UPDATE SET ${value_clauses.join(
','
)}`;
if (!no_return) {
query_str += RETURNING_STR;
}
const upserted = (await this.query_internal(query_str, params, conn)).rows;
return upserted && upserted.length > 0 ? upserted[0] : null;
}
async increment(type, data, filters, conn, no_return) {
if (!conn) conn = this.pool;
const data_fields = Object.keys(data);
const data_clauses = data_fields.map((f, i) => `${f} = ${f} + $${i + 1}`);
const parsed_filters = this.parseFilters(filters, data_fields.length);
const params = data_fields.map((f) => data[f]).concat(parsed_filters.params);
let query_str = `UPDATE ${type} SET ${data_clauses.join(',')} WHERE ${parsed_filters.clauses.join(' AND ')}`;
if (!no_return) query_str += RETURNING_STR;
const ret_val = await this.query_internal(query_str, params, conn);
return no_return ? ret_val.rowCount : ret_val.rows;
}
async incrementSingle(type, data, filters, conn, no_return) {
const records = await this.increment(type, data, filters, conn, no_return);
return no_return ? records : records && records.length > 0 ? records[0] : null;
}
async readQuery(text, params, retries) {
try {
const start_time = Date.now();
const result = await this.pool.query(text, params);
const total_time = Date.now() - start_time;
if (this._config.slow_query_time && total_time > this._config.slow_query_time) utils.log(`Slow query: ${text}, time: ${total_time}`, 1, 'Yellow');
return result;
} catch (err) {
utils.log(`Query failed (read-replica) [${text}], Error: ${err.message}`, 0, 'Red');
}
}
async query(text, params, conn, retries) {
try {
if (!conn) conn = this.pool;
const start_time = Date.now();
const result = await conn.query(text, params);
const total_time = Date.now() - start_time;
if (this._config.slow_query_time && total_time > this._config.slow_query_time) {
utils.log(`Slow query: ${text}, Param: ${params && params.length > 0 ? params[0] : ''}, Time: ${total_time}`, 1, 'Yellow');
}
return result;
} catch (err) {
utils.log(`Query failed [${text}], Error: ${err.message} Param: ${params && params.length > 0 ? params[0] : ''}`, 0, 'Red');
return null;
}
}
async transaction(callback) {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const result = await callback(client);
if (result && result.error) {
await client.query('ROLLBACK');
return result;
}
await client.query('COMMIT');
return result;
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
async transaction_fake(callback) {
return callback(this.pool);
}
async query_internal(text, params, conn) {
if (!conn) conn = this.pool;
try {
const start_time = Date.now();
const result = await conn.query(text, params);
const total_time = Date.now() - start_time;
if (this._config.slow_query_time && total_time > this._config.slow_query_time) {
utils.log(`Slow query: ${text}, time: ${total_time}`, 1, 'Yellow');
}
return result;
} catch (err) {
utils.log(`Query failed [${text}], Error: ${err.message} Param: ${params && params.length > 0 ? params[0] : ''}`, 0, 'Red');
throw err;
}
}
async query(text, params, conn) {
if(!conn) conn = this.pool;
try {
const start_time = Date.now();
const result = await conn.query(text, params);
const total_time = Date.now() - start_time;
if(this._config.slow_query_limit && total_time > this._config.slow_query_limit)
utils.log('Slow query: ' + text + ', time: ' + total_time, 1, 'Yellow');
return result;
} catch(err) {
utils.log('Query failed [' + text + '], Error: ' + err.message + ' Param: ' + (params && params.length > 0 ? params[0] : ''), 0, 'Red');
throw err;
}
}
}
module.exports = { QueryBuilder };