Skip to content

Repository files navigation

sqlcommenter

GoDocBuild StatusGo Report Card

Go implementation of https://google.github.io/sqlcommenter/.

Usage with pgx stdlib driver

package main
import (
"context""database/sql""github.com/jackc/pgx/v4/stdlib""github.com/jbub/sqlcommenter"
)
typecontextKeyintconstcontextKeyUserIDcontextKey=0funcwithUserID(ctx context.Context, keystring) context.Context {
returncontext.WithValue(ctx, contextKeyUserID, key)
}
funcuserIDFromContext(ctx context.Context) string {
returnctx.Value(contextKeyUserID).(string)
}
funcmain() {
pgxDrv:=stdlib.GetDefaultDriver()
drv:=sqlcommenter.WrapDriver(pgxDrv,
sqlcommenter.WithAttrPairs("application", "hello-app"),
sqlcommenter.WithAttrFunc(func(ctx context.Context) sqlcommenter.Attrs {
returnsqlcommenter.AttrPairs("user-id", userIDFromContext(ctx))
}),
)
sql.Register("pgx-sqlcommenter", drv)
db, err:=sql.Open("pgx-sqlcommenter", "postgres://user@host:5432/db")
iferr!=nil {
// handle error
}
deferdb.Close()
ctx:=context.Background()
rows, err:=db.QueryContext(withUserID(ctx, "22"), "SELECT 1")
iferr!=nil {
// handle error
}
deferrows.Close()
// will produce the following query: SELECT 1 /*application='hello-app',user-id='22'*/
}

About

Go implementation of https://google.github.io/sqlcommenter/.

Topics

Resources

Stars

10 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages