Skip to content

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

refactor(backend): extract transaction configuration and audit helpers (#21508)

p0ny8acbe4b639c3
diff --git a/backend/api/mcp/connection_audit.go b/backend/api/mcp/connection_audit.go
index 41e5464ac6..af13d48457 100644
--- a/backend/api/mcp/connection_audit.go
+++ b/backend/api/mcp/connection_audit.go
@@ -11,6 +11,7 @@ import (
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/audit"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
@@ -45,14 +46,14 @@ func (s *Server) refuseByCeiling(c *echo.Context, delegated auth.DelegatedMCPCre
func (s *Server) refuseConnection(c *echo.Context, delegated auth.DelegatedMCPCredential, reason string) error {
row := &storepb.AuditLog{
Parent: common.FormatWorkspace(delegated.WorkspaceID),
- Method: common.AuditMethodMCPSessionAuthorize,
+ Method: audit.AuditMethodMCPSessionAuthorize,
Resource: common.FormatWorkspace(delegated.WorkspaceID),
User: common.FormatUserEmail(delegated.Principal),
Status: &spb.Status{
Code: int32(codes.PermissionDenied),
Message: reason,
},
- RequestMetadata: common.RequestMetadataFromHTTP(c.Request()),
+ RequestMetadata: audit.RequestMetadataFromHTTP(c.Request()),
// The grant this token carries, and no correlation ID. That field is
// session-scoped, and this refusal is decided before the SDK resolves a
// session: an initial connection has none, and a mid-session refusal
@@ -65,7 +66,7 @@ func (s *Server) refuseConnection(c *echo.Context, delegated auth.DelegatedMCPCr
ClientId: delegated.ClientID,
},
}
- common.RecordOutOfBandAudit(c.Request().Context(), s.store,
+ audit.RecordOutOfBandAudit(c.Request().Context(), s.store,
s.profile.RuntimeEnableAuditLogStdout.Load(), delegated.WorkspaceID, row)
return echo.NewHTTPError(http.StatusForbidden, reason)
}
diff --git a/backend/api/mcp/connection_audit_test.go b/backend/api/mcp/connection_audit_test.go
index 33ef8be971..57aefa9ab9 100644
--- a/backend/api/mcp/connection_audit_test.go
+++ b/backend/api/mcp/connection_audit_test.go
@@ -17,6 +17,7 @@ import (
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/audit"
"github.com/bytebase/bytebase/backend/component/config"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
@@ -52,7 +53,7 @@ func TestMCPConnectionDenialEmission(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("User-Agent", "TestAgent/1.0")
- req.Header.Set(common.HeaderRealIP, "10.0.1.50")
+ req.Header.Set(audit.HeaderRealIP, "10.0.1.50")
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
handler := srv.authMiddleware(func(c *echo.Context) error {
@@ -73,7 +74,7 @@ func TestMCPConnectionDenialEmission(t *testing.T) {
require.Len(t, st.auditRows, 1)
row := st.auditRows[0]
- require.Equal(t, common.AuditMethodMCPSessionAuthorize, row.Method)
+ require.Equal(t, audit.AuditMethodMCPSessionAuthorize, row.Method)
require.Equal(t, "workspaces/ws-test", row.Parent)
require.Equal(t, "workspaces/ws-test", row.Resource)
require.Equal(t, "users/[email protected]", row.User)
@@ -235,7 +236,7 @@ func TestMCPConnectionDenialEmission(t *testing.T) {
require.Equal(t, http.StatusForbidden, connect(t, srv, mcpToken(t, secret, tokenOptions{})))
require.Contains(t, buf.String(), `"log_type":"audit"`,
"a database failure is exactly when the stream is the surface that still works")
- require.Contains(t, buf.String(), common.AuditMethodMCPSessionAuthorize)
+ require.Contains(t, buf.String(), audit.AuditMethodMCPSessionAuthorize)
})
t.Run("a failed write does not admit the connection", func(t *testing.T) {
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index cf46f25284..1299483a90 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -19,8 +19,8 @@ import (
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/api/auth"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/audit"
"github.com/bytebase/bytebase/backend/component/config"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/store"
@@ -341,8 +341,8 @@ func (s *Server) authMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// Normalize the resolved address onto the request so the per-request
// path sees it too: receiving middleware gets each request's headers,
// but never its peer address.
- resolvedIP := common.CallerIP(c.Request())
- c.Request().Header.Set(common.HeaderRealIP, resolvedIP)
+ resolvedIP := audit.CallerIP(c.Request())
+ c.Request().Header.Set(audit.HeaderRealIP, resolvedIP)
ctx = withCallerIP(ctx, resolvedIP)
ctx = withSessionBinding(ctx, sessionBinding{
fingerprint: sessionFingerprint(delegated),
@@ -488,7 +488,7 @@ func sessionFingerprint(identity auth.DelegatedMCPCredential) string {
func liveRequestMetadata(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
if extra := req.GetExtra(); extra != nil && extra.Header != nil {
- if ip := common.CallerIPFromHeaders(extra.Header); ip != "" {
+ if ip := audit.CallerIPFromHeaders(extra.Header); ip != "" {
ctx = withCallerIP(ctx, ip)
}
if token, err := auth.GetTokenFromHeaders(extra.Header); err == nil && token != "" {
diff --git a/backend/api/mcp/tool_http.go b/backend/api/mcp/tool_http.go
index 710da9fbb2..f60a2798f1 100644
--- a/backend/api/mcp/tool_http.go
+++ b/backend/api/mcp/tool_http.go
@@ -13,9 +13,9 @@ import (
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/api/auth"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/common/stacktrace"
+ "github.com/bytebase/bytebase/backend/component/audit"
)
// apiResponse holds the HTTP response from an internal API call.
@@ -70,7 +70,7 @@ func (s *Server) apiRequest(ctx context.Context, path string, body any) (*apiRes
// no peer address to fall back to, so without this the origin of every
// MCP-originated action would be blank.
if ip := getCallerIP(ctx); ip != "" {
- httpReq.Header.Set(common.HeaderRealIP, ip)
+ httpReq.Header.Set(audit.HeaderRealIP, ip)
}
// Mint the credential for this call. Per call, not per session: see
diff --git a/backend/api/oauth2/consent_audit.go b/backend/api/oauth2/consent_audit.go
index 1bdb0299eb..26fe8c7d69 100644
--- a/backend/api/oauth2/consent_audit.go
+++ b/backend/api/oauth2/consent_audit.go
@@ -14,6 +14,7 @@ import (
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/audit"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
@@ -79,8 +80,8 @@ func (s *Service) refuseConsentByCeiling(c *echo.Context, attempt consentAttempt
// The row is written here for the same reason the connection gate writes its
// own: this route is echo, so no interceptor sees it.
func (s *Service) refuseConsent(c *echo.Context, attempt consentAttempt, verdict auth.MCPCeilingVerdict) error {
- row := consentRefusalRow(attempt, verdict, common.RequestMetadataFromHTTP(c.Request()))
- common.RecordOutOfBandAudit(c.Request().Context(), s.store,
+ row := consentRefusalRow(attempt, verdict, audit.RequestMetadataFromHTTP(c.Request()))
+ audit.RecordOutOfBandAudit(c.Request().Context(), s.store,
s.profile.RuntimeEnableAuditLogStdout.Load(), attempt.user.workspaceID, row)
return c.HTML(http.StatusForbidden, consentRefusedHTML(verdict, attempt.redirectURI, attempt.state))
}
@@ -93,7 +94,7 @@ func (s *Service) refuseConsent(c *echo.Context, attempt consentAttempt, verdict
func consentRefusalRow(attempt consentAttempt, verdict auth.MCPCeilingVerdict, requestMetadata *storepb.RequestMetadata) *storepb.AuditLog {
return &storepb.AuditLog{
Parent: common.FormatWorkspace(attempt.user.workspaceID),
- Method: common.AuditMethodMCPConsentApprove,
+ Method: audit.AuditMethodMCPConsentApprove,
Resource: common.FormatWorkspace(attempt.user.workspaceID),
User: common.FormatUserEmail(attempt.user.email),
Status: &spb.Status{
diff --git a/backend/api/oauth2/consent_audit_test.go b/backend/api/oauth2/consent_audit_test.go
index 9768c788ff..5e9a5f236a 100644
--- a/backend/api/oauth2/consent_audit_test.go
+++ b/backend/api/oauth2/consent_audit_test.go
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/backend/api/auth"
- "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/audit"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
@@ -49,7 +49,7 @@ func TestConsentRefusal(t *testing.T) {
require.True(t, verdict.IsPolicy())
row := consentRefusalRow(attempt, verdict, &storepb.RequestMetadata{CallerIp: "10.0.1.50"})
- require.Equal(t, common.AuditMethodMCPConsentApprove, row.Method)
+ require.Equal(t, audit.AuditMethodMCPConsentApprove, row.Method)
require.Equal(t, "workspaces/ws-disabled", row.Parent)
require.Equal(t, "users/[email protected]", row.User)
require.EqualValues(t, 7, row.GetStatus().GetCode(), "PermissionDenied")
diff --git a/backend/api/v1/audit.go b/backend/api/v1/audit.go
index 893b2257b7..66a5adf0d4 100644
--- a/backend/api/v1/audit.go
+++ b/backend/api/v1/audit.go
@@ -21,6 +21,7 @@ import (
"github.com/bytebase/bytebase/backend/api/auth"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/audit"
"github.com/bytebase/bytebase/backend/component/config"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
@@ -40,7 +41,7 @@ const (
// audited method that reached its handler. Stdout, when on, streams every
// stored row and every call a permission check refused, before the insert.
type AuditInterceptor struct {
- auditLogWriter common.AuditLogWriter
+ auditLogWriter audit.LogWriter
secret string
profile *config.Profile
}
@@ -211,7 +212,7 @@ func (in *AuditInterceptor) createAuditLog(ctx context.Context, e *auditEntry) e
// database does not.
if in.profile.RuntimeEnableAuditLogStdout.Load() {
for _, row := range rows {
- common.LogAuditToStdout(ctx, row.payload)
+ audit.LogAuditToStdout(ctx, row.payload)
}
}
if !e.store {
@@ -547,9 +548,9 @@ func needAudit(ctx context.Context) bool {
func getRequestMetadataFromHeaders(headers http.Header, peerAddr string) *storepb.RequestMetadata {
// The forwarding headers first, then the peer address ConnectRPC reports
// for a direct connection.
- callerIP := common.CallerIPFromHeaders(headers)
+ callerIP := audit.CallerIPFromHeaders(headers)
if callerIP == "" {
- callerIP = common.StripPort(peerAddr)
+ callerIP = audit.StripPort(peerAddr)
}
return &storepb.RequestMetadata{
CallerIp: callerIP,
diff --git a/backend/api/v1/audit_test.go b/backend/api/v1/audit_test.go
index 05191cd7b1..459ea392ca 100644
--- a/backend/api/v1/audit_test.go
+++ b/backend/api/v1/audit_test.go
@@ -235,16 +235,16 @@ func (r *specRequest) Spec() connect.Spec {
return connect.Spec{Procedure: r.procedure}
}
-// auditLogWriterFunc adapts a function to common.AuditLogWriter.
+// auditLogWriterFunc adapts a function to audit.LogWriter.
type auditLogWriterFunc func(context.Context, string, *storepb.AuditLog) error
func (f auditLogWriterFunc) CreateAuditLog(ctx context.Context, workspace string, payload *storepb.AuditLog) error {
return f(ctx, workspace, payload)
}
-// recordingAuditLogWriter stands in for the store's insert. It keeps every row
+// recordingLogWriter stands in for the store's insert. It keeps every row
// the interceptor tried to store, and fails each insert with err when set.
-type recordingAuditLogWriter struct {
+type recordingLogWriter struct {
mu sync.Mutex
rows []auditRow
err error
@@ -253,7 +253,7 @@ type recordingAuditLogWriter struct {
onInsert func()
}
-func (w *recordingAuditLogWriter) CreateAuditLog(_ context.Context, workspace string, payload *storepb.AuditLog) error {
+func (w *recordingLogWriter) CreateAuditLog(_ context.Context, workspace string, payload *storepb.AuditLog) error {
if w.onInsert != nil {
w.onInsert()
}
@@ -263,7 +263,7 @@ func (w *recordingAuditLogWriter) CreateAuditLog(_ context.Context, workspace st
return w.err
}
-func (w *recordingAuditLogWriter) stored() []auditRow {
+func (w *recordingLogWriter) stored() []auditRow {
w.mu.Lock()
defer w.mu.Unlock()
return slices.Clone(w.rows)
@@ -273,9 +273,9 @@ func (w *recordingAuditLogWriter) stored() []auditRow {
// writer that keeps the rows each call stored, so a test asserts on what the
// interceptor decided rather than on a database. TestStreamingAuditRedactsRows
// writes through the real store.
-func newRecordingAuditInterceptor() (*AuditInterceptor, *recordingAuditLogWriter) {
+func newRecordingAuditInterceptor() (*AuditInterceptor, *recordingLogWriter) {
in := NewAuditInterceptor(nil, "test-secret", &config.Profile{})
- writer := &recordingAuditLogWriter{}
+ writer := &recordingLogWriter{}
in.auditLogWriter = writer
return in, writer
}
diff --git a/backend/common/engine.go b/backend/common/engine.go
index 7e921f0dcf..7e551e5993 100644
--- a/backend/common/engine.go
+++ b/backend/common/engine.go
@@ -457,45 +457,3 @@ func BackupDatabaseNameOfEngine(e storepb.Engine) string {
return "bbdataarchive"
}
}
-
-// TransactionMode represents the transaction execution mode for a migration script.
-type TransactionMode string
-
-const (
- // TransactionModeOn wraps the script in a single transaction.
- TransactionModeOn TransactionMode = "on"
- // TransactionModeOff executes the script's statements sequentially in auto-commit mode.
- TransactionModeOff TransactionMode = "off"
- // TransactionModeUnspecified means no explicit mode was specified.
- TransactionModeUnspecified TransactionMode = ""
-)
-
-// IsolationLevel represents the transaction isolation level.
-type IsolationLevel string
-
-const (
- // IsolationLevelDefault uses the database's default isolation level.
- IsolationLevelDefault IsolationLevel = ""
- // IsolationLevelReadUncommitted allows dirty reads.
- IsolationLevelReadUncommitted IsolationLevel = "READ UNCOMMITTED"
- // IsolationLevelReadCommitted prevents dirty reads.
- IsolationLevelReadCommitted IsolationLevel = "READ COMMITTED"
- // IsolationLevelRepeatableRead prevents dirty reads and non-repeatable reads.
- IsolationLevelRepeatableRead IsolationLevel = "REPEATABLE READ"
- // IsolationLevelSerializable provides the highest isolation level.
- IsolationLevelSerializable IsolationLevel = "SERIALIZABLE"
-)
-
-// TransactionConfig represents the complete transaction configuration.
-type TransactionConfig struct {
- Mode TransactionMode
- Isolation IsolationLevel
-}
-
-// GetDefaultTransactionMode returns the default transaction mode.
-// All engines default to "on" (transactional) for safety and backward compatibility.
-// Users can explicitly set "-- txn-mode = off" when needed for engines with limited transactional DDL support.
-func GetDefaultTransactionMode() TransactionMode {
- // All engines default to "on" for safety and backward compatibility
- return TransactionModeOn
-}
diff --git a/backend/common/audit.go b/backend/component/audit/audit.go
similarity index 94%
rename from backend/common/audit.go
rename to backend/component/audit/audit.go
index ef300cd456..b259cef528 100644
--- a/backend/common/audit.go
+++ b/backend/component/audit/audit.go
@@ -1,5 +1,5 @@
-//nolint:revive
-package common
+// Package audit records audit events and their request metadata.
+package audit
import (
"context"
@@ -8,6 +8,7 @@ import (
"net/http"
"time"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
@@ -32,9 +33,9 @@ const (
AuditMethodMCPConsentApprove = "/bytebase.mcp.Consent/Approve"
)
-// AuditLogWriter inserts one audit row. The v1 audit interceptor and the doors
+// LogWriter inserts one audit row. The v1 audit interceptor and the doors
// outside the connect chains write through it.
-type AuditLogWriter interface {
+type LogWriter interface {
CreateAuditLog(ctx context.Context, workspace string, payload *storepb.AuditLog) error
}
@@ -52,7 +53,7 @@ type AuditLogWriter interface {
// refusal into an admission, so the caller gets no error to act on. The stdout
// mirror does NOT depend on the insert — a metadata-database failure is when
// losing the row from both surfaces would matter most.
-func RecordOutOfBandAudit(ctx context.Context, writer AuditLogWriter, mirrorToStdout bool, workspace string, row *storepb.AuditLog) {
+func RecordOutOfBandAudit(ctx context.Context, writer LogWriter, mirrorToStdout bool, workspace string, row *storepb.AuditLog) {
row.Severity = storepb.AuditLog_WARNING
// WithoutCancel so the row survives a client hanging up on its own refusal,
@@ -140,7 +141,7 @@ func LogAuditToStdout(ctx context.Context, p *storepb.AuditLog) {
// Request is already redacted for sensitive data by getRequestString()
if p.Request != "" {
request := p.Request
- if truncated, wasTruncated := TruncateString(p.Request, maxAuditPayloadChars); wasTruncated {
+ if truncated, wasTruncated := common.TruncateString(p.Request, maxAuditPayloadChars); wasTruncated {
request = truncated + "...[truncated]"
}
attrs = append(attrs, slog.String("request", request))
@@ -150,7 +151,7 @@ func LogAuditToStdout(ctx context.Context, p *storepb.AuditLog) {
// Response is already redacted for sensitive data by getResponseString()
if p.Response != "" {
response := p.Response
- if truncated, wasTruncated := TruncateString(p.Response, maxAuditPayloadChars); wasTruncated {
+ if truncated, wasTruncated := common.TruncateString(p.Response, maxAuditPayloadChars); wasTruncated {
response = truncated + "...[truncated]"
}
attrs = append(attrs, slog.String("response", response))
diff --git a/backend/common/audit_test.go b/backend/component/audit/audit_test.go
similarity index 99%
rename from backend/common/audit_test.go
rename to backend/component/audit/audit_test.go
index a2a95356c3..73a9db8f39 100644
--- a/backend/common/audit_test.go
+++ b/backend/component/audit/audit_test.go
@@ -1,5 +1,4 @@
-//nolint:revive
-package common
+package audit
import (
"bytes"
diff --git a/backend/plugin/db/clickhouse/clickhouse.go b/backend/plugin/db/clickhouse/clickhouse.go
index 9eb8d76931..a7a61226c7 100644
--- a/backend/plugin/db/clickhouse/clickhouse.go
+++ b/backend/plugin/db/clickhouse/clickhouse.go
@@ -17,6 +17,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
"github.com/bytebase/bytebase/backend/plugin/parser/standard"
@@ -129,8 +130,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
singleSQLs, err := standard.SplitSQL(statement)
@@ -143,7 +144,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, singleSQLs, opts)
}
return d.executeInTransactionMode(ctx, singleSQLs, opts)
diff --git a/backend/plugin/db/cockroachdb/cockroachdb.go b/backend/plugin/db/cockroachdb/cockroachdb.go
index 1a59eab2a1..1aa46849e7 100644
--- a/backend/plugin/db/cockroachdb/cockroachdb.go
+++ b/backend/plugin/db/cockroachdb/cockroachdb.go
@@ -26,6 +26,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
crdbparser "github.com/bytebase/bytebase/backend/plugin/parser/cockroachdb"
@@ -249,8 +250,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
owner, err := d.GetCurrentDatabaseOwner(ctx)
@@ -302,7 +303,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
commands = tmpCommands
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, owner, statement, commands, nonTransactionAndSetRoleStmts, opts, isPlsql)
}
return d.executeInTransactionMode(ctx, owner, statement, commands, nonTransactionAndSetRoleStmts, opts, isPlsql)
diff --git a/backend/plugin/db/databricks/databricks.go b/backend/plugin/db/databricks/databricks.go
index 77ced400f6..80fb1b8740 100644
--- a/backend/plugin/db/databricks/databricks.go
+++ b/backend/plugin/db/databricks/databricks.go
@@ -14,8 +14,8 @@ import (
// Databricks SQL.
dbsql "github.com/databricks/databricks-sdk-go/service/sql"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -128,8 +128,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOpti
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
// Databricks has different transaction support based on the target:
@@ -143,7 +143,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, _ db.ExecuteOpti
// For transaction mode "on", we note that Databricks will handle transactionality
// at the operation level for supported operations (e.g., Delta table operations).
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
// Execute in auto-commit mode (default Databricks behavior)
_, err := d.QueryConn(ctx, nil, statement, db.QueryContext{})
return 0, err
diff --git a/backend/plugin/db/mssql/mssql.go b/backend/plugin/db/mssql/mssql.go
index b48dec4cc4..f4d8efc5f2 100644
--- a/backend/plugin/db/mssql/mssql.go
+++ b/backend/plugin/db/mssql/mssql.go
@@ -24,11 +24,11 @@ import (
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/durationpb"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
@@ -172,12 +172,12 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, statement, opts)
}
return d.executeInTransactionMode(ctx, statement, opts)
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.go
index e1cbe20347..58a2d876de 100644
--- a/backend/plugin/db/mysql/mysql.go
+++ b/backend/plugin/db/mysql/mysql.go
@@ -31,6 +31,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
@@ -410,8 +411,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
statement = cleanedStatement
// Apply default when transaction mode is not specified
- if transactionConfig.Mode == common.TransactionModeUnspecified {
- transactionConfig.Mode = common.GetDefaultTransactionMode()
+ if transactionConfig.Mode == transaction.ModeUnspecified {
+ transactionConfig.Mode = transaction.DefaultMode()
}
conn, err := d.db.Conn(ctx)
@@ -435,12 +436,12 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
// Validate isolation level for MySQL if specified
- if transactionConfig.Isolation != common.IsolationLevelDefault {
- validLevels := map[common.IsolationLevel]bool{
- common.IsolationLevelReadUncommitted: true,
- common.IsolationLevelReadCommitted: true,
- common.IsolationLevelRepeatableRead: true,
- common.IsolationLevelSerializable: true,
+ if transactionConfig.Isolation != transaction.IsolationLevelDefault {
+ validLevels := map[transaction.IsolationLevel]bool{
+ transaction.IsolationLevelReadUncommitted: true,
+ transaction.IsolationLevelReadCommitted: true,
+ transaction.IsolationLevelRepeatableRead: true,
+ transaction.IsolationLevelSerializable: true,
}
if !validLevels[transactionConfig.Isolation] {
return 0, errors.Errorf("invalid isolation level for MySQL: %s. Supported levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE", transactionConfig.Isolation)
@@ -448,14 +449,14 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
// Execute based on transaction mode
- if transactionConfig.Mode == common.TransactionModeOff {
+ if transactionConfig.Mode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, conn, commands, opts, connectionID)
}
return d.executeInTransactionMode(ctx, conn, commands, opts, connectionID, transactionConfig.Isolation)
}
// executeInTransactionMode executes statements within a single transaction
-func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions, connectionID string, isolationLevel common.IsolationLevel) (int64, error) {
+func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, commands []base.Statement, opts db.ExecuteOptions, connectionID string, isolationLevel transaction.IsolationLevel) (int64, error) {
var totalRowsAffected int64
if err := conn.Raw(func(driverConn any) error {
@@ -466,8 +467,8 @@ func (d *Driver) executeInTransactionMode(ctx context.Context, conn *sql.Conn, c
// Set isolation level if specified
txOptions := driver.TxOptions{}
- if isolationLevel != common.IsolationLevelDefault {
- txOptions.Isolation = driver.IsolationLevel(base.ConvertToSQLIsolation(isolationLevel))
+ if isolationLevel != transaction.IsolationLevelDefault {
+ txOptions.Isolation = driver.IsolationLevel(transaction.ToSQLIsolation(isolationLevel))
}
tx, err := txer.BeginTx(ctx, txOptions)
diff --git a/backend/plugin/db/oracle/oracle.go b/backend/plugin/db/oracle/oracle.go
index 4ac7098d63..7d55f84a9a 100644
--- a/backend/plugin/db/oracle/oracle.go
+++ b/backend/plugin/db/oracle/oracle.go
@@ -17,11 +17,11 @@ import (
goora "github.com/sijms/go-ora/v2"
"google.golang.org/protobuf/types/known/durationpb"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql"
@@ -113,8 +113,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
commands, err := buildExecuteCommands(statement)
@@ -132,7 +132,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
defer conn.Close()
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, conn, commands, opts)
}
return d.executeInTransactionMode(ctx, conn, commands, opts)
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index af39d1aafc..a5780295fe 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -28,6 +28,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
@@ -394,8 +395,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
owner, err := d.GetCurrentDatabaseOwner(ctx)
@@ -447,7 +448,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
// Execute based on transaction mode
var affectedRows int64
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
affectedRows, err = d.executeInAutoCommitMode(ctx, owner, statement, commands, nonTransactionAndSetRoleStmts, opts, isPlsql)
} else {
affectedRows, err = d.executeInTransactionMode(ctx, owner, statement, commands, nonTransactionAndSetRoleStmts, opts, isPlsql)
@@ -470,7 +471,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
opts.LogRetryInfo(err, i+1)
// Do retry.
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
affectedRows, err = d.executeInAutoCommitMode(ctx, owner, statement, commands, nonTransactionAndSetRoleStmts, opts, isPlsql)
} else {
affectedRows, err = d.executeInTransactionMode(ctx, owner, statement, commands, nonTransactionAndSetRoleStmts, opts, isPlsql)
diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.go
index 6e86a7165a..8a707f05dc 100644
--- a/backend/plugin/db/redshift/redshift.go
+++ b/backend/plugin/db/redshift/redshift.go
@@ -22,6 +22,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
redshiftparser "github.com/bytebase/bytebase/backend/plugin/parser/redshift"
@@ -172,8 +173,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
var commands []base.Statement
@@ -197,7 +198,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, commands, opts)
}
return d.executeInTransactionMode(ctx, commands, opts)
diff --git a/backend/plugin/db/snowflake/snowflake.go b/backend/plugin/db/snowflake/snowflake.go
index 2145101898..0965ba71d8 100644
--- a/backend/plugin/db/snowflake/snowflake.go
+++ b/backend/plugin/db/snowflake/snowflake.go
@@ -21,6 +21,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
@@ -241,12 +242,12 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, statement, opts)
}
return d.executeInTransactionMode(ctx, statement, opts)
diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.go
index 148f93a1da..5b3e395e9e 100644
--- a/backend/plugin/db/spanner/spanner.go
+++ b/backend/plugin/db/spanner/spanner.go
@@ -31,6 +31,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
@@ -169,8 +170,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
stmts, err := util.SanitizeSQL(statement)
@@ -194,7 +195,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, stmts, opts)
}
return d.executeInTransactionMode(ctx, stmts, opts)
diff --git a/backend/plugin/db/starrocks/starrocks.go b/backend/plugin/db/starrocks/starrocks.go
index a3a1a3844c..910b03b34a 100644
--- a/backend/plugin/db/starrocks/starrocks.go
+++ b/backend/plugin/db/starrocks/starrocks.go
@@ -24,6 +24,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
@@ -169,8 +170,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
// Only preprocess when DELIMITER directives are present; normal
@@ -190,7 +191,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
// Note: StarRocks is an OLAP database with limited transaction support.
// For DDL operations, transactions are not supported. For DML operations,
// StarRocks supports transactions within certain limitations.
- if transactionMode == common.TransactionModeOff || opts.CreateDatabase {
+ if transactionMode == transaction.ModeOff || opts.CreateDatabase {
return d.executeInAutoCommitMode(ctx, statement)
}
return d.executeInTransactionMode(ctx, statement, opts)
diff --git a/backend/plugin/db/tidb/tidb.go b/backend/plugin/db/tidb/tidb.go
index 5066982488..74b2182609 100644
--- a/backend/plugin/db/tidb/tidb.go
+++ b/backend/plugin/db/tidb/tidb.go
@@ -23,6 +23,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
"github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
@@ -199,8 +200,8 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
transactionMode := config.Mode
// Apply default when transaction mode is not specified
- if transactionMode == common.TransactionModeUnspecified {
- transactionMode = common.GetDefaultTransactionMode()
+ if transactionMode == transaction.ModeUnspecified {
+ transactionMode = transaction.DefaultMode()
}
conn, err := d.db.Conn(ctx)
@@ -224,7 +225,7 @@ func (d *Driver) Execute(ctx context.Context, statement string, opts db.ExecuteO
}
// Execute based on transaction mode
- if transactionMode == common.TransactionModeOff {
+ if transactionMode == transaction.ModeOff {
return d.executeInAutoCommitMode(ctx, conn, commands, opts, connectionID)
}
return d.executeInTransactionMode(ctx, conn, commands, opts, connectionID)
diff --git a/backend/plugin/db/transaction/config.go b/backend/plugin/db/transaction/config.go
new file mode 100644
index 0000000000..56a9ee9940
--- /dev/null
+++ b/backend/plugin/db/transaction/config.go
@@ -0,0 +1,61 @@
+// Package transaction defines transaction execution settings shared by database drivers.
+package transaction
+
+import "database/sql"
+
+// Mode represents the transaction execution mode for a migration script.
+type Mode string
+
+const (
+ // ModeOn wraps the script in a single transaction.
+ ModeOn Mode = "on"
+ // ModeOff executes the script's statements sequentially in auto-commit mode.
+ ModeOff Mode = "off"
+ // ModeUnspecified means no explicit mode was specified.
+ ModeUnspecified Mode = ""
+)
+
+// IsolationLevel represents the transaction isolation level.
+type IsolationLevel string
+
+const (
+ // IsolationLevelDefault uses the database's default isolation level.
+ IsolationLevelDefault IsolationLevel = ""
+ // IsolationLevelReadUncommitted allows dirty reads.
+ IsolationLevelReadUncommitted IsolationLevel = "READ UNCOMMITTED"
+ // IsolationLevelReadCommitted prevents dirty reads.
+ IsolationLevelReadCommitted IsolationLevel = "READ COMMITTED"
+ // IsolationLevelRepeatableRead prevents dirty reads and non-repeatable reads.
+ IsolationLevelRepeatableRead IsolationLevel = "REPEATABLE READ"
+ // IsolationLevelSerializable provides the highest isolation level.
+ IsolationLevelSerializable IsolationLevel = "SERIALIZABLE"
+)
+
+// Config represents the complete transaction configuration.
+type Config struct {
+ Mode Mode
+ Isolation IsolationLevel
+}
+
+// DefaultMode returns the default transaction mode.
+// All engines default to "on" (transactional) for safety and backward compatibility.
+// Users can explicitly set "-- txn-mode = off" when needed for engines with limited transactional DDL support.
+func DefaultMode() Mode {
+ return ModeOn
+}
+
+// ToSQLIsolation converts our IsolationLevel to database/sql.IsolationLevel
+func ToSQLIsolation(level IsolationLevel) sql.IsolationLevel {
+ switch level {
+ case IsolationLevelReadUncommitted:
+ return sql.LevelReadUncommitted
+ case IsolationLevelReadCommitted:
+ return sql.LevelReadCommitted
+ case IsolationLevelRepeatableRead:
+ return sql.LevelRepeatableRead
+ case IsolationLevelSerializable:
+ return sql.LevelSerializable
+ default:
+ return sql.LevelDefault
+ }
+}
diff --git a/backend/plugin/parser/base/transaction_mode.go b/backend/plugin/parser/base/transaction_mode.go
index e1d01fff33..4b840dc652 100644
--- a/backend/plugin/parser/base/transaction_mode.go
+++ b/backend/plugin/parser/base/transaction_mode.go
@@ -1,11 +1,10 @@
package base
import (
- "database/sql"
"regexp"
"strings"
- "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/db/transaction"
)
// Directive regex patterns
@@ -30,10 +29,10 @@ var (
// Directives can appear in any order within the top comment lines.
// Scanning stops at the first non-comment, non-empty line.
// Returns the transaction configuration and the SQL script without the directives.
-func ParseTransactionConfig(script string) (common.TransactionConfig, string) {
- config := common.TransactionConfig{
- Mode: common.TransactionModeUnspecified,
- Isolation: common.IsolationLevelDefault,
+func ParseTransactionConfig(script string) (transaction.Config, string) {
+ config := transaction.Config{
+ Mode: transaction.ModeUnspecified,
+ Isolation: transaction.IsolationLevelDefault,
}
lines := strings.Split(script, "\n")
@@ -60,7 +59,7 @@ func ParseTransactionConfig(script string) (common.TransactionConfig, string) {
// Check for transaction mode directive
if matches := txnModeDirectiveRegex.FindStringSubmatch(line); len(matches) == 2 {
mode := strings.ToLower(matches[1])
- config.Mode = common.TransactionMode(mode)
+ config.Mode = transaction.Mode(mode)
directiveLines[i] = true
continue
}
@@ -73,7 +72,7 @@ func ParseTransactionConfig(script string) (common.TransactionConfig, string) {
// Note: We set the value as-is here. Invalid values will be caught
// by the specific database driver during execution, allowing each
// database to validate according to its supported levels.
- config.Isolation = common.IsolationLevel(isolation)
+ config.Isolation = transaction.IsolationLevel(isolation)
directiveLines[i] = true
continue
}
@@ -93,22 +92,6 @@ func ParseTransactionConfig(script string) (common.TransactionConfig, string) {
return config, script
}
-// ConvertToSQLIsolation converts our IsolationLevel to database/sql.IsolationLevel
-func ConvertToSQLIsolation(level common.IsolationLevel) sql.IsolationLevel {
- switch level {
- case common.IsolationLevelReadUncommitted:
- return sql.LevelReadUncommitted
- case common.IsolationLevelReadCommitted:
- return sql.LevelReadCommitted
- case common.IsolationLevelRepeatableRead:
- return sql.LevelRepeatableRead
- case common.IsolationLevelSerializable:
- return sql.LevelSerializable
- default:
- return sql.LevelDefault
- }
-}
-
// CleanDirectives removes all Bytebase directive comments from a SQL statement.
// This includes: -- txn-mode, -- txn-isolation, -- ghost
// Use this before passing statements to external tools (like gh-ost) that may not handle directives.
diff --git a/docs/backend-common-audit.md b/docs/backend-common-audit.md
index 78096aaa9d..04d39514bb 100644
--- a/docs/backend-common-audit.md
+++ b/docs/backend-common-audit.md
@@ -7,8 +7,11 @@ The second migration moves the PostgreSQL socket-directory helper to
`resources/postgres`, prefix matching to a private server helper, ANTLR line
conversion to `plugin/parser/base`, and TiDB error-position conversion to a
private TiDB parser helper. A subsequent migration moves the Connect-specific
-parser-engine conversion into a private v1 helper. The remaining entries are
-proposals.
+parser-engine conversion into a private v1 helper. This migration moves
+transaction configuration and SQL isolation conversion to `plugin/db/transaction`, and audit recording,
+stdout formatting, and HTTP metadata helpers to `component/audit`. Protobuf
+sanitization remains unchanged pending a separate ownership decision. The
+remaining entries are proposals.
The root package mixes unrelated ownership: resource names, identity, request
context, audit transport, policy expressions, SQL execution, and generic helpers.
@@ -35,11 +38,11 @@ necessarily existing files or packages.
| `Obfuscate`, `Unobfuscate` | Private helpers in `store` | All production uses are persisted instance credential encoding in `store/instance.go`. Preserve the stored encoding exactly. |
| `HasPrefixes` | Private helper in `server` | Only `server_frontend_routes.go` calls it. |
| Live position conversions in `common/position.go` | `plugin/parser/base/position.go`; TiDB-only conversion local to `plugin/parser/tidb` | Parser base already owns position mapping. Advisor implementations consume the ANTLR line conversion. |
-| Transaction types and default mode in `common/engine.go` | `plugin/parser/base/transaction_mode.go` | This file already parses directives and converts isolation levels; drivers consume the result. Avoid putting types in `plugin/db` and making parser base depend on drivers. |
+| Transaction types and default mode in `common/engine.go` | `plugin/db/transaction` (implemented) | Execution settings and SQL isolation conversion are driver-owned. The directive parser imports this leaf package without depending on the full driver package. |
| `ConvertToParserEngine` (completed) | Private helper in `api/v1` | Only v1 calls it, and it returns a Connect error. The move preserves the mapping and error behavior. |
| Audit callback keys, setters, getters, `PermissionDeniedError` | Private helpers in `api/v1` | These coordinate v1 interceptors and handlers; no production callers outside v1 were found. |
| `GetQueryExportFactors` and its traversal | Private helpers in `component/review` | The only production caller is review evaluation. It should consume the shared IAM expression definitions described below. |
-| `SanitizeUTF8Message` and reflection traversal | Private helpers in `plugin/db/oracle` | Only Oracle metadata sync calls it. Keep string sanitization shared because v1 uses it too. |
+| `SanitizeUTF8Message` and reflection traversal | Deferred | Oracle metadata sync is the current caller, but the implementation handles arbitrary protobuf messages and can serve other engines. Decide shared ownership separately. |
| `GetPostgresSocketDir` | `resources/postgres` | Callers are embedded PostgreSQL setup, server startup, and the self-hosted sample manager. |
| `ReleaseMode` | `component/config` | `Profile.Mode` is the central configuration field; the package currently imports common only for this type. |
| Build-tagged `IsDev` | Local build-tagged files in `plugin/db/cosmosdb` | Cosmos DB is its only production consumer. Keep build-time mode distinct from runtime `Profile.Mode`. |
@@ -52,7 +55,7 @@ necessarily existing files or packages.
| Principal email conventions, account suffixes, password/email/phone validation, directory-sync token hashing | A leaf `component/iam/identity` package | Used across APIs, identity providers, recovery, and store. Must not import the parent IAM manager or store. Separate files by concept, rather than another util file. |
| `AuthContext`, `DelegatedGrant`, authorization resource types | `api/auth` | They describe transport authentication and authorization. These can live with the existing auth implementation, unlike the cross-component workspace context. |
| Workspace/user context keys and workspace accessor | A leaf `common/requestcontext` package | Review and parser-context components also consume request identity. Keep it independent of `api/auth`, store, and Connect. Use typed accessors and private keys as a separate interface cleanup. |
-| `audit.go` | `component/audit` | Shared by v1, MCP, and OAuth2. Preserve the narrow writer interface, detached bounded write, denial severity, stdout behavior, and caller-IP semantics. Keep HTTP metadata helpers with the audit module initially. |
+| `audit.go` | `component/audit` (implemented) | Shared by v1, MCP, and OAuth2. Preserves the narrow writer interface, detached bounded write, denial severity, stdout behavior, and caller-IP semantics. HTTP metadata helpers remain with the audit module. |
| Approval CEL definitions/validation and `risk.go` | `component/review` | This is review policy. Keep validation and runtime evaluation on the same definitions; map validation errors to Connect at the v1 caller. |
| IAM CEL definitions, member validation, `EvalBindingCondition` | A leaf `component/iam/condition` package | Store and utils call the evaluator. Moving it into the parent IAM package creates a cycle because IAM imports store and utils. Preserve partial-evaluation behavior. |
| Masking CEL definitions/validation | Initially private files in `api/v1` | All current external consumers are v1. The existing `component/masker` implements value masking, which is a different responsibility from policy-expression evaluation. |
@@ -119,4 +122,8 @@ only if that package is moved later.
The initial audit used source and caller inspection. The first migration passes
tests for common, store, query builder, v1, webhook adapters, and the webhook
manager, plus the server build. Repository-wide lint reports existing findings
-on code already present at HEAD. Remaining proposed package graphs are not yet compiler-verified.
+on code already present at HEAD. The transaction and audit migration passes tests
+for common, audit, parser base, v1, MCP, OAuth2, and all 12 affected driver packages, plus the
+server build. Repository-wide lint reports 45 findings in 22 untouched files
+with golangci-lint v2.13.2 built using Go 1.27.1; none are in the migrated code.
+Remaining proposed package graphs are not yet compiler-verified.
diff --git a/docs/design/audit-payload-redaction-from-proto.md b/docs/design/audit-payload-redaction-from-proto.md
index 1e29c9fcf0..a09c165a93 100644
--- a/docs/design/audit-payload-redaction-from-proto.md
+++ b/docs/design/audit-payload-redaction-from-proto.md
@@ -164,7 +164,7 @@ streaming rows reach redaction only through those two: `auditConnectStreamingCon
is the only streaming RPC, is audited, and its response carries every row of an admin-mode query, so
moving the walk up into `WrapUnary` — where the `service_data` and permission-refusal plumbing
lives — silently drops streaming redaction. One end-to-end assertion on the `Send` path is
-required: streaming persistence is otherwise exercised through a fake `common.AuditLogWriter`,
+required: streaming persistence is otherwise exercised through a fake `audit.LogWriter`,
which bypasses the real insert.
A **plan** per message type, built from the descriptor on first use and cached by