diff --git a/dbutil/litestream/register.go b/dbutil/litestream/register.go index 9dddf2d..9f8cf5b 100644 --- a/dbutil/litestream/register.go +++ b/dbutil/litestream/register.go @@ -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 } @@ -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 } diff --git a/dbutil/litestream/register_notrace.go b/dbutil/litestream/register_notrace.go new file mode 100644 index 0000000..3149877 --- /dev/null +++ b/dbutil/litestream/register_notrace.go @@ -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 +} diff --git a/dbutil/litestream/register_trace.go b/dbutil/litestream/register_trace.go new file mode 100644 index 0000000..0abb5f1 --- /dev/null +++ b/dbutil/litestream/register_trace.go @@ -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, + }) +}