|
| 1 | +# sqlcommenter |
| 2 | +[](https://godoc.org/github.com/jbub/sqlcommenter) |
| 3 | +[](https://cloud.drone.io/jbub/sqlcommenter) |
| 4 | +[](https://goreportcard.com/report/github.com/jbub/sqlcommenter) |
| 5 | + |
| 6 | +Go implementation of https://google.github.io/sqlcommenter/. |
| 7 | + |
| 8 | +## Usage with pgx stdlib driver |
| 9 | + |
| 10 | +```go |
| 11 | +package main |
| 12 | + |
| 13 | +import ( |
| 14 | + "context" |
| 15 | + "database/sql" |
| 16 | + |
| 17 | + "github.com/jackc/pgx/v4/stdlib" |
| 18 | + "github.com/jbub/sqlcommenter" |
| 19 | +) |
| 20 | + |
| 21 | +type contextKey int |
| 22 | + |
| 23 | +const contextKeyUserID contextKey = 0 |
| 24 | + |
| 25 | +func withUserID(ctx context.Context, key string) context.Context { |
| 26 | + return context.WithValue(ctx, contextKeyUserID, key) |
| 27 | +} |
| 28 | + |
| 29 | +func userIDFromContext(ctx context.Context) string { |
| 30 | + return ctx.Value(contextKeyUserID).(string) |
| 31 | +} |
| 32 | + |
| 33 | +func main() { |
| 34 | + pgxDrv := stdlib.GetDefaultDriver() |
| 35 | + drv := sqlcommenter.WrapDriver(pgxDrv, |
| 36 | + sqlcommenter.WithAttrPairs("application", "hello-app"), |
| 37 | + sqlcommenter.WithAttrFunc(func(ctx context.Context) sqlcommenter.Attrs { |
| 38 | + return sqlcommenter.AttrPairs("user-id", userIDFromContext(ctx)) |
| 39 | + }), |
| 40 | + ) |
| 41 | + |
| 42 | + sql.Register("pgx-sqlcommenter", drv) |
| 43 | + |
| 44 | + db, err := sql.Open("pgx-sqlcommenter", "postgres://user@host:5432/db") |
| 45 | + if err != nil { |
| 46 | + // handle error |
| 47 | + } |
| 48 | + defer db.Close() |
| 49 | + |
| 50 | + ctx := context.Background() |
| 51 | + |
| 52 | + rows, err := db.QueryContext(withUserID(ctx, "22"), "SELECT 1") |
| 53 | + if err != nil { |
| 54 | + // handle error |
| 55 | + } |
| 56 | + defer rows.Close() |
| 57 | + |
| 58 | + // will produce the following query: SELECT 1 /* application='hello-app',user-id='22' */ |
| 59 | +} |
| 60 | +``` |
0 commit comments