Documentation ¶
Overview ¶
An application that illustrates how to instrument jmoiron/sqlx with DatastoreSegments
To run this example, be sure the environment varible NEW_RELIC_LICENSE_KEY is set to your license key. Postgres must be running on the default port 5432 and have a user "foo" and a database "bar".
Adding instrumentation for the SQLx package is easy. It means you can make database calls without having to manually create DatastoreSegments. Setup can be done in two steps:
Set up your driver ¶
If you are using one of our currently supported database drivers (see https://docs.oldfritter.com/docs/agents/go-agent/get-started/go-agent-compatibility-requirements#frameworks), follow the instructions on installing the driver.
As an example, for the `lib/pq` driver, you will use the oldfritter integration's driver in place of the postgres driver. If your code is using sqlx.Open with `lib/pq` like this:
import ( "github.com/jmoiron/sqlx" _ "github.com/lib/pq" ) func main() { db, err := sqlx.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full") }
Then change the side-effect import to the integration package, and open "nrpostgres" instead:
import ( "github.com/jmoiron/sqlx" _ "github.com/oldfritter/go-agent/_integrations/nrpq" ) func main() { db, err := sqlx.Open("nrpostgres", "user=pqgotest dbname=pqgotest sslmode=verify-full") }
If you are not using one of the supported database drivers, use the `InstrumentSQLDriver` (https://godoc.org/github.com/oldfritter/go-agent#InstrumentSQLDriver) API. See https://github.com/oldfritter/go-agent/blob/master/_integrations/nrmysql/nrmysql.go for a full example.
Add context to your database calls ¶
Next, you must provide a context containing a oldfritter.Transaction to all methods on sqlx.DB, sqlx.NamedStmt, sqlx.Stmt, and sqlx.Tx that make a database call. For example, instead of the following:
err := db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason")
Do this:
ctx := oldfritter.NewContext(context.Background(), txn) err := db.GetContext(ctx, &jason, "SELECT * FROM person WHERE first_name=$1", "Jason")