Attach hooks to any database/sql driver


sqlhooks Build Status Coverage Status Go Report Card

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.


go get

Requires Go >= 1.8.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

go get
go get

Usage GoDoc

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

import (


// 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


 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
 ok    11.713s
  • handler sql error

    handler sql error

    Now if any SQL error happens, After hook will not be called. It's cause OpenTracing span can't be finished normally. And the span will disappear on OpenTracing dashboard(I'm using Jaeger). It makes lot's of inconvenient because the only thing I really care about is the error message.

    opened by xuzhenglun 19
  • Return an ExecerContext if conn is an execer

    Return an ExecerContext if conn is an execer

    A driver.Conn can optionally implement driver.ExecerContext or driver.Execer. When they do, instead of creating a prepared statement and then executing that database/sql will directly call ExecContext or Exec respectively. We need to implement this since some drivers do not support all statements being prepared first. For example in postgresql you can run multiple statements in a conn.Exec, but it will fail if you try to prepare multiple statements in one call.

    opened by keegancsmith 12
  • Actual resulting query?

    Actual resulting query?

    I was hoping the after hook would include the resulting query, as it is actually passed to the database.

    So instead of showing the original query like

    'select id, first, last from users where id=?', '12'

    It would include

    'select id, first, last from users where id=12'

    Useful for debugging edge cases, logging of all actual statements (to rebuild a database or specific situation) and other things.

    opened by Gys 9
  • allow composing Hooks

    allow composing Hooks

    adds func Compose that allows composing multiple Hooks into one. It runs every callback on every hook in argument order, even if previous hooks return an error. If multiple hooks return errors, the error return value will be MultipleErrors, which allows for introspecting the errors if necessary.

    I chose not to abort processing when any handler returns an error, because common usage would be to compose logging / tracing / metrics, and those kinds of handlers will want to run in every case to make sure that e.g. latencies are tracked correctly.

    I added compatibility with Go 1.13's errors.Is/errors.As methods under a conditional compilation flag.

    Fixes: #12

    opened by ccmtaylor 8
  • Change Notifications

    Change Notifications

    Great work! I think this could be great for data change notification events to various parts of an application. Is it possible to make the hooks pre or post execution with the ability to cancel a pre-hook query? For example, a use case might be to stop any query that contains "CREATE TABLE" for users that don't have that permission.

    opened by nkev 7
  • can't use transactions with sqlhooks

    can't use transactions with sqlhooks

    I can't start transaction with non default isolation level because connection returned from sqlhooks.Conn wrapper doesn't implement driver.ConnBeginTx interface

    opened by minaevmike 6
  • driver.ErrSkip error with sqlx

    driver.ErrSkip error with sqlx

    The hooks get entered twice for each sql query because from my understanding, the first hit to the hook get cancelled because of driver.ErrSkip "driver: skip fast-path; continue as if unimplemented" It seems to happen with sqlx.

    More details is in the discussion over at data-dog

    Right now a quick fix would be checking for driver.ErrSkip and ignore it in every execs and query

    results, err := conn.execContext(ctx, query, args)
    - if err != nil {
    + if err != nil && err != driver.ErrSkip {
        return results, handlerErr(ctx, conn.hooks, err, query, list...)

    The other fix (from the thread) is to set interpolateParams=true is the database dsn.

    opened by gmhafiz 4
  • Issues with gorm

    Issues with gorm

    I've recently tried out sqlhooks and encountered a problem:

    [2018-05-23 14:51:15]  Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"labels"  WHERE (user_id = 0 AND is_system = 1 AND label IN (?,?,?,?))' at line 1
    [2018-05-23 14:51:15]  [2.00ms]  SELECT * FROM "labels"  WHERE (user_id = 0 AND is_system = 1 AND label IN ('Inbox','Archive','Trash','Snoozed'))

    As you can see, for some reason requests went into mysql without substitution. This only occurs if I wrap the driver with sqlhooks:

    	sql.Register("mysqlWithHooks", sqlhooks.Wrap(&mysql.MySQLDriver{}, &Hooks{}))
    	db, err := gorm.Open("mysqlWithHooks", config.DB.DSN())
    	if err != nil {
    		return stacktrace.Propagate(err, "Failed to connect to DB")

    I wonder if I'm doing something wrong here.

    opened by dobegor 3
  • QueryerContext interface and prepared statements

    QueryerContext interface and prepared statements

    If we don't implement QueryerContext or Queryer interface for connection, db.Query() will always do statement "prepare" and statement "exec". These extra roundtrips can add unneeded latency.

    Run this test program and check in wireshark:

    A change like this fixes this:

    I could send a PR if you would like this fixed here

    opened by surki 1
  • when using wraper driver, table name has  Double quotes

    when using wraper driver, table name has Double quotes

    when using wraper dierver, code like this: image sql exec err for table name has double quotes, image

    when not using wraper, code like this image sql exec success, table name change ok image

    so, what is the problem?

    opened by huangyong-170207 1
  • feat: support driver.DriverContext interface

    feat: support driver.DriverContext interface

    sql.Open internally makes use of the DriverContext interface, and if a Driver does not implement it, it creates a light wrapper1.

    This DriverContext provides better context support as well as providing some useful error checking upfront. For instance, the mysql driver can check the DSN value before opening a connection to see if it's well formed. That way you get an error instantly instead of an error when making your first sql query


    opened by conradludgate 2
  • Add Rows wrapper and safetyhooks

    Add Rows wrapper and safetyhooks

    Work in progress of safetyhooks, which panics when sql.Rows are not closed, this is useful to detect leaks. Based on sharp-edge finalizers

    opened by qustavo 2
  • SQL commands inside hook methods

    SQL commands inside hook methods

    I would like to execute SQL commands inside the hook methods. These commands must be on the same transaction of the original command. I mean the one triggered by the programmer using the database/sql API. I have to do this transparently. Do you think it is feseable and straightforward to implement? I guess I would have to add extra parameters to the hook methods' signatures. However, I am wondering how I could append these extra comands to the ongoing transaction.

    opened by fadc80 1
Gustavo Chaín
Technical Dealer
Gustavo Chaín
Microsoft ActiveX Object DataBase driver for go that using exp/sql

go-adodb Microsoft ADODB driver conforming to the built-in database/sql interface Installation This package can be installed with the go get command:

mattn 131 Nov 2, 2022
Oracle driver for Go using database/sql

go-oci8 Description Golang Oracle database driver conforming to the Go database/sql interface Installation Install Oracle full client or Instant Clien

mattn 596 Nov 13, 2022
sqlite3 driver for go using database/sql

go-sqlite3 Latest stable version is v1.14 or later not v2. NOTE: The increase to v2 was an accident. There were no major changes or features. Descript

mattn 6.2k Nov 24, 2022
Go Sql Server database driver.

gofreetds Go FreeTDS wrapper. Native Sql Server database driver. Features: can be used as database/sql driver handles calling stored procedures handle

minus5 106 Oct 19, 2022
Pure Go Postgres driver for database/sql

pq - A pure Go postgres driver for Go's database/sql package Install go get Features SSL Handles bad connections for database/sql S

null 7.7k Nov 19, 2022
Qmgo - The Go driver for MongoDB. It‘s based on official mongo-go-driver but easier to use like Mgo.

Qmgo English | 简体中文 Qmgo is a Go driver for MongoDB . It is based on MongoDB official driver, but easier to use like mgo (such as the chain call). Qmg

Qiniu Cloud 1k Nov 27, 2022
Go driver for PostgreSQL over SSH. This driver can connect to postgres on a server via SSH using the local ssh-agent, password, or private-key.

pqssh Go driver for PostgreSQL over SSH. This driver can connect to postgres on a server via SSH using the local ssh-agent, password, or private-key.

mattn 52 Nov 6, 2022
Mirror of Apache Calcite - Avatica Go SQL Driver

Apache Avatica/Phoenix SQL Driver Apache Calcite's Avatica Go is a Go database/sql driver for the Avatica server. Avatica is a sub-project of Apache C

The Apache Software Foundation 103 Nov 3, 2022
Firebird RDBMS sql driver for Go (golang)

firebirdsql (Go firebird sql driver) Firebird RDBMS SQL driver for Go Requirements Firebird 2.5 or higher Golang 1.13 or higher

Hajime Nakagami 183 Nov 18, 2022
Microsoft SQL server driver written in go language

A pure Go MSSQL driver for Go's database/sql package Install Requires Go 1.8 or above. Install with go get . Connecti

null 1.7k Nov 17, 2022
GoBigdis is a persistent database that implements the Redis server protocol. Any Redis client can interface with it and start to use it right away.

GoBigdis GoBigdis is a persistent database that implements the Redis server protocol. Any Redis client can interface with it and start to use it right

Riccardo 5 Apr 27, 2022
GO DRiver for ORacle DB

Go DRiver for ORacle godror is a package which is a database/sql/driver.Driver for connecting to Oracle DB, using Anthony Tuininga's excellent OCI wra

null 400 Nov 17, 2022
PostgreSQL driver and toolkit for Go

pgx - PostgreSQL Driver and Toolkit pgx is a pure Go driver and toolkit for PostgreSQL. pgx aims to be low-level, fast, and performant, while also ena

Jack Christensen 6.3k Nov 23, 2022
Lightweight Golang driver for ArangoDB

Arangolite Arangolite is a lightweight ArangoDB driver for Go. It focuses on pure AQL querying. See AranGO for a more ORM-like experience. IMPORTANT:

Fabien Herfray 73 Sep 26, 2022
Go language driver for RethinkDB

RethinkDB-go - RethinkDB Driver for Go Go driver for RethinkDB Current version: v6.2.1 (RethinkDB v2.4) Please note that this version of the driver on

RethinkDB 1.6k Nov 22, 2022
goriak - Go language driver for Riak KV

goriak Current version: v3.2.1. Riak KV version: 2.0 or higher, the latest version of Riak KV is always recommended. What is goriak? goriak is a wrapp

Gustav Westling 28 Sep 26, 2022
Mongo Go Models (mgm) is a fast and simple MongoDB ODM for Go (based on official Mongo Go Driver)

Mongo Go Models Important Note: We changed package name from Kamva) to kamva) in v

kamva 587 Nov 19, 2022
The MongoDB driver for Go

The MongoDB driver for Go This fork has had a few improvements by ourselves as well as several PR's merged from the original mgo repo that are current

GlobalSign 2k Nov 19, 2022
The Go driver for MongoDB

MongoDB Go Driver The MongoDB supported driver for Go. Requirements Installation Usage Bugs / Feature Reporting Testing / Development Continuous Integ

mongodb 7.1k Nov 20, 2022