Skip to content

feat(tracing): Add pg-native support to Postgres tracing integration. #3894

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions packages/tracing/src/integrations/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ interface PgClient {
};
}

interface PgOptions {
usePgNative?: boolean;
}

/** Tracing integration for node-postgres package */
export class Postgres implements Integration {
/**
Expand All @@ -20,25 +24,38 @@ export class Postgres implements Integration {
*/
public name: string = Postgres.id;

private _usePgNative: boolean;

public constructor(options: PgOptions = {}) {
this._usePgNative = !!options.usePgNative;
}

/**
* @inheritDoc
*/
public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
const pkg = loadModule<{ Client: PgClient }>('pg');
const pkg = loadModule<{ Client: PgClient; native: { Client: PgClient } }>('pg');

if (!pkg) {
logger.error('Postgres Integration was unable to require `pg` package.');
return;
}

if (this._usePgNative && !pkg.native?.Client) {
logger.error(`Postgres Integration was unable to access 'pg-native' bindings.`);
return;
}

const { Client } = this._usePgNative ? pkg.native : pkg;

/**
* function (query, callback) => void
* function (query, params, callback) => void
* function (query) => Promise
* function (query, params) => Promise
* function (pg.Cursor) => pg.Cursor
*/
fill(pkg.Client.prototype, 'query', function(orig: () => void | Promise<unknown>) {
fill(Client.prototype, 'query', function(orig: () => void | Promise<unknown>) {
return function(this: unknown, config: unknown, values: unknown, callback: unknown) {
const scope = getCurrentHub().getScope();
const parentSpan = scope?.getSpan();
Expand Down
97 changes: 97 additions & 0 deletions packages/tracing/test/integrations/postgres.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/* eslint-disable @typescript-eslint/unbound-method */
import { Hub, Scope } from '@sentry/hub';

import { Postgres } from '../../src/integrations/postgres';
import { Span } from '../../src/span';

class PgClient {
// https://node-postgres.com/api/client#clientquery
public query(_text: unknown, values: unknown, callback?: () => void) {
if (typeof callback === 'function') {
callback();
return;
}

if (typeof values === 'function') {
values();
return;
}

return Promise.resolve();
}
}

// mock for 'pg' / 'pg-native' package
jest.mock('@sentry/utils', () => {
const actual = jest.requireActual('@sentry/utils');
return {
...actual,
loadModule() {
return {
Client: PgClient,
native: {
Client: PgClient,
},
};
},
};
});

describe('setupOnce', () => {
['pg', 'pg-native'].forEach(pgApi => {
const Client: PgClient = new PgClient();
let scope = new Scope();
let parentSpan: Span;
let childSpan: Span;

beforeAll(() => {
(pgApi === 'pg' ? new Postgres() : new Postgres({ usePgNative: true })).setupOnce(
() => undefined,
() => new Hub(undefined, scope),
);
});

beforeEach(() => {
scope = new Scope();
parentSpan = new Span();
childSpan = parentSpan.startChild();
jest.spyOn(scope, 'getSpan').mockReturnValueOnce(parentSpan);
jest.spyOn(parentSpan, 'startChild').mockReturnValueOnce(childSpan);
jest.spyOn(childSpan, 'finish');
});

it(`should wrap ${pgApi}'s query method accepting callback as the last argument`, done => {
Client.query('SELECT NOW()', {}, function() {
expect(scope.getSpan).toBeCalled();
expect(parentSpan.startChild).toBeCalledWith({
description: 'SELECT NOW()',
op: 'db',
});
expect(childSpan.finish).toBeCalled();
done();
}) as void;
});

it(`should wrap ${pgApi}'s query method accepting callback as the second argument`, done => {
Client.query('SELECT NOW()', function() {
expect(scope.getSpan).toBeCalled();
expect(parentSpan.startChild).toBeCalledWith({
description: 'SELECT NOW()',
op: 'db',
});
expect(childSpan.finish).toBeCalled();
done();
}) as void;
});

it(`should wrap ${pgApi}'s query method accepting no callback as the last argument but returning promise`, async () => {
await Client.query('SELECT NOW()', null);
expect(scope.getSpan).toBeCalled();
expect(parentSpan.startChild).toBeCalledWith({
description: 'SELECT NOW()',
op: 'db',
});
expect(childSpan.finish).toBeCalled();
});
});
});