Skip to content

Commit

Permalink
dbutil: print sqlite queries when compiled in trace mode
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Jul 13, 2024
1 parent fe2e452 commit 773705b
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
8 changes: 8 additions & 0 deletions dbutil/litestream/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import (
func init() {
sql.Register("litestream", &sqlite3.SQLiteDriver{
ConnectHook: func(conn *sqlite3.SQLiteConn) (err error) {
err = DoSetTrace(conn)
if err != nil {
return
}
if err = conn.SetFileControlInt("main", sqlite3.SQLITE_FCNTL_PERSIST_WAL, 1); err != nil {
return
}
Expand All @@ -36,6 +40,10 @@ func init() {

sql.Register("sqlite3-fk-wal", &sqlite3.SQLiteDriver{
ConnectHook: func(conn *sqlite3.SQLiteConn) (err error) {
err = DoSetTrace(conn)
if err != nil {
return
}
if _, err = conn.Exec("PRAGMA foreign_keys = ON", []driver.Value{}); err != nil {
return
}
Expand Down
11 changes: 11 additions & 0 deletions dbutil/litestream/register_notrace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//go:build cgo && !sqlite_trace

package litestream

import (
"github.com/mattn/go-sqlite3"
)

func DoSetTrace(conn *sqlite3.SQLiteConn) error {
return nil
}
38 changes: 38 additions & 0 deletions dbutil/litestream/register_trace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//go:build cgo && sqlite_trace

package litestream

import (
"fmt"
"time"

"github.com/mattn/go-sqlite3"
)

func traceCallback(info sqlite3.TraceInfo) int {
switch info.EventCode {
case sqlite3.TraceStmt:
fmt.Println(info.ExpandedSQL)
fmt.Println("-------------------------------------------------------------")
default:
fmt.Print("exectime: ", time.Duration(info.RunTimeNanosec).String())
if info.AutoCommit {
fmt.Print(" - autocommit")
} else {
fmt.Print(" - transaction")
}
if info.DBError.Code != 0 || info.DBError.ExtendedCode != 0 {
fmt.Printf(" - error %#v", info.DBError)
}
fmt.Println()
}
return 0
}

func DoSetTrace(conn *sqlite3.SQLiteConn) error {
return conn.SetTrace(&sqlite3.TraceConfig{
Callback: traceCallback,
EventMask: sqlite3.TraceStmt | sqlite3.TraceProfile | sqlite3.TraceRow | sqlite3.TraceClose,
WantExpandedSQL: true,
})
}

0 comments on commit 773705b

Please sign in to comment.