github.com/instana/go-sensor@v1.62.2-0.20240520081010-4919868049e1/example_instrumentation_go1.10_test.go (about)

     1  // (c) Copyright IBM Corp. 2021
     2  // (c) Copyright Instana Inc. 2020
     3  
     4  package instana_test
     5  
     6  import (
     7  	"context"
     8  	"database/sql"
     9  
    10  	instana "github.com/instana/go-sensor"
    11  )
    12  
    13  // This example demonstrates how to instrument an *sql.DB instance created with sql.OpenDB() and driver.Connector
    14  func ExampleWrapSQLConnector() {
    15  	// Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended
    16  	// to use a single instance throughout your application
    17  	sensor := instana.NewSensor("my-http-client")
    18  
    19  	// Instrument the connector. Normally this would be a type provided by the driver library.
    20  	// Here we use a test mock to avoid bringing external dependencies.
    21  	//
    22  	// Note that instana.WrapSQLConnector() requires the connection string to send it later
    23  	// along with database spans.
    24  	connector := instana.WrapSQLConnector(sensor, "driver connection string", &sqlConnector{})
    25  
    26  	// Use wrapped connector to initialize the database client. Note that
    27  	db := sql.OpenDB(connector)
    28  
    29  	// Inject parent span into the context
    30  	span := sensor.Tracer().StartSpan("entry")
    31  	ctx := instana.ContextWithSpan(context.Background(), span)
    32  
    33  	// Query the database, passing the context containing the active span
    34  	db.QueryContext(ctx, "SELECT * FROM users;")
    35  
    36  	// SQL queries that are not expected to return a result set are also supported
    37  	db.ExecContext(ctx, "UPDATE users SET last_seen_at = NOW();")
    38  }