-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpostgres-bap-conn.js
More file actions
370 lines (279 loc) · 10.7 KB
/
postgres-bap-conn.js
File metadata and controls
370 lines (279 loc) · 10.7 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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"use strict";
const
lodashMerge = require("lodash.merge");
const
FORMAT_JSON = "json",
FORMAT_ARRAY = "array", // array with header + data
FORMAT_ARRAY_NO_HEADER = "array-no-header"; // array data only
class DataStorePostgresConn extends besh.DataStoreBapConn {
constructor(log, pool, id) {
super(log);
this._pool = pool;
this._client = null;
this._id = id;
this.log.debug("Creating connId: %d", this._id);
}
async create(collection, fields, id) {
let query = {};
let fieldStr = "",
valuesStr = "",
count = 1;
query.values = [];
for (const f in fields) {
if (count > 1) {
fieldStr += ",";
valuesStr += ",";
}
fieldStr += f;
query.values.push(fields[f]);
valuesStr += `$${count}`;
count++;
}
if (id === undefined) {
query.text =
`INSERT INTO ${collection} (${fieldStr}) VALUES (${valuesStr})`;
} else {
query.text =
`INSERT INTO ${collection} (${fieldStr}) VALUES (${valuesStr})
RETURNING ${id}`.replace(/\s\s+/g, " ").replace(/\n/g, " ");
}
this.log.debug("connId:%d create() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
if (e.code === "23505") {
throw new besh.DataStoreBapConnError(
"Duplicate record exists!",
besh.DataStoreBapConnError.DUP_CODE, this)
}
throw this.Error("Something wrong with your request!", e.code);
});
return res.rows;
}
async read(collection, fields, criteria, opts) {
// opts = { orderBy, orderByDesc, format, distinct }
let query = {},
defaults = {
format: this.JSON,
distinct: false
};
if (fields === undefined) {
fields = [ "*" ];
}
opts = lodashMerge(defaults, opts);
if (opts.distinct) {
query.text =
`SELECT DISTINCT ${fields.join()} FROM ${collection}`;
}
else {
query.text = `SELECT ${fields.join()} FROM ${collection}`;
}
query.values = [];
if (criteria !== undefined && Object.keys(criteria).length > 0) {
query.text += " WHERE ";
let position = 1;
for (const fld in criteria) {
if (position > 1) {
query.text += " AND ";
}
const val = criteria[fld];
if (Array.isArray(val)) {
let inText = `$${position}`;
query.values.push(val[0]);
position++;
// Start from 1, not fom 0!
for (let i = 1; i < val.length; i++) {
inText += `,$${position}`;
query.values.push(val[i]);
position++;
}
query.text += `${fld} IN (${inText})`;
} else if (typeof val === "object") {
query.text += `${fld}${val.op}$${position}`;
query.values.push(val.val);
position++;
} else {
query.text += `${fld}=$${position}`;
query.values.push(val);
position++;
}
}
}
let orderByAdded = false;
if (opts.groupBy !== undefined && opts.groupBy.length > 0) {
query.text += ` GROUP BY ${opts.groupBy.join()}`;
}
if (opts.orderBy !== undefined && opts.orderBy.length > 0) {
query.text += ` ORDER BY ${opts.orderBy.join()}`;
query.text += " ASC"
orderByAdded = true;
}
if (opts.orderByDesc !== undefined && opts.orderByDesc.length > 0) {
if (orderByAdded) {
query.text += `, ${opts.orderByDesc.join()} DESC`;
} else {
query.text += ` ORDER BY ${opts.orderByDesc.join()} DESC`;
}
}
if (opts.format === this.ARRAY ||
opts.format === this.ARRAY_NO_HEADER) {
query.rowMode = "array";
}
this.log.debug("connId:%d retrieve() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
if (opts.format === this.ARRAY_HEADER) {
return res.fields;
}
if (opts.format === this.ARRAY) {
let rows = res.fields.map((f) => f.name);
return [rows, ...res.rows];
}
return res.rows;
}
async update(collection, fields, criteria) {
let query = {};
let fieldStr = "",
count = 1;
query.values = [];
for (const f in fields) {
if (count > 1) {
fieldStr += ",";
}
fieldStr += `${f}=$${count}`;
query.values.push(fields[f]);
count++;
}
query.text = `UPDATE ${collection} SET ${fieldStr}`;
if (criteria !== undefined &&
Object.keys(criteria).length > 0) {
let where = "";
for (const c in criteria) {
if (where.length !== 0) {
where += " AND ";
}
where += `${c}=$${count}`;
query.values.push(criteria[c]);
count++;
}
query.text += ` WHERE ${where}`;
}
this.log.debug("connId:%d update() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
if (e.code === "23505") {
throw new besh.DataStoreBapConnError(
"Duplicate record exists!",
besh.DataStoreBapConnError.DUP_CODE, this)
}
throw this.Error("Something wrong with your request!", e.code);
});
return res.rowCount;
}
async delete(collection, criteria) {
let query = {};
query.values = [];
query.text = `DELETE FROM ${collection}`;
let count = 1;
if (criteria !== undefined &&
Object.keys(criteria).length > 0) {
let where = "";
for (const c in criteria) {
if (where.length !== 0) {
where += " AND ";
}
where += `${c}=$${count}`;
query.values.push(criteria[c]);
count++;
}
query.text += ` WHERE ${where}`;
}
this.log.debug("connId:%d delete() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
return res.rowCount;
}
async query(query) {
this.log.debug("connId:%d query() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
return res.rows;
}
async exec(query) {
this.log.debug("connId:%d query() query: %j", this._id, query);
let client = this._client === null ? this._pool : this._client;
let res = await client.query(query).catch((e) => {
// TODO: Improve error handling
this.log.error("connId:%d '%s' happened for query (%j): %j",
this._id, e, query, e);
throw this.Error("Something wrong with your request!", e.code);
});
return res.rowCount;
}
async connect() {
if (this._client !== null) {
throw this.Error(`connId:${this._id} Already have a connection!`);
}
this.log.debug(`connId:${this._id} Getting connection`);
this._client = await this._pool.connect();
}
async release() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Releasing connection`);
await this._client.release();
this._client = null;
}
async begin() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Beginning transaction ...`);
await this._client.query("BEGIN;");
}
async commit() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Commiting transaction ...`);
await this._client.query("COMMIT;");
}
async rollback() {
if (this._client === null) {
throw this.Error(`connId:${this._id} Do not have a connection!`);
}
this.log.debug(`connId:${this._id} Rolling back transaction ...`);
await this._client.query("ROLLBACK;");
}
get JSON() {
return FORMAT_JSON;
}
get ARRAY() {
return FORMAT_ARRAY;
}
get ARRAY_NO_HEADER() {
return FORMAT_ARRAY_NO_HEADER;
}
}
module.exports = DataStorePostgresConn;