sqlcommenter

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2021 License: MIT Imports: 5 Imported by: 0

README

sqlcommenter

GoDoc Build Status Go Report Card

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

Public API is not stable, expect breaking changes.

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Comment

func Comment(ctx context.Context, query string, opts ...Option) string

func WrapDriver

func WrapDriver(drv driver.Driver, opts ...Option) driver.Driver

Types

type Attr

type Attr struct {
	Key   string
	Value string
}

type AttrProvider

type AttrProvider interface {
	GetAttrs(context.Context) Attrs
}

type AttrProviderFunc

type AttrProviderFunc func(context.Context) Attrs

func (AttrProviderFunc) GetAttrs

func (f AttrProviderFunc) GetAttrs(ctx context.Context) Attrs

type Attrs

type Attrs map[string]string

func AttrPairs

func AttrPairs(pairs ...string) Attrs

func (Attrs) Update

func (a Attrs) Update(other Attrs)

type Option

type Option func(cmt *commenter)

func WithAttrFunc

func WithAttrFunc(fn AttrProviderFunc) Option

func WithAttrPairs

func WithAttrPairs(pairs ...string) Option

func WithAttrProvider

func WithAttrProvider(prov AttrProvider) Option

func WithAttrs

func WithAttrs(attrs Attrs) Option

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL