Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: database/sql integration #893

Open
wants to merge 27 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
e544314
feat: initial sentrysql implementation
aldy505 Oct 18, 2024
92e3a6b
chore: resolve a few lint issues
aldy505 Oct 18, 2024
aa4acb2
chore: another attempt at resolving lint issues
aldy505 Oct 18, 2024
a6b5de8
chore: wrong method name
aldy505 Oct 18, 2024
c6ebbda
chore: another attempt of fixing lint issues
aldy505 Oct 18, 2024
63413f3
feat: implement missing bits from driver interfaces
aldy505 Oct 19, 2024
b77e392
chore: missing a period on comment
aldy505 Oct 19, 2024
9b59328
test: replace ramsql with in-memory sqlite
aldy505 Oct 19, 2024
7ecd868
test: common queries
aldy505 Oct 19, 2024
19c97df
chore: avoid cyclo errors
aldy505 Oct 19, 2024
d9073aa
test: no parent span
aldy505 Oct 19, 2024
05d699b
test: db.Driver
aldy505 Oct 19, 2024
0fc642e
chore: trailing newline
aldy505 Oct 19, 2024
7b5fbb5
test: using mysql server for connector
aldy505 Oct 19, 2024
93198bd
test: remove mysql server, stay on go1.18
aldy505 Oct 19, 2024
ab1d3bf
chore: another go1.18 rollback
aldy505 Oct 19, 2024
18d5f66
test: NewSentrySQLConnector
aldy505 Oct 26, 2024
3e31bb5
chore(example): sql integration example
aldy505 Oct 26, 2024
fbd4dfc
chore: don't lint fakedb
aldy505 Oct 26, 2024
1023392
test: backport to go1.18
aldy505 Oct 26, 2024
2dc58a5
test: backport to go1.18
aldy505 Oct 26, 2024
c5fa49d
chore: lint
aldy505 Oct 26, 2024
a6e4fd4
Merge remote-tracking branch 'origin/master' into feat/sentrysql
aldy505 Nov 2, 2024
1f38b9f
test(sentrysql): test against legacy driver
aldy505 Nov 2, 2024
f173533
chore(sentrysql): remove unvisited context check
aldy505 Nov 2, 2024
bcc99fc
chore: lint
aldy505 Nov 2, 2024
38ba84c
chore(sentrysql): make sure we implement required interfaces
aldy505 Nov 6, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
197 changes: 197 additions & 0 deletions _examples/sql/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
package main

import (
"context"
"database/sql"
"errors"
"fmt"
"time"

"github.com/getsentry/sentry-go"
"github.com/getsentry/sentry-go/sentrysql"
"github.com/lib/pq"
)

func init() {
// Registering a custom database driver that's wrapped by sentrysql.
// Later, we can call `sql.Open("sentrysql-postgres", databaseDSN)` to use it.
sql.Register("sentrysql-postgres", sentrysql.NewSentrySQL(&pq.Driver{}, sentrysql.WithDatabaseSystem(sentrysql.PostgreSQL), sentrysql.WithDatabaseName("postgres"), sentrysql.WithServerAddress("write.postgres.internal", "5432")))
}

func main() {
err := sentry.Init(sentry.ClientOptions{
// Either set your DSN here or set the SENTRY_DSN environment variable.
Dsn: "",
// Enable printing of SDK debug messages.
// Useful when getting started or trying to figure something out.
Debug: true,
// EnableTracing must be set to true if you want the SQL queries to be traced.
EnableTracing: true,
TracesSampleRate: 1.0,
})
if err != nil {
fmt.Printf("failed to initialize sentry: %s\n", err.Error())
return
}

// We are going to emulate a scenario where an application requires a read database and a write database.
// This is also to show how to use each `sentrysql.NewSentrySQLConnector` and `sentrysql.NewSentrySQL`.

// Create a database connection for read database.
connector, err := pq.NewConnector("postgres://postgres:[email protected]:5432/postgres")
if err != nil {
fmt.Printf("failed to create a postgres connector: %s\n", err.Error())
return
}

sentryWrappedConnector := sentrysql.NewSentrySQLConnector(
connector,
sentrysql.WithDatabaseSystem(sentrysql.PostgreSQL), // required if you want to see the queries on the Queries Insights page
sentrysql.WithDatabaseName("postgres"),
sentrysql.WithServerAddress("read.postgres.internal", "5432"),
)

readDatabase := sql.OpenDB(sentryWrappedConnector)
defer func() {
err := readDatabase.Close()
if err != nil {
sentry.CaptureException(err)
}
}()

// Create a database connection for write database.
writeDatabase, err := sql.Open("sentrysql-postgres", "postgres://postgres:[email protected]:5432/postgres")
if err != nil {
fmt.Printf("failed to open write postgres database: %s\n", err.Error())
return
}
defer func() {
err := writeDatabase.Close()
if err != nil {
sentry.CaptureException(err)
}
}()

ctx, cancel := context.WithTimeout(
sentry.SetHubOnContext(context.Background(), sentry.CurrentHub().Clone()),
time.Minute,
)
defer cancel()

err = ScaffoldDatabase(ctx, writeDatabase)
if err != nil {
fmt.Printf("failed to scaffold database: %s\n", err.Error())
return
}

users, err := GetAllUsers(ctx, readDatabase)
if err != nil {
fmt.Printf("failed to get users: %s\n", err.Error())
return
}

for _, user := range users {
fmt.Printf("User: %+v\n", user)
}
}

// ScaffoldDatabase prepares the database to have the users table.
func ScaffoldDatabase(ctx context.Context, db *sql.DB) error {
// A parent span is required to have the queries to be traced.
// Make sure to override the `context.Context` with the parent span's context.
span := sentry.StartSpan(ctx, "ScaffoldDatabase")
ctx = span.Context()
defer span.Finish()

conn, err := db.Conn(ctx)
if err != nil {
return fmt.Errorf("acquiring connection from pool: %w", err)
}
defer func() {
err := conn.Close()
if err != nil && !errors.Is(err, sql.ErrConnDone) {
if hub := sentry.GetHubFromContext(ctx); hub != nil {
hub.CaptureException(err)
}
}
}()

tx, err := conn.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable, ReadOnly: false})
if err != nil {
return fmt.Errorf("beginning transaction: %w", err)
}
defer func() {
err := tx.Rollback()
if err != nil && !errors.Is(err, sql.ErrTxDone) {
if hub := sentry.GetHubFromContext(ctx); hub != nil {
hub.CaptureException(err)
}
}
}()

_, err = tx.ExecContext(ctx, "CREATE TABLE users (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), active BOOLEAN)")
if err != nil {
return fmt.Errorf("creating users table: %w", err)
}

err = tx.Commit()
if err != nil {
return fmt.Errorf("committing transaction: %w", err)
}

return nil
}

// User represents a user in the database.
type User struct {
ID int
Name string
Email string
}

// GetAllUsers returns all the users from the database.
func GetAllUsers(ctx context.Context, db *sql.DB) ([]User, error) {
// A parent span is required to have the queries to be traced.
// Make sure to override the `context.Context` with the parent span's context.
span := sentry.StartSpan(ctx, "GetAllUsers")
ctx = span.Context()
defer span.Finish()

conn, err := db.Conn(ctx)
if err != nil {
return nil, fmt.Errorf("acquiring connection from pool: %w", err)
}
defer func() {
err := conn.Close()
if err != nil && !errors.Is(err, sql.ErrConnDone) {
if hub := sentry.GetHubFromContext(ctx); hub != nil {
hub.CaptureException(err)
}
}
}()

rows, err := conn.QueryContext(ctx, "SELECT id, name, email FROM users WHERE active = $1", true)
if err != nil {
return nil, fmt.Errorf("querying users: %w", err)
}
defer func() {
err := rows.Close()
if err != nil {
if hub := sentry.GetHubFromContext(ctx); hub != nil {
hub.CaptureException(err)
}
}
}()

var users []User
for rows.Next() {
var user User
err := rows.Scan(&user.ID, &user.Name, &user.Email)
if err != nil {
return nil, fmt.Errorf("scanning user: %w", err)
}
users = append(users, user)
}

return users, nil
}
10 changes: 10 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ go 1.18

require (
github.com/gin-gonic/gin v1.8.1
github.com/glebarez/go-sqlite v1.21.1
github.com/go-errors/errors v1.4.2
github.com/go-sql-driver/mysql v1.8.1
github.com/gofiber/fiber/v2 v2.52.2
github.com/google/go-cmp v0.5.9
github.com/kataras/iris/v12 v12.2.0
github.com/labstack/echo/v4 v4.10.0
github.com/lib/pq v1.10.9
github.com/pingcap/errors v0.11.4
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.9.0
Expand All @@ -20,6 +23,7 @@ require (
)

require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/BurntSushi/toml v1.2.1 // indirect
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 // indirect
github.com/CloudyKit/jet/v6 v6.2.0 // indirect
Expand All @@ -29,6 +33,7 @@ require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/flosch/pongo2/v4 v4.0.2 // indirect
Expand Down Expand Up @@ -67,6 +72,7 @@ require (
github.com/nxadm/tail v1.4.11 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sanity-io/litter v1.5.5 // indirect
Expand Down Expand Up @@ -94,5 +100,9 @@ require (
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.22.3 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/sqlite v1.21.1 // indirect
moul.io/http2curl/v2 v2.3.0 // indirect
)
22 changes: 22 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak=
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 h1:sR+/8Yb4slttB4vD+b9btVEnWgL3Q00OBTzVT8B9C0c=
Expand All @@ -24,6 +26,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/djherbis/atime v1.1.0/go.mod h1:28OF6Y8s3NQWwacXc5eZTsEsiMzp7LF8MbXE+XJPdBE=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385 h1:clC1lXBpe2kTj2VHdaIu9ajZQe4kcEY9j0NsnDDBZ3o=
github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
Expand All @@ -37,6 +41,8 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.8.1 h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8=
github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk=
github.com/glebarez/go-sqlite v1.21.1 h1:7MZyUPh2XTrHS7xNEHQbrhfMZuPSzhkm2A1qgg0y5NY=
github.com/glebarez/go-sqlite v1.21.1/go.mod h1:ISs8MF6yk5cL4n/43rSOmVMGJJjHYr7L2MbZZ5Q4E2E=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
Expand All @@ -47,6 +53,8 @@ github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/j
github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=
github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=
github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/gofiber/fiber/v2 v2.52.2 h1:b0rYH6b06Df+4NyrbdptQL8ifuxw/Tf2DgfkZkDaxEo=
Expand All @@ -59,6 +67,7 @@ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
Expand Down Expand Up @@ -103,6 +112,8 @@ github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8
github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mailgun/raymond/v2 v2.0.48 h1:5dmlB680ZkFG2RN/0lvTAghrSxIESeu9/2aeDqACtjw=
github.com/mailgun/raymond/v2 v2.0.48/go.mod h1:lsgvL50kgt1ylcFJYZiULi5fjPBkkhNfj4KA0W54Z18=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
Expand Down Expand Up @@ -142,6 +153,9 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
Expand Down Expand Up @@ -289,5 +303,13 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.22.3 h1:D/g6O5ftAfavceqlLOFwaZuA5KYafKwmr30A6iSqoyY=
modernc.org/libc v1.22.3/go.mod h1:MQrloYP209xa2zHome2a8HLiLm6k0UT8CoHpV74tOFw=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.21.1 h1:GyDFqNnESLOhwwDRaHGdp2jKLDzpyT/rNLglX3ZkMSU=
modernc.org/sqlite v1.21.1/go.mod h1:XwQ0wZPIh1iKb5mkvCJ3szzbhk+tykC8ZWqTRTgYRwI=
moul.io/http2curl/v2 v2.3.0 h1:9r3JfDzWPcbIklMOs2TnIFzDYvfAZvjeavG6EzP7jYs=
moul.io/http2curl/v2 v2.3.0/go.mod h1:RW4hyBjTWSYDOxapodpNEtX0g5Eb16sxklBqmd2RHcE=
Loading
Loading