Skip to content

feat: database/sql integration #893

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

Open
wants to merge 33 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 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
31ef60f
Merge branch 'master' into feat/sentrysql
aldy505 Nov 25, 2024
2802546
Merge remote-tracking branch 'origin/master' into feat/sentrysql
aldy505 Apr 25, 2025
0020dcc
ref(sentrysql): don't return ErrSkip for conn.QueryContext and conn.E…
aldy505 Apr 25, 2025
7cd3b58
ref: move sentrysql to dedicated module
aldy505 Apr 25, 2025
3178fa9
ref(sentrysql): set context before accesing non-context methods
aldy505 Apr 25, 2025
9b12d0a
test(sentrysql): check for received and want spans before observing t…
aldy505 May 7, 2025
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
}
Loading
Loading