sql

package
v1.62.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2024 License: Apache-2.0, BSD-3-Clause, Apache-2.0 Imports: 22 Imported by: 107

Documentation

Overview

Package sql provides functions to trace the database/sql package (https://golang.org/pkg/database/sql). It will automatically augment operations such as connections, statements and transactions with tracing.

We start by telling the package which driver we will be using. For example, if we are using "github.com/lib/pq", we would do as follows:

sqltrace.Register("pq", &pq.Driver{})
db, err := sqltrace.Open("pq", "postgres://pqgotest:password@localhost...")

The rest of our application would continue as usual, but with tracing enabled.

Example
package main

import (
	"log"

	sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"

	"github.com/lib/pq"
)

func main() {
	// The first step is to register the driver that we will be using.
	sqltrace.Register("postgres", &pq.Driver{})

	// Followed by a call to Open.
	db, err := sqltrace.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}

	// Then, we continue using the database/sql package as we normally would, with tracing.
	rows, err := db.Query("SELECT name FROM users WHERE age=?", 27)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
}
Output:

Example (Context)
package main

import (
	"context"
	"log"

	sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"

	"github.com/go-sql-driver/mysql"
)

func main() {
	// Register the driver that we will be using (in this case mysql) under a custom service name.
	sqltrace.Register("mysql", &mysql.MySQLDriver{}, sqltrace.WithServiceName("my-db"))

	// Open a connection to the DB using the driver we've just registered with tracing.
	db, err := sqltrace.Open("mysql", "user:password@/dbname")
	if err != nil {
		log.Fatal(err)
	}

	// Create a root span, giving name, server and resource.
	span, ctx := tracer.StartSpanFromContext(context.Background(), "my-query",
		tracer.SpanType(ext.SpanTypeSQL),
		tracer.ServiceName("my-db"),
		tracer.ResourceName("initial-access"),
	)

	// Subsequent spans inherit their parent from context.
	rows, err := db.QueryContext(ctx, "SELECT * FROM city LIMIT 5")
	if err != nil {
		log.Fatal(err)
	}
	rows.Close()
	span.Finish(tracer.WithError(err))
}
Output:

Example (DbStats)
package main

import (
	"log"

	sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"

	"github.com/lib/pq"
)

func main() {
	sqltrace.Register("postgres", &pq.Driver{})
	db, err := sqltrace.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=disable")

	if err != nil {
		log.Fatal(err)
	}

	// Tracing is now enabled. Continue to use the database/sql package as usual
	rows, err := db.Query("SELECT name FROM users WHERE age=?", 27)
	if err != nil {
		log.Fatal(err)
	}
	rows.Close()
}
Output:

Example (DbmPropagation)
package main

import (
	"log"

	sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"

	"github.com/lib/pq"
)

func main() {
	// The first step is to set the dbm propagation mode when registering the driver. Note that this can also
	// be done on sqltrace.Open for more granular control over the feature.
	sqltrace.Register("postgres", &pq.Driver{}, sqltrace.WithDBMPropagation(tracer.DBMPropagationModeFull))

	// Followed by a call to Open.
	db, err := sqltrace.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}

	// Then, we continue using the database/sql package as we normally would, with tracing.
	rows, err := db.Query("SELECT name FROM users WHERE age=?", 27)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
}
Output:

Example (Sqlite)
package main

import (
	"context"
	"log"

	sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"

	sqlite "github.com/mattn/go-sqlite3"
)

func main() {
	// Register the driver that we will be using (in this case Sqlite) under a custom service name.
	sqltrace.Register("sqlite", &sqlite.SQLiteDriver{}, sqltrace.WithServiceName("sqlite-example"))

	// Open a connection to the DB using the driver we've just registered with tracing.
	db, err := sqltrace.Open("sqlite", "./test.db")
	if err != nil {
		log.Fatal(err)
	}

	// Create a root span, giving name, server and resource.
	span, ctx := tracer.StartSpanFromContext(context.Background(), "my-query",
		tracer.SpanType("example"),
		tracer.ServiceName("sqlite-example"),
		tracer.ResourceName("initial-access"),
	)

	// Subsequent spans inherit their parent from context.
	rows, err := db.QueryContext(ctx, "SELECT * FROM city LIMIT 5")
	if err != nil {
		log.Fatal(err)
	}
	rows.Close()
	span.Finish(tracer.WithError(err))
}
Output:

Index

Examples

Constants

View Source
const (
	// QueryTypeConnect is used for Connect traces.
	QueryTypeConnect QueryType = "Connect"
	// QueryTypeQuery is used for Query traces.
	QueryTypeQuery = "Query"
	// QueryTypePing is used for Ping traces.
	QueryTypePing = "Ping"
	// QueryTypePrepare is used for Prepare traces.
	QueryTypePrepare = "Prepare"
	// QueryTypeExec is used for Exec traces.
	QueryTypeExec = "Exec"
	// QueryTypeBegin is used for Begin traces.
	QueryTypeBegin = "Begin"
	// QueryTypeClose is used for Close traces.
	QueryTypeClose = "Close"
	// QueryTypeCommit is used for Commit traces.
	QueryTypeCommit = "Commit"
	// QueryTypeRollback is used for Rollback traces.
	QueryTypeRollback = "Rollback"
)
View Source
const (
	MaxOpenConnections = tracerPrefix + "sql.db.connections.max_open"
	OpenConnections    = tracerPrefix + "sql.db.connections.open"
	InUse              = tracerPrefix + "sql.db.connections.in_use"
	Idle               = tracerPrefix + "sql.db.connections.idle"
	WaitCount          = tracerPrefix + "sql.db.connections.waiting"
	WaitDuration       = tracerPrefix + "sql.db.connections.wait_duration"
	MaxIdleClosed      = tracerPrefix + "sql.db.connections.closed.max_idle_conns"
	MaxIdleTimeClosed  = tracerPrefix + "sql.db.connections.closed.max_idle_time"
	MaxLifetimeClosed  = tracerPrefix + "sql.db.connections.closed.max_lifetime"
)

ref: https://pkg.go.dev/database/sql#DBStats

Variables

This section is empty.

Functions

func Open

func Open(driverName, dataSourceName string, opts ...Option) (*sql.DB, error)

Open returns connection to a DB using the traced version of the given driver. The driver may first be registered using Register. If this did not occur, Open will determine the driver by opening a DB connection and retrieving the driver using (*sql.DB).Driver, before closing it and opening a new, traced connection.

func OpenDB added in v1.16.0

func OpenDB(c driver.Connector, opts ...Option) *sql.DB

OpenDB returns connection to a DB using the traced version of the given driver. The driver may first be registered using Register. If this did not occur, OpenDB will determine the driver name based on its type.

func Register

func Register(driverName string, driver driver.Driver, opts ...RegisterOption)

Register tells the sql integration package about the driver that we will be tracing. If used, it must be called before Open. It uses the driverName suffixed with ".db" as the default service name.

func WithSpanTags added in v1.17.0

func WithSpanTags(ctx context.Context, tags map[string]string) context.Context

WithSpanTags creates a new context containing the given set of tags. They will be added to any query created with the returned context.

Types

type Option added in v1.16.0

type Option func(*config)

Option represents an option that can be passed to Register, Open or OpenDB.

func WithAnalytics added in v1.11.0

func WithAnalytics(on bool) Option

WithAnalytics enables Trace Analytics for all started spans.

func WithAnalyticsRate added in v1.11.0

func WithAnalyticsRate(rate float64) Option

WithAnalyticsRate sets the sampling rate for Trace Analytics events correlated to started spans.

func WithChildSpansOnly added in v1.35.0

func WithChildSpansOnly() Option

WithChildSpansOnly causes spans to be created only when there is an existing parent span in the Context.

func WithCustomTag added in v1.42.0

func WithCustomTag(key string, value interface{}) Option

WithCustomTag will attach the value to the span tagged by the key

func WithDBMPropagation added in v1.44.0

func WithDBMPropagation(mode tracer.DBMPropagationMode) Option

WithDBMPropagation enables injection of tags as sql comments on traced queries. This includes dynamic values like span id, trace id and the sampled flag which can make queries unique for some cache implementations. Use DBMPropagationModeService if this is a concern.

Note that enabling sql comment propagation results in potentially confidential data (service names) being stored in the databases which can then be accessed by other 3rd parties that have been granted access to the database.

func WithDSN added in v1.16.0

func WithDSN(name string) Option

WithDSN allows the data source name (DSN) to be provided when using OpenDB and a driver.Connector. The value is used to automatically set tags on spans.

func WithErrorCheck added in v1.42.0

func WithErrorCheck(fn func(err error) bool) Option

WithErrorCheck specifies a function fn which determines whether the passed error should be marked as an error. The fn is called whenever a database/sql operation finishes with an error

func WithIgnoreQueryTypes added in v1.50.0

func WithIgnoreQueryTypes(qtypes ...QueryType) Option

WithIgnoreQueryTypes specifies the query types for which spans should not be created.

func WithSQLCommentInjection deprecated added in v1.39.0

func WithSQLCommentInjection(mode tracer.SQLCommentInjectionMode) Option

WithSQLCommentInjection enables injection of tags as sql comments on traced queries. This includes dynamic values like span id, trace id and sampling priority which can make queries unique for some cache implementations.

Deprecated: Use WithDBMPropagation instead.

func WithServiceName

func WithServiceName(name string) Option

WithServiceName sets the given service name when registering a driver, or opening a database connection.

type QueryType added in v1.50.0

type QueryType string

QueryType represents the different available traced db queries.

type RegisterOption

type RegisterOption = Option

RegisterOption has been deprecated in favor of Option.

type TracedConn added in v1.49.0

type TracedConn struct {
	driver.Conn
	// contains filtered or unexported fields
}

TracedConn holds a traced connection with tracing parameters.

func (*TracedConn) BeginTx added in v1.49.0

func (tc *TracedConn) BeginTx(ctx context.Context, opts driver.TxOptions) (tx driver.Tx, err error)

BeginTx starts a transaction.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

func (*TracedConn) CheckNamedValue added in v1.49.0

func (tc *TracedConn) CheckNamedValue(value *driver.NamedValue) error

CheckNamedValue is called before passing arguments to the driver and is called in place of any ColumnConverter. CheckNamedValue must do type validation and conversion as appropriate for the driver.

func (*TracedConn) ExecContext added in v1.49.0

func (tc *TracedConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (r driver.Result, err error)

ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*TracedConn) Ping added in v1.49.0

func (tc *TracedConn) Ping(ctx context.Context) (err error)

Ping verifies the connection to the database is still alive.

func (*TracedConn) PrepareContext added in v1.49.0

func (tc *TracedConn) PrepareContext(ctx context.Context, query string) (stmt driver.Stmt, err error)

PrepareContext creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's Close method when the statement is no longer needed.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*TracedConn) QueryContext added in v1.49.0

func (tc *TracedConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error)

QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*TracedConn) ResetSession added in v1.49.0

func (tc *TracedConn) ResetSession(ctx context.Context) error

ResetSession implements driver.SessionResetter

func (*TracedConn) WrappedConn added in v1.49.0

func (tc *TracedConn) WrappedConn() driver.Conn

WrappedConn returns the wrapped connection object.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL