sqlhooks

将钩子附加到任何 database/sql 驱动上。「Attach hooks to any database/sql driver」

Github stars Tracking Chart

sqlhooks

在任何 database/sql 驱动上附加钩子。

sqlhooks 的目的是提供一种方法来检测你的 sql 语句,使得真正容易记录查询或测量执行时间,而无需修改你的实际代码。

安装

go get github.com/qustavo/sqlhooks/v2

要求 Go >= 1.14.x

破坏性变化

V2 不向后兼容以前的版本,如果你想获取旧版本,你可以使用 go modules 或从 gopkg.in 获取它们

go get github.com/qustavo/sqlhooks
go get gopkg.in/qustavo/sqlhooks.v1

使用方法

// 这个例子显示了如何检测sql查询,以显示它们所消耗的时间
package main
import (
    "context"
    "database/sql"
    "fmt"
    "time"
    "github.com/qustavo/sqlhooks/v2"
    "github.com/mattn/go-sqlite3"
)
// 钩子满足sqlhook.Hooks接口
type Hooks struct {}
// 在钩子之前,将打印查询和它的args,并返回带有时间戳的上下文
func (h *Hooks) Before(ctx context.Context, query string, args ...interface{}) (context.Context, error) {
    fmt.Printf("> %s %q", query, args)
    return context.WithValue(ctx, "begin", time.Now()), nil
}
// After钩子将获得在Before钩子上注册的时间戳,并打印经过的时间。
func (h *Hooks) After(ctx context.Context, query string, args ...interface{}) (context.Context, error) {
    begin := ctx.Value("begin").(time.Time)
    fmt.Printf(". took: %s\n", time.Since(begin))
    return ctx, nil
}
func main() {
    // First, register the wrapper
    sql.Register("sqlite3WithHooks", sqlhooks.Wrap(&sqlite3.SQLiteDriver{}, &Hooks{}))
    // Connect to the registered wrapped driver
    db, _ := sql.Open("sqlite3WithHooks", ":memory:")
    // Do you're stuff
    db.Exec("CREATE TABLE t (id INTEGER, text VARCHAR(16))")
    db.Exec("INSERT into t (text) VALUES(?), (?)", "foo", "bar")
    db.Query("SELECT id, text FROM t")
}
/*
Output should look like:
> CREATE TABLE t (id INTEGER, text VARCHAR(16)) []. took: 121.238µs
> INSERT into t (text) VALUES(?), (?) ["foo" "bar"]. took: 36.364µs
> SELECT id, text FROM t []. took: 4.653µs
*/

基准测试

 go test -bench=. -benchmem
 goos: linux
 goarch: amd64
 pkg: github.com/qustavo/sqlhooks/v2
 cpu: Intel(R) Xeon(R) W-10885M CPU @ 2.40GHz
 BenchmarkSQLite3/Without_Hooks-16                 191196              6163 ns/op             456 B/op         14 allocs/op
 BenchmarkSQLite3/With_Hooks-16                    189997              6329 ns/op             456 B/op         14 allocs/op
 BenchmarkMySQL/Without_Hooks-16                    13278             83462 ns/op             309 B/op          7 allocs/op
 BenchmarkMySQL/With_Hooks-16                       13460             87331 ns/op             309 B/op          7 allocs/op
 BenchmarkPostgres/Without_Hooks-16                 13016             91421 ns/op             401 B/op         10 allocs/op
 BenchmarkPostgres/With_Hooks-16                    12339             94033 ns/op             401 B/op         10 allocs/op
 PASS
 ok      github.com/qustavo/sqlhooks/v2  10.294s


Main metrics

Overview
Name With Ownerqustavo/sqlhooks
Primary LanguageGo
Program languageGo (Language Count: 1)
Platform
License:MIT License
所有者活动
Created At2016-04-20 18:37:14
Pushed At2024-06-27 16:54:20
Last Commit At2022-04-01 09:12:13
Release Count11
Last Release Namev2.1.0 (Posted on 2021-08-08 10:42:42)
First Release Namev0.1 (Posted on )
用户参与
Stargazers Count656
Watchers Count8
Fork Count43
Commits Count124
Has Issues Enabled
Issues Count24
Issue Open Count5
Pull Requests Count21
Pull Requests Open Count5
Pull Requests Close Count7
项目设置
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private

sqlhooks

Build Status
Go Report Card
Coverage Status

Attach hooks to any database/sql driver.

The purpose of sqlhooks is to provide a way to instrument your sql statements, making really easy to log queries or measure execution time without modifying your actual code.

Install

go get github.com/qustavo/sqlhooks/v2

Requires Go >= 1.14.x

Breaking changes

V2 isn't backward compatible with previous versions, if you want to fetch old versions, you can use go modules or get them from gopkg.in

go get github.com/qustavo/sqlhooks
go get gopkg.in/qustavo/sqlhooks.v1

Usage GoDoc

// This example shows how to instrument sql queries in order to display the time that they consume
package main

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"github.com/qustavo/sqlhooks/v2"
	"github.com/mattn/go-sqlite3"
)

// Hooks satisfies the sqlhook.Hooks interface
type Hooks struct {}

// Before hook will print the query with it's args and return the context with the timestamp
func (h *Hooks) Before(ctx context.Context, query string, args ...interface{}) (context.Context, error) {
	fmt.Printf("> %s %q", query, args)
	return context.WithValue(ctx, "begin", time.Now()), nil
}

// After hook will get the timestamp registered on the Before hook and print the elapsed time
func (h *Hooks) After(ctx context.Context, query string, args ...interface{}) (context.Context, error) {
	begin := ctx.Value("begin").(time.Time)
	fmt.Printf(". took: %s\n", time.Since(begin))
	return ctx, nil
}

func main() {
	// First, register the wrapper
	sql.Register("sqlite3WithHooks", sqlhooks.Wrap(&sqlite3.SQLiteDriver{}, &Hooks{}))

	// Connect to the registered wrapped driver
	db, _ := sql.Open("sqlite3WithHooks", ":memory:")

	// Do you're stuff
	db.Exec("CREATE TABLE t (id INTEGER, text VARCHAR(16))")
	db.Exec("INSERT into t (text) VALUES(?), (?)", "foo", "bar")
	db.Query("SELECT id, text FROM t")
}

/*
Output should look like:
> CREATE TABLE t (id INTEGER, text VARCHAR(16)) []. took: 121.238µs
> INSERT into t (text) VALUES(?), (?) ["foo" "bar"]. took: 36.364µs
> SELECT id, text FROM t []. took: 4.653µs
*/

Benchmarks

 go test -bench=. -benchmem
 BenchmarkSQLite3/Without_Hooks-4                  200000              8572 ns/op             627 B/op         16 allocs/op
 BenchmarkSQLite3/With_Hooks-4                     200000             10231 ns/op             738 B/op         18 allocs/op
 BenchmarkMySQL/Without_Hooks-4                     10000            108421 ns/op             437 B/op         10 allocs/op
 BenchmarkMySQL/With_Hooks-4                        10000            226085 ns/op             597 B/op         13 allocs/op
 BenchmarkPostgres/Without_Hooks-4                  10000            125718 ns/op             649 B/op         17 allocs/op
 BenchmarkPostgres/With_Hooks-4                      5000            354831 ns/op            1122 B/op         27 allocs/op
 PASS
 ok      github.com/qustavo/sqlhooks    11.713s