Skip to content

Commit 25e53d6

Browse files
authored
refactor(instrumentation-mysql2): improve performance of getSpanName using substring (open-telemetry#2470)
1 parent d056d21 commit 25e53d6

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

plugins/node/opentelemetry-instrumentation-mysql/src/utils.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,13 @@ export function getDbValues(
112112
* @returns SQL statement without variable arguments or SQL verb
113113
*/
114114
export function getSpanName(query: string | Query | QueryOptions): string {
115-
if (typeof query === 'object') {
116-
return query.sql;
115+
const rawQuery = typeof query === 'object' ? query.sql : query;
116+
// Extract the SQL verb
117+
const firstSpace = rawQuery?.indexOf(' ');
118+
if (typeof firstSpace === 'number' && firstSpace !== -1) {
119+
return rawQuery?.substring(0, firstSpace);
117120
}
118-
return query.split(' ')[0];
121+
return rawQuery;
119122
}
120123

121124
export function arrayStringifyHelper(arr: Array<unknown> | undefined): string {

plugins/node/opentelemetry-instrumentation-mysql/test/index.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ describe('[email protected]', () => {
153153

154154
query.on('end', () => {
155155
const spans = memoryExporter.getFinishedSpans();
156-
assert.strictEqual(spans[0].name, sql);
156+
assert.strictEqual(spans[0].name, 'SELECT');
157157
done();
158158
});
159159
});

plugins/node/opentelemetry-instrumentation-mysql2/src/utils.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,11 @@ export function getDbStatement(
131131
export function getSpanName(query: string | Query | QueryOptions): string {
132132
const rawQuery = typeof query === 'object' ? query.sql : query;
133133
// Extract the SQL verb
134-
return rawQuery?.split(' ')?.[0];
134+
const firstSpace = rawQuery?.indexOf(' ');
135+
if (typeof firstSpace === 'number' && firstSpace !== -1) {
136+
return rawQuery?.substring(0, firstSpace);
137+
}
138+
return rawQuery;
135139
}
136140

137141
export const once = (fn: Function) => {

0 commit comments

Comments
 (0)