Skip to content
11 changes: 10 additions & 1 deletion packages/instrumentation-pg/src/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,12 +360,21 @@ export class PgInstrumentation extends InstrumentationBase<PgInstrumentationConf

const instrumentationConfig = plugin.getConfig();

// Normalize the query configuration so that prepared statements with a separate
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the suggestion on the issue itself, of just updating the line 342 to
values: (arg0 as any).values ?? (Array.isArray(args[1]) ? args[1] : undefined),, this way it avoids doing some repetition on checks, which is what you're doing here.

Would you mind making that solutions instead and checking if the tests will work as expected?

// values array (query(config, values)) are correctly merged into one object.
const normalizedQueryConfig =
firstArgIsQueryObjectWithText &&
Array.isArray(args[1]) &&
queryConfig?.text
? { ...queryConfig, values: args[1] }
: queryConfig;

const span = utils.handleConfigQuery.call(
this,
plugin.tracer,
instrumentationConfig,
plugin._semconvStability,
queryConfig
normalizedQueryConfig
);

// Modify query text w/ a tracing comment before invoking original for
Expand Down
53 changes: 53 additions & 0 deletions packages/instrumentation-pg/test/pg.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,59 @@ describe('pg', () => {
});
});
});

it('should record query and values for prepared statements', done => {
const queryConfig = {
name: 'get_pg_tables',
text: 'SELECT * FROM pg_tables WHERE schemaname = $1',
};
const values = ['public'];

const expectedAttributes = {
...DEFAULT_ATTRIBUTES,
[ATTR_DB_STATEMENT]: queryConfig.text,
[AttributeNames.PG_PLAN]: queryConfig.name,
[AttributeNames.PG_VALUES]: values,
};

const events: TimedEvent[] = [];
const span = tracer.startSpan('prepared statement span');

context.with(trace.setSpan(context.active(), span), () => {
const resNoPromise = (client.query as any)(
queryConfig,
values,
(err: Error | null, res: any) => {
assert.strictEqual(err, null);
assert.ok(res);
assert.ok(Array.isArray(res.rows));

const spans = memoryExporter.getFinishedSpans();
const pgSpan = spans[spans.length - 1];
const recordedAttributes = pgSpan.attributes;

assert.strictEqual(
recordedAttributes[ATTR_DB_STATEMENT],
queryConfig.text
);

assert.ok(
!recordedAttributes[ATTR_DB_STATEMENT].includes(values[0]),
'Query text should NOT contain parameter value'
);

assert.deepStrictEqual(
recordedAttributes[AttributeNames.PG_VALUES],
['public']
);

runCallbackTest(span, expectedAttributes, events);
done();
}
);
assert.strictEqual(resNoPromise, undefined);
});
});
});

describe('when specifying a requestHook configuration', () => {
Expand Down