forked from sqlpad/sqlpad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatements.js
More file actions
323 lines (274 loc) · 8.17 KB
/
statements.js
File metadata and controls
323 lines (274 loc) · 8.17 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
/* eslint-disable no-await-in-loop */
const util = require('util');
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const { promisify } = require('util');
const LRU = require('lru-cache');
const redis = require('redis');
const { Op } = require('@rickbergfalk/sequelize');
const ensureJson = require('./ensure-json');
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);
const unlink = util.promisify(fs.unlink);
const access = util.promisify(fs.access);
function redisDbKey(id) {
return `statement-result/${id}`;
}
class Statements {
/**
* @param {import('../sequelize-db')} sequelizeDb
* @param {import('../lib/config')} config
*/
constructor(sequelizeDb, config) {
this.sequelizeDb = sequelizeDb;
this.config = config;
this.queryResultStore = config.get('queryResultStore');
if (this.queryResultStore === 'redis') {
const client = redis.createClient(config.get('redisUri'));
this.redisClient = client;
this.redisGetAsync = promisify(client.get).bind(client);
this.redisSetexAsync = promisify(client.setex).bind(client);
this.redisDelAsync = promisify(client.del).bind(client);
}
if (this.queryResultStore === 'memory') {
this.memoryCache = new LRU({ max: 1000, maxAge: 1000 * 60 * 60 });
}
}
isFileStore() {
return this.queryResultStore === 'file';
}
isDatabaseStore() {
return this.queryResultStore === 'database';
}
isRedisStore() {
return this.queryResultStore === 'redis';
}
isMemoryStore() {
return this.queryResultStore === 'memory';
}
async findOneById(id) {
let statement = await this.sequelizeDb.Statements.findOne({
where: { id },
});
if (!statement) {
return;
}
statement.columns = ensureJson(statement.columns);
statement.error = ensureJson(statement.error);
return statement.toJSON();
}
async findAllByBatchId(batchId) {
let items = await this.sequelizeDb.Statements.findAll({
where: { batchId },
order: [['sequence', 'ASC']],
});
items = items.map((item) => {
const i = item.toJSON();
i.columns = ensureJson(i.columns);
i.error = ensureJson(i.error);
return i;
});
return items;
}
/**
* Remove statement by id
* @param {string} id - statement id
*/
async removeById(id) {
const statement = await this.findOneById(id);
const { resultsPath } = statement;
if (this.isFileStore() && resultsPath) {
const dbPath = this.config.get('dbPath');
const fullPath = path.join(dbPath, resultsPath);
let exists = true;
try {
await access(fullPath);
} catch (error) {
exists = false;
}
if (exists) {
await unlink(fullPath);
}
}
if (this.isRedisStore()) {
await this.redisDelAsync(redisDbKey(id));
}
if (this.isMemoryStore()) {
this.memoryCache.del(id);
}
if (this.isDatabaseStore()) {
await this.sequelizeDb.Cache.destroy({ where: { id: redisDbKey(id) } });
}
return this.sequelizeDb.Statements.destroy({ where: { id } });
}
async updateStarted(id, startTime) {
const update = {
status: 'started',
startTime,
};
await this.sequelizeDb.Statements.update(update, { where: { id } });
return this.findOneById(id);
}
async updateErrored(id, error, stopTime, durationMs) {
const update = {
status: 'error',
stopTime,
durationMs,
error,
};
await this.sequelizeDb.Statements.update(update, { where: { id } });
return this.findOneById(id);
}
async updateErrorQueuedToCancelled(batchId) {
await this.sequelizeDb.Statements.update(
{ status: 'cancelled' },
{ where: { batchId, status: 'queued' } }
);
}
async updateCancelled(id, stopTime, durationMs) {
const update = {
status: 'cancelled',
stopTime,
durationMs,
};
await this.sequelizeDb.Statements.update(update, { where: { id } });
return this.findOneById(id);
}
async updateFinished(id, queryResult, stopTime, durationMs) {
const { config } = this;
const dbPath = config.get('dbPath');
const rowCount = queryResult.rows.length;
let resultsPath;
// If rows returned write results csv
if (rowCount > 0) {
const arrOfArr = queryResult.rows.map((row) => {
return queryResult.columns.map((col) => row[col.name]);
});
if (this.isFileStore()) {
const dir = id.slice(0, 3);
await mkdirp(path.join(dbPath, 'results', dir));
resultsPath = path.join('results', dir, `${id}.json`);
const fullPath = path.join(dbPath, resultsPath);
await writeFile(fullPath, JSON.stringify(arrOfArr));
}
if (this.isRedisStore()) {
// Redis results can be removed by redis itself
// In the event seconds does not exist or is zero, default to 1 hour
let seconds =
parseInt(config.get('queryHistoryRetentionTimeInDays'), 10) * 86400;
if (!seconds || seconds <= 0) {
seconds = 60 * 60;
}
await this.redisSetexAsync(
redisDbKey(id),
seconds,
JSON.stringify(arrOfArr)
);
}
if (this.isDatabaseStore()) {
const ONE_DAY = 1000 * 60 * 60 * 24;
const daysMs =
parseInt(config.get('queryHistoryRetentionTimeInDays'), 10) * ONE_DAY;
const expiryDate = new Date(Date.now() + daysMs);
await this.sequelizeDb.Cache.create({
id: redisDbKey(id),
data: arrOfArr,
expiryDate,
name: 'statement results',
});
}
if (this.isMemoryStore()) {
this.memoryCache.set(id, arrOfArr);
}
}
const update = {
status: 'finished',
stopTime,
durationMs,
rowCount,
affectedRows: queryResult.affectedRows,
columns: queryResult.columns,
resultsPath,
incomplete: queryResult.incomplete,
};
await this.sequelizeDb.Statements.update(update, { where: { id } });
}
async getStatementResults(id) {
const statement = await this.findOneById(id);
if (!statement) {
throw new Error('Statement not found');
}
const { config } = this;
if (this.isFileStore()) {
const { resultsPath } = statement;
// If no result path the query had no rows.
// Return empty array
if (!resultsPath) {
return [];
}
const fullPath = path.join(config.get('dbPath'), resultsPath);
let exists = true;
try {
await access(fullPath);
} catch (error) {
exists = false;
}
if (exists) {
const fileData = await readFile(fullPath, 'utf8');
return JSON.parse(fileData);
}
return [];
}
if (this.isRedisStore()) {
const json = await this.redisGetAsync(redisDbKey(statement.id));
if (json) {
const parsed = JSON.parse(json);
if (Array.isArray(parsed)) {
return parsed;
}
}
return [];
}
if (this.isDatabaseStore()) {
const doc = await this.sequelizeDb.Cache.findOne({
where: { id: redisDbKey(statement.id) },
});
if (doc) {
const result = ensureJson(doc.data);
if (Array.isArray(result)) {
return result;
}
}
return [];
}
if (this.isMemoryStore()) {
const result = this.memoryCache.get(statement.id);
if (Array.isArray(result)) {
return result;
}
return [];
}
}
async removeOldEntries() {
const days =
this.config.get('queryHistoryRetentionTimeInDays') * 86400 * 1000;
const retentionPeriodStartTime = new Date(new Date().getTime() - days);
const statements = await this.sequelizeDb.Statements.findAll({
where: { createdAt: { [Op.lt]: retentionPeriodStartTime } },
attributes: ['id'],
raw: true,
});
for (const statement of statements) {
await this.removeById(statement.id);
}
}
async updateExecutionId(id, executionId) {
const update = {
executionId,
};
await this.sequelizeDb.Statements.update(update, { where: { id } });
return this.findOneById(id);
}
}
module.exports = Statements;