github.com/instana/go-sensor@v1.62.2-0.20240520081010-4919868049e1/instrumentation_sql_go1.10.go (about) 1 // (c) Copyright IBM Corp. 2021 2 // (c) Copyright Instana Inc. 2020 3 4 package instana 5 6 import ( 7 "context" 8 "database/sql/driver" 9 ) 10 11 type wrappedSQLConnector struct { 12 driver.Connector 13 14 connDetails DbConnDetails 15 sensor TracerLogger 16 } 17 18 // WrapSQLConnector wraps an existing sql.Connector and instruments the DB calls made using it 19 func WrapSQLConnector(sensor TracerLogger, name string, connector driver.Connector) *wrappedSQLConnector { 20 if c, ok := connector.(*wrappedSQLConnector); ok { 21 return c 22 } 23 24 return &wrappedSQLConnector{ 25 Connector: connector, 26 connDetails: ParseDBConnDetails(name), 27 sensor: sensor, 28 } 29 } 30 31 func (c *wrappedSQLConnector) Connect(ctx context.Context) (driver.Conn, error) { 32 conn, err := c.Connector.Connect(ctx) 33 if err != nil { 34 return conn, err 35 } 36 37 if connAlreadyWrapped(conn) { 38 return conn, nil 39 } 40 41 w := wrapConn(c.connDetails, conn, c.sensor) 42 43 return w, nil 44 } 45 46 func (c *wrappedSQLConnector) Driver() driver.Driver { 47 if drv, ok := c.Connector.Driver().(*wrappedSQLDriver); ok { 48 return drv 49 } 50 51 return &wrappedSQLDriver{ 52 Driver: c.Connector.Driver(), 53 sensor: c.sensor, 54 } 55 } 56 57 func (drv *wrappedSQLDriver) OpenConnector(name string) (driver.Connector, error) { 58 var connector driver.Connector = dsnConnector{dsn: name, driver: drv} 59 60 if d, ok := drv.Driver.(driver.DriverContext); ok { 61 var err error 62 63 connector, err = d.OpenConnector(name) 64 if err != nil { 65 return connector, err 66 } 67 } 68 69 if connector, ok := connector.(*wrappedSQLConnector); ok { 70 return connector, nil 71 } 72 73 wc := WrapSQLConnector(drv.sensor, name, connector) 74 75 return wc, nil 76 }