Skip to content
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
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { assertSentryTransaction, TestEnv } from '../../../../utils';

class PgClient {
database?: string = 'test';
user?: string = 'user';
host?: string = 'localhost';
port?: number = 5432;

// https://node-postgres.com/api/client#clientquery
public query(_text: unknown, values: unknown, callback?: () => void) {
if (typeof callback === 'function') {
Expand Down Expand Up @@ -42,20 +47,32 @@ test('should auto-instrument `pg` package.', async () => {
op: 'db',
data: {
'db.system': 'postgresql',
'db.user': 'user',
'db.name': 'test',
'server.address': 'localhost',
'server.port': 5432,
},
},
{
description: 'SELECT * FROM bazz',
op: 'db',
data: {
'db.system': 'postgresql',
'db.user': 'user',
'db.name': 'test',
'server.address': 'localhost',
'server.port': 5432,
},
},
{
description: 'SELECT NOW()',
op: 'db',
data: {
'db.system': 'postgresql',
'db.user': 'user',
'db.name': 'test',
'server.address': 'localhost',
'server.port': 5432,
},
},
],
Expand Down
35 changes: 31 additions & 4 deletions packages/tracing-internal/src/node/integrations/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ interface PgClient {
};
}

interface PgClientThis {
database?: string;
host?: string;
port?: number;
user?: string;
}

interface PgOptions {
usePgNative?: boolean;
}
Expand Down Expand Up @@ -74,15 +81,35 @@ export class Postgres implements LazyLoadedIntegration<PGModule> {
* function (pg.Cursor) => pg.Cursor
*/
fill(Client.prototype, 'query', function (orig: () => void | Promise<unknown>) {
return function (this: unknown, config: unknown, values: unknown, callback: unknown) {
return function (this: PgClientThis, config: unknown, values: unknown, callback: unknown) {
const scope = getCurrentHub().getScope();
const parentSpan = scope?.getSpan();

const data: Record<string, string | number> = {
'db.system': 'postgresql',
};

try {
if (this.database) {
data['db.name'] = this.database;
}
if (this.host) {
data['server.address'] = this.host;
}
if (this.port) {
data['server.port'] = this.port;
}
if (this.user) {
data['db.user'] = this.user;
}
} catch (e) {
// ignore
}

const span = parentSpan?.startChild({
description: typeof config === 'string' ? config : (config as { text: string }).text,
op: 'db',
data: {
'db.system': 'postgresql',
},
data,
});

if (typeof callback === 'function') {
Expand Down