Skip to content

jbub/sqlcommenter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

a52d979 · Oct 10, 2024

History

18 Commits
Oct 10, 2024
Oct 5, 2021
Oct 10, 2024
Oct 10, 2024
Feb 22, 2022
Feb 11, 2022
Nov 2, 2021
Feb 22, 2022
Feb 22, 2022
Oct 10, 2024
Feb 11, 2022
Oct 10, 2024
Nov 2, 2021
Nov 2, 2021
Oct 10, 2024
Oct 5, 2021
Feb 11, 2022

Repository files navigation

sqlcommenter

GoDoc Build Status Go 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"
)

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'*/
}