@@ -33,13 +33,26 @@ module.exports = function captureMySQL(mysql) {
3333 return mysql ;
3434} ;
3535
36+ function isPromise ( maybePromise ) {
37+ if ( maybePromise != null && maybePromise . then instanceof Function ) {
38+ // mysql2 has a `Query` class with a `then` method which always throws an error when called.
39+ // We want to avoid calling this, so we need to check for more than just the presence of a `then` method.
40+ // See https://github.com/sidorares/node-mysql2/blob/dbb344e89a1cc8bb457b24e67b07cdb3013fe844/lib/commands/query.js#L38-L44
41+ // Since it's highly unlikely that any Promise implementation would name their class `Query`,
42+ // we can safely use this to determine whether or not this is actually a Promise.
43+ const constructorName = maybePromise . constructor != null ? maybePromise . constructor . name : undefined ;
44+ return constructorName !== 'Query' ;
45+ }
46+ return false ;
47+ }
48+
3649function patchCreateConnection ( mysql ) {
3750 var baseFcn = '__createConnection' ;
3851 mysql [ baseFcn ] = mysql [ 'createConnection' ] ;
3952
4053 mysql [ 'createConnection' ] = function patchedCreateConnection ( ) {
4154 var connection = mysql [ baseFcn ] . apply ( connection , arguments ) ;
42- if ( connection && connection . then instanceof Function ) {
55+ if ( isPromise ( connection ) ) {
4356 connection = connection . then ( ( result ) => {
4457 patchObject ( result . connection ) ;
4558 return result ;
@@ -57,7 +70,7 @@ function patchCreatePool(mysql) {
5770
5871 mysql [ 'createPool' ] = function patchedCreatePool ( ) {
5972 var pool = mysql [ baseFcn ] . apply ( pool , arguments ) ;
60- if ( pool && pool . then instanceof Function ) {
73+ if ( isPromise ( pool ) ) {
6174 pool = pool . then ( ( result ) => {
6275 patchObject ( result . pool ) ;
6376 return result ;
@@ -112,7 +125,7 @@ function patchGetConnection(pool) {
112125 }
113126
114127 var result = pool [ baseFcn ] . apply ( pool , args ) ;
115- if ( result && result . then instanceof Function ) {
128+ if ( isPromise ( result ) ) {
116129 return result . then ( patchObject ) ;
117130 } else {
118131 return result ;
@@ -232,7 +245,7 @@ function captureOperation(name) {
232245 }
233246 } ;
234247
235- if ( command . then instanceof Function ) {
248+ if ( isPromise ( command ) ) {
236249 command . then ( ( ) => {
237250 subsegment . close ( ) ;
238251 } ) ;
0 commit comments