/
pg.pub.ts
299 lines (270 loc) · 11.6 KB
/
pg.pub.ts
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
import {channel, IModulePatcher, PatchFunction} from "diagnostic-channel";
import {EventEmitter} from "events";
// copy the pg.Result type: https://node-postgres.com/api/result
export interface IPostgresResult {
rowCount: number;
command: string;
}
export interface IPostgresData {
query: {
text?: string;
plan?: string;
preparable?: {
text: string;
args: any[];
}
};
database: {
host: string;
port: string;
};
result?: IPostgresResult;
duration: number;
error?: Error;
}
type PostgresCallback = (err: Error, res: IPostgresResult) => any;
function postgres6PatchFunction(originalPg, originalPgPath) {
const originalClientQuery = originalPg.Client.prototype.query;
const diagnosticOriginalFunc = "__diagnosticOriginalFunc";
// wherever the callback is passed, find it, save it, and remove it from the call
// to the the original .query() function
originalPg.Client.prototype.query = function query(config, values, callback) {
const data: IPostgresData = {
query: {},
database: {
host: this.connectionParameters.host,
port: this.connectionParameters.port,
},
result: null,
error: null,
duration: 0,
};
const start = process.hrtime();
let queryResult;
function patchCallback(cb?: PostgresCallback): PostgresCallback {
if (cb && cb[diagnosticOriginalFunc]) {
cb = cb[diagnosticOriginalFunc];
}
const trackingCallback = channel.bindToContext(function(err: Error, res: IPostgresResult): any {
const end = process.hrtime(start);
data.result = res && { rowCount: res.rowCount, command: res.command };
data.error = err;
data.duration = Math.ceil((end[0] * 1e3) + (end[1] / 1e6));
channel.publish("postgres", data);
// emulate weird internal behavior in pg@6
// on success, the callback is called *before* query events are emitted
// on failure, the callback is called *instead of* the query emitting events
// with no events, that means no promises (since the promise is resolved/rejected in an event handler)
// since we are always inserting ourselves as a callback, we have to restore the original
// behavior if the user didn't provide one themselves
if (err) {
if (cb) {
return cb.apply(this, arguments);
} else if (queryResult && queryResult instanceof EventEmitter) {
queryResult.emit("error", err);
}
} else if (cb) {
cb.apply(this, arguments);
}
});
try {
Object.defineProperty(trackingCallback, diagnosticOriginalFunc, { value: cb });
return trackingCallback;
} catch (e) {
// this should never happen, but bailout in case it does
return cb;
}
}
// this function takes too many variations of arguments.
// this patches any provided callback or creates a new callback if one wasn't provided.
// since the callback is always called (if provided) in addition to always having a Promisified
// EventEmitter returned (well, sometimes -- see above), its safe to insert a callback if none was given
try {
if (typeof config === "string") {
if (values instanceof Array) {
data.query.preparable = {
text: config,
args: values,
};
callback = patchCallback(callback);
} else {
data.query.text = config;
// pg v6 will, for some reason, accept both
// client.query("...", undefined, () => {...})
// **and**
// client.query("...", () => {...});
// Internally, precedence is given to the callback argument
if (callback) {
callback = patchCallback(callback);
} else {
values = patchCallback(values);
}
}
} else {
if (typeof config.name === "string") {
data.query.plan = config.name;
} else if (config.values instanceof Array) {
data.query.preparable = {
text: config.text,
args: config.values,
};
} else {
data.query.text = config.text;
}
if (callback) {
callback = patchCallback(callback);
} else if (values) {
values = patchCallback(values);
} else {
config.callback = patchCallback(config.callback);
}
}
} catch (e) {
// if our logic here throws, bail out and just let pg do its thing
return originalClientQuery.apply(this, arguments);
}
arguments[0] = config;
arguments[1] = values;
arguments[2] = callback;
arguments.length = (arguments.length > 3) ? arguments.length : 3;
queryResult = originalClientQuery.apply(this, arguments);
return queryResult;
};
return originalPg;
}
function postgres7PatchFunction(originalPg, originalPgPath) {
const originalClientQuery = originalPg.Client.prototype.query;
const diagnosticOriginalFunc = "__diagnosticOriginalFunc";
// wherever the callback is passed, find it, save it, and remove it from the call
// to the the original .query() function
originalPg.Client.prototype.query = function query(config, values, callback) {
let callbackProvided: boolean = !!callback; // Starting in pg@7.x+, Promise is returned only if !callbackProvided
const data: IPostgresData = {
query: {},
database: {
host: this.connectionParameters.host,
port: this.connectionParameters.port,
},
result: null,
error: null,
duration: 0,
};
const start = process.hrtime();
let queryResult;
function patchCallback(cb?: PostgresCallback): PostgresCallback {
if (cb && cb[diagnosticOriginalFunc]) {
cb = cb[diagnosticOriginalFunc];
}
const trackingCallback = channel.bindToContext(function(err: Error, res: IPostgresResult): any {
const end = process.hrtime(start);
data.result = res && { rowCount: res.rowCount, command: res.command };
data.error = err;
data.duration = Math.ceil((end[0] * 1e3) + (end[1] / 1e6));
channel.publish("postgres", data);
if (err) {
if (cb) {
return cb.apply(this, arguments);
} else if (queryResult && queryResult instanceof EventEmitter) {
queryResult.emit("error", err);
}
} else if (cb) {
cb.apply(this, arguments);
}
});
try {
Object.defineProperty(trackingCallback, diagnosticOriginalFunc, { value: cb });
return trackingCallback;
} catch (e) {
// this should never happen, but bailout in case it does
return cb;
}
}
// Only try to wrap the callback if it is a function. We want to keep the same
// behavior of returning a promise only if no callback is provided. Wrapping
// a nonfunction makes it a function and pg will interpret it as a callback
try {
if (typeof config === "string") {
if (values instanceof Array) {
data.query.preparable = {
text: config,
args: values,
};
callbackProvided = typeof callback === "function";
callback = callback ? patchCallback(callback) : callback;
} else {
data.query.text = config;
if (callback) {
callbackProvided = typeof callback === "function";
callback = callbackProvided ? patchCallback(callback) : callback;
} else {
callbackProvided = typeof values === "function";
values = callbackProvided ? patchCallback(values) : values;
}
}
} else {
if (typeof config.name === "string") {
data.query.plan = config.name;
} else if (config.values instanceof Array) {
data.query.preparable = {
text: config.text,
args: config.values,
};
} else {
data.query.text = config.text;
}
if (callback) {
callbackProvided = typeof callback === "function";
callback = patchCallback(callback);
} else if (values) {
callbackProvided = typeof values === "function";
values = callbackProvided ? patchCallback(values) : values;
} else {
callbackProvided = typeof config.callback === "function";
config.callback = callbackProvided ? patchCallback(config.callback) : config.callback;
}
}
} catch (e) {
// if our logic here throws, bail out and just let pg do its thing
return originalClientQuery.apply(this, arguments);
}
arguments[0] = config;
arguments[1] = values;
arguments[2] = callback;
arguments.length = (arguments.length > 3) ? arguments.length : 3;
queryResult = originalClientQuery.apply(this, arguments);
if (!callbackProvided) {
// no callback, so create a pass along promise
return queryResult
// pass resolved promise after publishing the event
.then((result) => {
patchCallback()(undefined, result);
return new this._Promise((resolve, reject) => {
resolve(result);
});
})
// pass along rejected promise after publishing the error
.catch((error) => {
patchCallback()(error, undefined);
return new this._Promise((resolve, reject) => {
reject(error);
});
});
}
return queryResult;
};
return originalPg;
}
export const postgres6: IModulePatcher = {
versionSpecifier: "6.*",
patch: postgres6PatchFunction,
};
export const postgres7: IModulePatcher = {
versionSpecifier: "7.*",
patch: postgres7PatchFunction,
};
export function enable() {
channel.registerMonkeyPatch("pg", postgres6);
channel.registerMonkeyPatch("pg", postgres7);
}