-
Notifications
You must be signed in to change notification settings - Fork 241
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
aldy505
wants to merge
33
commits into
getsentry:master
Choose a base branch
from
aldy505:feat/sentrysql
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 24 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
e544314
feat: initial sentrysql implementation
aldy505 92e3a6b
chore: resolve a few lint issues
aldy505 aa4acb2
chore: another attempt at resolving lint issues
aldy505 a6b5de8
chore: wrong method name
aldy505 c6ebbda
chore: another attempt of fixing lint issues
aldy505 63413f3
feat: implement missing bits from driver interfaces
aldy505 b77e392
chore: missing a period on comment
aldy505 9b59328
test: replace ramsql with in-memory sqlite
aldy505 7ecd868
test: common queries
aldy505 19c97df
chore: avoid cyclo errors
aldy505 d9073aa
test: no parent span
aldy505 05d699b
test: db.Driver
aldy505 0fc642e
chore: trailing newline
aldy505 7b5fbb5
test: using mysql server for connector
aldy505 93198bd
test: remove mysql server, stay on go1.18
aldy505 ab1d3bf
chore: another go1.18 rollback
aldy505 18d5f66
test: NewSentrySQLConnector
aldy505 3e31bb5
chore(example): sql integration example
aldy505 fbd4dfc
chore: don't lint fakedb
aldy505 1023392
test: backport to go1.18
aldy505 2dc58a5
test: backport to go1.18
aldy505 c5fa49d
chore: lint
aldy505 a6e4fd4
Merge remote-tracking branch 'origin/master' into feat/sentrysql
aldy505 1f38b9f
test(sentrysql): test against legacy driver
aldy505 f173533
chore(sentrysql): remove unvisited context check
aldy505 bcc99fc
chore: lint
aldy505 38ba84c
chore(sentrysql): make sure we implement required interfaces
aldy505 31ef60f
Merge branch 'master' into feat/sentrysql
aldy505 2802546
Merge remote-tracking branch 'origin/master' into feat/sentrysql
aldy505 0020dcc
ref(sentrysql): don't return ErrSkip for conn.QueryContext and conn.E…
aldy505 7cd3b58
ref: move sentrysql to dedicated module
aldy505 3178fa9
ref(sentrysql): set context before accesing non-context methods
aldy505 9b12d0a
test(sentrysql): check for received and want spans before observing t…
aldy505 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.