github.com/mier85/go-sensor@v1.30.1-0.20220920111756-9bf41b3bc7e0/example_instrumentation_go1.10_test.go (about)

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