Skip to content

Instantly share code, notes, and snippets.

@Tarliton
Created July 7, 2021 15:24
Show Gist options
  • Save Tarliton/ea9d42b14b0891ed28134a7b99d0e398 to your computer and use it in GitHub Desktop.
Save Tarliton/ea9d42b14b0891ed28134a7b99d0e398 to your computer and use it in GitHub Desktop.
Auto GORM New Relic instrumentation/integration
package main
import (
"context"
"database/sql"
"fmt"
_ "github.com/newrelic/go-agent/v3/integrations/nrmysql"
"github.com/newrelic/go-agent/v3/newrelic"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"os"
"time"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
// Set up a local mysql docker container with:
// docker run -it -p 3306:3306 --net "bridge" -e MYSQL_ALLOW_EMPTY_PASSWORD=true mysql
db, err := sql.Open("nrmysql", "root@/information_schema")
if nil != err {
panic(err)
}
gormdb, err := gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
app, err := newrelic.NewApplication(
newrelic.ConfigAppName("my-nice-app"),
newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")),
newrelic.ConfigDebugLogger(os.Stdout),
newrelic.ConfigDistributedTracerEnabled(true),
newrelic.ConfigEnabled(true),
)
if nil != err {
panic(err)
}
app.WaitForConnection(5 * time.Second)
txn := app.StartTransaction("mysqlQuery")
ctx := newrelic.NewContext(context.Background(), txn)
gormdb = gormdb.WithContext(ctx)
row := gormdb.Raw("SELECT count(*) from tables")
var count int
row.Scan(&count)
fmt.Println("number of tables in information_schema", count)
// Migrate the schema
gormdb.AutoMigrate(&Product{})
// Create
gormdb.Create(&Product{Code: "D42", Price: 100})
// Read
var product Product
gormdb.First(&product, 1) // find product with integer primary key
gormdb.First(&product, "code = ?", "D42") // find product with code D42
// Update - update product's price to 200
gormdb.Model(&product).Update("Price", 200)
// Update - update multiple fields
gormdb.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
gormdb.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
// Delete - delete product
gormdb.Delete(&product, 1)
txn.End()
app.Shutdown(5 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment