Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Add sqlite3 tracing

天舟d4fb04a76011
diff --git a/backend/.air.toml b/backend/.air.toml
index 55c2df54e2..f9dfd319d4 100644
--- a/backend/.air.toml
+++ b/backend/.air.toml
@@ -3,7 +3,7 @@ tmp_dir = ".air"
[build]
bin = "./.air/bytebase"
- cmd = "go build -o ./.air/bytebase ./cmd/echo/"
+ cmd = "go build --tags \"debug sqlite_trace\" -o ./.air/bytebase ./cmd/echo/"
delay = 1000
exclude_dir = [".air", "vendor"]
exclude_file = []
diff --git a/backend/store/sqlite.go b/backend/store/sqlite.go
index 2b7ecf32da..bafc2c840a 100644
--- a/backend/store/sqlite.go
+++ b/backend/store/sqlite.go
@@ -32,10 +32,10 @@ var seedFS embed.FS
// DB represents the database connection.
type DB struct {
- l *bytebase.Logger
-
db *sql.DB
+ l *bytebase.Logger
+
// Datasource name.
DSN string
@@ -69,7 +69,7 @@ func (db *DB) Open() (err error) {
}
// Connect to the database.
- if db.db, err = sql.Open("sqlite3", db.DSN); err != nil {
+ if db.db, err = sql.Open("sqlite3_tracing", db.DSN); err != nil {
return err
}
diff --git a/backend/store/sqliteTracing.go b/backend/store/sqliteTracing.go
new file mode 100644
index 0000000000..7065a08872
--- /dev/null
+++ b/backend/store/sqliteTracing.go
@@ -0,0 +1,67 @@
+// +build debug, sqlite_trace
+
+package store
+
+import (
+ "database/sql"
+ "fmt"
+ "strings"
+
+ sqlite3 "github.com/mattn/go-sqlite3"
+)
+
+var (
+ whitelistTables = []string{"project", "environment", "instance", "issue"}
+)
+
+func traceCallback(info sqlite3.TraceInfo) int {
+ // Not very readable but may be useful; uncomment next line in case of doubt:
+ //fmt.Printf("Trace: %#v\n", info)
+
+ var dbErrText string
+ if info.DBError.Code != 0 || info.DBError.ExtendedCode != 0 {
+ dbErrText = fmt.Sprintf("; DB error: %#v", info.DBError)
+ } else {
+ dbErrText = ""
+ }
+
+ expandedText := info.StmtOrTrigger
+ if info.ExpandedSQL != "" {
+ expandedText = info.ExpandedSQL
+ }
+
+ // Make sql on a single line and remove redundant whitespaces.
+ cleanText := strings.Join(strings.Fields(strings.TrimSpace(strings.Replace(expandedText, "\n", " ", -1))), " ")
+
+ if dbErrText == "" {
+
+ for _, table := range whitelistTables {
+ if strings.Contains(cleanText, fmt.Sprintf("FROM %s ", table)) {
+ fmt.Printf("%s%s\n",
+ cleanText,
+ dbErrText)
+ }
+ }
+ } else {
+ fmt.Printf("%s%s\n",
+ cleanText,
+ dbErrText)
+ }
+ return 0
+}
+
+func init() {
+ eventMask := sqlite3.TraceStmt | sqlite3.TraceClose
+
+ sql.Register("sqlite3_tracing",
+ &sqlite3.SQLiteDriver{
+ ConnectHook: func(conn *sqlite3.SQLiteConn) error {
+ err := conn.SetTrace(&sqlite3.TraceConfig{
+ Callback: traceCallback,
+ EventMask: eventMask,
+ WantExpandedSQL: true,
+ })
+ return err
+ },
+ })
+}