https://github.com/jbub/sqlcommenter
Go implementation of https://google.github.io/sqlcommenter/.
https://github.com/jbub/sqlcommenter
go golang sql
Last synced: 22 days ago
JSON representation
Go implementation of https://google.github.io/sqlcommenter/.
- Host: GitHub
- URL: https://github.com/jbub/sqlcommenter
- Owner: jbub
- License: mit
- Created: 2021-10-05T13:39:18.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2022-08-12T07:22:31.000Z (over 3 years ago)
- Last Synced: 2024-06-19T17:50:56.041Z (almost 2 years ago)
- Topics: go, golang, sql
- Language: Go
- Homepage:
- Size: 24.4 KB
- Stars: 10
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# sqlcommenter
[](https://godoc.org/github.com/jbub/sqlcommenter)
[](https://cloud.drone.io/jbub/sqlcommenter)
[](https://goreportcard.com/report/github.com/jbub/sqlcommenter)
Go implementation of https://google.github.io/sqlcommenter/.
## Usage with pgx stdlib driver
```go
package main
import (
"context"
"database/sql"
"github.com/jackc/pgx/v4/stdlib"
"github.com/jbub/sqlcommenter"
)
type contextKey int
const contextKeyUserID contextKey = 0
func withUserID(ctx context.Context, key string) context.Context {
return context.WithValue(ctx, contextKeyUserID, key)
}
func userIDFromContext(ctx context.Context) string {
return ctx.Value(contextKeyUserID).(string)
}
func main() {
pgxDrv := stdlib.GetDefaultDriver()
drv := sqlcommenter.WrapDriver(pgxDrv,
sqlcommenter.WithAttrPairs("application", "hello-app"),
sqlcommenter.WithAttrFunc(func(ctx context.Context) sqlcommenter.Attrs {
return sqlcommenter.AttrPairs("user-id", userIDFromContext(ctx))
}),
)
sql.Register("pgx-sqlcommenter", drv)
db, err := sql.Open("pgx-sqlcommenter", "postgres://user@host:5432/db")
if err != nil {
// handle error
}
defer db.Close()
ctx := context.Background()
rows, err := db.QueryContext(withUserID(ctx, "22"), "SELECT 1")
if err != nil {
// handle error
}
defer rows.Close()
// will produce the following query: SELECT 1 /*application='hello-app',user-id='22'*/
}
```