Skip to content

Commit

Permalink
Add support for pg-cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-pytel committed Feb 28, 2021
1 parent 506ba58 commit de46c0a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 15 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ Library | Plugin Name
| [`axios`](https://github.com/axios/axios) | `axios` |
| [`mysql`](https://github.com/mysqljs/mysql) | `mysql` |
| [`pg`](https://github.com/brianc/node-postgres) | `pg` |
| [`pg-cursor`](https://github.com/brianc/node-postgres) | `pg-cursor` |
| [`mongodb`](https://github.com/mongodb/node-mongodb-native) | `mongodb` |

### Compatible Libraries
Expand Down
51 changes: 36 additions & 15 deletions src/plugins/PgPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ class MySQLPlugin implements SwPlugin {

install(installer: PluginInstaller): void {
const Client = installer.require('pg/lib/client');

let Cursor: any;

try {
Cursor = installer.require('pg-cursor');
} catch {}

const _query = Client.prototype.query;

Client.prototype.query = function(config: any, values: any, callback: any) {
Expand Down Expand Up @@ -76,7 +83,7 @@ class MySQLPlugin implements SwPlugin {

if (typeof values === 'function')
values = wrapCallback(values);
else
else if (_values !== undefined)
_values = values;

if (typeof callback === 'function')
Expand All @@ -95,23 +102,37 @@ class MySQLPlugin implements SwPlugin {

query = _query.call(this, config, values, callback);

if (query && typeof query.then === 'function') { // generic Promise check
query = query.then(
(res: any) => {
span.resync();
span.stop();

return res;
},

(err: any) => {
span.resync();
if (query) {
if (Cursor && query instanceof Cursor) {
query.on('error', (err: any) => {
span.resync(); // this may precede 'end' .resync() but its fine
span.error(err);
span.stop();
});

return Promise.reject(err);
}
);
query.on('end', () => {
span.resync(); // cursor does not .resync() until it is closed because maybe other exit spans will be opened during processing
span.stop();
});

} else if (typeof query.then === 'function') { // generic Promise check
query = query.then(
(res: any) => {
span.resync();
span.stop();

return res;
},

(err: any) => {
span.resync();
span.error(err);
span.stop();

return Promise.reject(err);
}
);
} // else we assume there was a callback
}

} catch (e) {
Expand Down

0 comments on commit de46c0a

Please sign in to comment.