Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mysql): preserve routine/trigger/event session context on declarative apply (BYT-9832) (#20769)
h3n4lb7212d696e10
diff --git a/backend/plugin/schema/mysql/sdl_migration_omni.go b/backend/plugin/schema/mysql/sdl_migration_omni.goindex 63b7d6bb6b..1e6c2f1aa7 100644--- a/backend/plugin/schema/mysql/sdl_migration_omni.go+++ b/backend/plugin/schema/mysql/sdl_migration_omni.go@@ -21,7 +21,7 @@ func init() {// MySQL-only for now: OceanBase is intentionally NOT registered pending validation// against a live OceanBase oracle — an executable-but-unvalidated registration would// route OB declarative releases through untested diff/drop-advice paths.- schema.RegisterDiffSDLMigration(storepb.Engine_MYSQL, mysqlDiffSDLMigration)+ schema.RegisterDiffSDLMigration(storepb.Engine_MYSQL, mysqlDiffSDLMigrationWithContext)schema.RegisterSDLDropAdvices(storepb.Engine_MYSQL, mysqlSDLDropAdvices)// Metadata-to-metadata diffs (SQLService.DiffMetadata, changelog-target DiffSchema)// keep the pre-SDL legacy differ/generator path (mirroring pg's@@ -142,11 +142,21 @@ func explicitDefaultsForTimestampSet(version catalog.Version) string {// target MySQL version, so Diff (which reads the version off the `to` catalog) and// GenerateMigration reproduce that version's stored form — a 5.7 schema no longer// phantom-diffs on the utf8mb4 default collation and never emits utf8mb4_0900_ai_ci.-func buildMigrationPlan(sourceText, targetText string, version catalog.Version) (*catalog.MigrationPlan, error) {+//+// sessionCtx, when non-nil, carries the per-object session context (sql_mode/charset/+// collation, and event time_zone) of the SOURCE schema. It is stamped onto the source+// (from) catalog via ApplySessionContext AFTER load and BEFORE Diff — the source is where+// the OLD/From objects live, and their original context is what a recreate must restore.+// The context is deliberately not part of any object's declarative identity, so it never+// causes a phantom diff; it is consumed only by the generator's recreate framing.+func buildMigrationPlan(sourceText, targetText string, version catalog.Version, sessionCtx *schema.SDLSessionContextMap) (*catalog.MigrationPlan, error) {from, err := loadCatalog(sourceText, version)if err != nil {return nil, errors.Wrap(err, "failed to load source schema")}+ if sessionCtx != nil {+ from.ApplySessionContext(toCatalogSessionContextMap(sessionCtx))+ }to, err := loadCatalog(targetText, version)if err != nil {return nil, errors.Wrap(err, "failed to load target schema")@@ -158,14 +168,48 @@ func buildMigrationPlan(sourceText, targetText string, version catalog.Version)return catalog.GenerateMigration(from, to, diff), nil}-// mysqlDiffSDLMigration is the registered SDL diff entry point: two schema texts plus-// the target server version in, migration SQL out. engineVersion is the synced+// toCatalogSessionContextMap converts the engine-neutral schema.SDLSessionContextMap+// (built by the generic SDL layer from synced metadata) into omni's+// catalog.SessionContextMap. The two are field-for-field identical; this keeps the omni+// dependency confined to the MySQL package.+func toCatalogSessionContextMap(m *schema.SDLSessionContextMap) catalog.SessionContextMap {+ conv := func(src map[string]schema.SDLSessionContext) map[string]catalog.SessionContext {+ if len(src) == 0 {+ return nil+ }+ dst := make(map[string]catalog.SessionContext, len(src))+ for name, c := range src {+ dst[name] = catalog.SessionContext{+ SQLMode: c.SQLMode,+ CharacterSetClient: c.CharacterSetClient,+ CollationConnection: c.CollationConnection,+ TimeZone: c.TimeZone,+ }+ }+ return dst+ }+ return catalog.SessionContextMap{+ Functions: conv(m.Functions),+ Procedures: conv(m.Procedures),+ Triggers: conv(m.Triggers),+ Events: conv(m.Events),+ }+}++// mysqlDiffSDLMigrationWithContext is the registered SDL diff entry point: two schema+// texts plus the target server version in, migration SQL out. engineVersion is the synced// database's version string (e.g. "5.7.25"), threaded by the release/DiffSchema paths// so the omni catalog selects the version-correct normalizer (a 5.7 database is// canonicalized as 5.7 — utf8mb4_general_ci default, integer display widths — instead// of the 8.0 stored form); an empty or unparseable value falls back to 8.0.-func mysqlDiffSDLMigration(sourceSDL, targetSDL, engineVersion string) (string, error) {- plan, err := buildMigrationPlan(sourceSDL, targetSDL, mysqlVersionFor(engineVersion))+//+// sessionCtx carries the source schema's per-object session context so a routine/trigger/+// event recreate is re-emitted under its ORIGINAL sql_mode/charset/collation (event+// time_zone too). It is nil for the SDL↔SDL and metadata↔metadata callers that have no+// synced metadata to source it from; only the live rollout (schema.SDLMigration) supplies+// it.+func mysqlDiffSDLMigrationWithContext(sourceSDL, targetSDL, engineVersion string, sessionCtx *schema.SDLSessionContextMap) (string, error) {+ plan, err := buildMigrationPlan(sourceSDL, targetSDL, mysqlVersionFor(engineVersion), sessionCtx)if err != nil {return "", err}@@ -175,6 +219,14 @@ func mysqlDiffSDLMigration(sourceSDL, targetSDL, engineVersion string) (string,return stripDatabaseContext(plan.SQL()), nil}+// mysqlDiffSDLMigration is the bare (no session context) 3-arg form: two schema texts plus+// the target version, migration SQL out. It is the in-package convenience used by the SDL+// test suites — a recreate through it carries no session framing, matching the old+// behavior. Production callers reach the context-aware form via schema.SDLMigration.+func mysqlDiffSDLMigration(sourceSDL, targetSDL, engineVersion string) (string, error) {+ return mysqlDiffSDLMigrationWithContext(sourceSDL, targetSDL, engineVersion, nil)+}+// mysqlDiffMetadataMigration computes migration SQL between two metadata states via the// LEGACY differ/generator (schema.GetDatabaseSchemaDiff + schema.GenerateMigration) —// exactly the pre-SDL behavior of schema.DiffMigration for MySQL. Metadata-based@@ -285,7 +337,11 @@ func mysqlSDLDropAdvices(userSDLText string, currentSchema *model.DatabaseMetadaif err != nil {return nil, err}- plan, err := buildMigrationPlan(sourceSDL, userSDLText, mysqlVersionFor(engineVersion))+ // Session context is intentionally not applied here: drop/replace classification+ // depends only on the op TYPES (OpDrop*/OpCreate*), which are identical with or+ // without the recreate framing. Applying context would only add SET wrappers to+ // op.SQL, changing nothing the advice walker inspects.+ plan, err := buildMigrationPlan(sourceSDL, userSDLText, mysqlVersionFor(engineVersion), nil)if err != nil {return nil, err}diff --git a/backend/plugin/schema/mysql/sdl_session_context_live_test.go b/backend/plugin/schema/mysql/sdl_session_context_live_test.gonew file mode 100644index 0000000000..01f3df5adb--- /dev/null+++ b/backend/plugin/schema/mysql/sdl_session_context_live_test.go@@ -0,0 +1,368 @@+package mysql++import (+ "context"+ "database/sql"+ "fmt"+ "strings"+ "testing"++ mysqldriver "github.com/go-sql-driver/mysql"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+ "github.com/bytebase/bytebase/backend/store/model"+)++// End-to-end proof for BYT-9832 STAGE 2 (bytebase wiring) against the LIVE 5.7 (:13307)+// and 8.0 (:13306) oracles. It drives the REAL production entry point,+// schema.SDLMigration (the function database_migrate_executor.go's diff() calls), so the+// whole path exercised is: seed object under a distinctive session context → sync to+// metadata (which captures sql_mode/charset/collation, and event time_zone) →+// schema.SDLMigration(userSDL, syncedMetadata, version) → the generated migration is+// APPLIED on a deploy session whose DEFAULT sql_mode differs → read back+// information_schema to prove the ORIGINAL context survived the recreate/ALTER.+//+// Without the STAGE 2 wiring (buildSDLSessionContextMap + ApplySessionContext on the+// source catalog) the object comes back stamped with the deploy session's mode — which is+// exactly the regression these assertions catch.++// origRoutineMode is a non-default sql_mode whose semantics visibly differ from the deploy+// default: PIPES_AS_CONCAT makes `||` string concat (not OR), NO_BACKSLASH_ESCAPES changes+// escaping. A bare recreate under the deploy default would silently lose both.+const origRoutineMode = "PIPES_AS_CONCAT,NO_BACKSLASH_ESCAPES"++// deploySessionMode is the (different) sql_mode the migration is applied under, standing in+// for a deploy connection whose session default is not the object's authoring mode.+const deploySessionMode = "STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"++// openLiveDB opens a raw *sql.DB against a live oracle with multi-statement support so a+// framed migration (SET …; CREATE …; SET …) runs as one script on one session, and returns+// it with a cleanup. It connects plaintext (no tls param), the equivalent of the mysql+// CLI's --ssl-mode=DISABLED that 5.7 needs.+func openLiveDB(t *testing.T, srv liveServer, database string) *sql.DB {+ t.Helper()+ cfg := mysqldriver.NewConfig()+ cfg.User = "root"+ cfg.Passwd = liveOraclePassword+ cfg.Net = "tcp"+ cfg.Addr = fmt.Sprintf("%s:%s", srv.host, srv.port)+ cfg.DBName = database+ cfg.MultiStatements = true+ cfg.AllowNativePasswords = true+ sqlDB, err := sql.Open("mysql", cfg.FormatDSN())+ require.NoError(t, err, "[%s] sql.Open", srv.name)+ t.Cleanup(func() { _ = sqlDB.Close() })+ return sqlDB+}++// scConn grabs a dedicated single connection (so session-variable state is stable across+// statements) and registers its cleanup.+func scConn(ctx context.Context, t *testing.T, sqlDB *sql.DB, srv liveServer) *sql.Conn {+ t.Helper()+ conn, err := sqlDB.Conn(ctx)+ require.NoError(t, err, "[%s] grab conn", srv.name)+ t.Cleanup(func() { _ = conn.Close() })+ return conn+}++// newSCDatabase creates a fresh database on srv and registers cleanup, returning its name.+func newSCDatabase(ctx context.Context, t *testing.T, srv liveServer, prefix string) string {+ t.Helper()+ dbName := fmt.Sprintf("%s_%s", prefix, strings.ReplaceAll(uuid.New().String(), "-", "_"))+ admin := openLiveDB(t, srv, "")+ _, err := admin.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", dbName))+ require.NoError(t, err, "[%s] create db", srv.name)+ t.Cleanup(func() {+ c := openLiveDB(t, srv, "")+ _, _ = c.ExecContext(ctx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName))+ })+ return dbName+}++// syncDBToMetadata syncs dbName on srv to the model.DatabaseMetadata the production release+// path feeds schema.SDLMigration — the value whose per-object sql_mode/charset/collation+// (and event time_zone) STAGE 2 threads into the diff.+func syncDBToMetadata(ctx context.Context, t *testing.T, srv liveServer, dbName string) *model.DatabaseMetadata {+ t.Helper()+ driver, err := createLiveMySQLDriver(ctx, srv, dbName)+ require.NoError(t, err, "[%s] open driver", srv.name)+ defer driver.Close(ctx)+ metadata, err := driver.SyncDBSchema(ctx)+ require.NoError(t, err, "[%s] sync", srv.name)+ return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_MYSQL, true)+}++// applyMigrationUnderDeployMode runs the generated migration on a session whose sql_mode is+// first set to deploySessionMode, proving the framing (not the ambient session) governs the+// stored context.+func applyMigrationUnderDeployMode(ctx context.Context, t *testing.T, conn *sql.Conn, srv, migrationSQL string) {+ t.Helper()+ _, err := conn.ExecContext(ctx, "SET SESSION sql_mode = "+quoteLiteral(deploySessionMode))+ require.NoError(t, err, "[%s] set deploy mode", srv)+ _, err = conn.ExecContext(ctx, migrationSQL)+ require.NoError(t, err, "[%s] APPLY FAILED:\n%s", srv, migrationSQL)+}++// quoteLiteral single-quotes a MySQL string literal for the test's own SET statements+// (the omni generator does its own quoting inside the migration).+func quoteLiteral(s string) string {+ return "'" + strings.ReplaceAll(s, "'", "''") + "'"+}++func execUnderMode(ctx context.Context, t *testing.T, conn *sql.Conn, srv liveServer, sqlMode, timeZone string, stmts ...string) {+ t.Helper()+ _, err := conn.ExecContext(ctx, "SET SESSION sql_mode = "+quoteLiteral(sqlMode))+ require.NoError(t, err, "[%s] set authoring sql_mode", srv.name)+ if timeZone != "" {+ _, err = conn.ExecContext(ctx, "SET SESSION time_zone = "+quoteLiteral(timeZone))+ require.NoError(t, err, "[%s] set authoring time_zone", srv.name)+ }+ for _, s := range stmts {+ _, err = conn.ExecContext(ctx, s)+ require.NoError(t, err, "[%s] seed stmt %q", srv.name, s)+ }+}++func readRoutineSQLMode(ctx context.Context, t *testing.T, conn *sql.Conn, dbName, name string) string {+ t.Helper()+ var mode sql.NullString+ err := conn.QueryRowContext(ctx,+ "SELECT SQL_MODE FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA=? AND ROUTINE_NAME=?",+ dbName, name).Scan(&mode)+ require.NoError(t, err, "read routine sql_mode")+ return mode.String+}++func readTriggerSQLMode(ctx context.Context, t *testing.T, conn *sql.Conn, dbName, name string) string {+ t.Helper()+ var mode sql.NullString+ err := conn.QueryRowContext(ctx,+ "SELECT SQL_MODE FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA=? AND TRIGGER_NAME=?",+ dbName, name).Scan(&mode)+ require.NoError(t, err, "read trigger sql_mode")+ return mode.String+}++func readEventModeTZ(ctx context.Context, t *testing.T, conn *sql.Conn, dbName, name string) (string, string) {+ t.Helper()+ var mode, tz sql.NullString+ err := conn.QueryRowContext(ctx,+ "SELECT SQL_MODE, TIME_ZONE FROM information_schema.EVENTS WHERE EVENT_SCHEMA=? AND EVENT_NAME=?",+ dbName, name).Scan(&mode, &tz)+ require.NoError(t, err, "read event sql_mode/time_zone")+ return mode.String, tz.String+}++// TestSDLSessionContextRoutineLive proves a routine whose BODY changes is re-emitted under+// its ORIGINAL sql_mode across the whole production wiring (schema.SDLMigration).+//+//nolint:tparallel+func TestSDLSessionContextRoutineLive(t *testing.T) {+ skipUnlessLiveOracle(t)+ ctx := context.Background()++ for _, srv := range liveServers {+ srv := srv+ t.Run(srv.name, func(t *testing.T) {+ dbName := newSCDatabase(ctx, t, srv, "sc_rtn")+ conn := scConn(ctx, t, openLiveDB(t, srv, dbName), srv)++ // Seed the function under the ORIGINAL mode.+ execUnderMode(ctx, t, conn, srv, origRoutineMode, "",+ "CREATE FUNCTION f(a INT) RETURNS INT DETERMINISTIC RETURN a + 1")++ // This is the exact value the release path hands schema.SDLMigration.+ metadata := syncDBToMetadata(ctx, t, srv, dbName)++ // Desired SDL: same routine, body edited (a + 2). Bare — carries no session framing.+ userSDL := "CREATE FUNCTION f(a INT) RETURNS INT DETERMINISTIC RETURN a + 2;"+ migrationSQL, err := schema.SDLMigration(storepb.Engine_MYSQL, userSDL, metadata, srv.version)+ require.NoError(t, err)+ require.NotEmpty(t, migrationSQL, "[%s] expected a recreate migration", srv.name)+ t.Logf("[%s] routine migration:\n%s", srv.name, migrationSQL)+ // The framing must be present (proof STAGE 2 wired the context through).+ require.Contains(t, migrationSQL, "SET sql_mode",+ "[%s] migration lacks sql_mode framing:\n%s", srv.name, migrationSQL)++ applyMigrationUnderDeployMode(ctx, t, conn, srv.name, migrationSQL)++ got := readRoutineSQLMode(ctx, t, conn, dbName, "f")+ require.Equal(t, origRoutineMode, got,+ "[%s] routine sql_mode not preserved across recreate\nmigration:\n%s", srv.name, migrationSQL)+ })+ }+}++// TestSDLSessionContextTriggerLive proves a trigger whose BODY changes is re-emitted under+// its ORIGINAL sql_mode across schema.SDLMigration.+//+//nolint:tparallel+func TestSDLSessionContextTriggerLive(t *testing.T) {+ skipUnlessLiveOracle(t)+ ctx := context.Background()++ for _, srv := range liveServers {+ srv := srv+ t.Run(srv.name, func(t *testing.T) {+ dbName := newSCDatabase(ctx, t, srv, "sc_trg")+ conn := scConn(ctx, t, openLiveDB(t, srv, dbName), srv)++ base := []string{+ "CREATE TABLE t (id INT PRIMARY KEY, val INT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",+ "CREATE TABLE audit (id INT PRIMARY KEY AUTO_INCREMENT, tid INT, oldv INT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",+ }+ // Tables under the deploy mode; the TRIGGER under the ORIGINAL mode.+ execUnderMode(ctx, t, conn, srv, deploySessionMode, "", base...)+ execUnderMode(ctx, t, conn, srv, origRoutineMode, "",+ "CREATE TRIGGER t_audit AFTER UPDATE ON t FOR EACH ROW BEGIN INSERT INTO audit (tid, oldv) VALUES (NEW.id, OLD.val); END")++ metadata := syncDBToMetadata(ctx, t, srv, dbName)++ userSDL := strings.Join([]string{+ "CREATE TABLE t (id INT PRIMARY KEY, val INT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",+ "CREATE TABLE audit (id INT PRIMARY KEY AUTO_INCREMENT, tid INT, oldv INT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",+ "CREATE TRIGGER t_audit AFTER UPDATE ON t FOR EACH ROW BEGIN INSERT INTO audit (tid, oldv) VALUES (NEW.id, OLD.val + 1); END;",+ }, "\n")+ migrationSQL, err := schema.SDLMigration(storepb.Engine_MYSQL, userSDL, metadata, srv.version)+ require.NoError(t, err)+ require.NotEmpty(t, migrationSQL, "[%s] expected a trigger recreate migration", srv.name)+ t.Logf("[%s] trigger migration:\n%s", srv.name, migrationSQL)+ require.Contains(t, migrationSQL, "SET sql_mode",+ "[%s] trigger migration lacks sql_mode framing:\n%s", srv.name, migrationSQL)++ applyMigrationUnderDeployMode(ctx, t, conn, srv.name, migrationSQL)++ got := readTriggerSQLMode(ctx, t, conn, dbName, "t_audit")+ require.Equal(t, origRoutineMode, got,+ "[%s] trigger sql_mode not preserved across recreate\nmigration:\n%s", srv.name, migrationSQL)+ })+ }+}++// TestSDLSessionContextEventLive proves an event whose BODY changes preserves both sql_mode+// and the ORIGINAL time_zone across schema.SDLMigration. The event modify path is an ALTER+// EVENT … DO (which empirically re-stamps sql_mode from the session), so a bare apply would+// silently lose the original mode — the case the framing exists for.+//+//nolint:tparallel+func TestSDLSessionContextEventLive(t *testing.T) {+ skipUnlessLiveOracle(t)+ ctx := context.Background()++ const origEventMode = "PIPES_AS_CONCAT"+ const origTZ = "+08:00"++ for _, srv := range liveServers {+ srv := srv+ t.Run(srv.name, func(t *testing.T) {+ dbName := newSCDatabase(ctx, t, srv, "sc_evt")+ conn := scConn(ctx, t, openLiveDB(t, srv, dbName), srv)++ // event_scheduler toggle may lack privilege; ignore its error only.+ if _, err := conn.ExecContext(ctx, "SET GLOBAL event_scheduler = OFF"); err != nil {+ t.Logf("[%s] event_scheduler off (ignored): %v", srv.name, err)+ }+ execUnderMode(ctx, t, conn, srv, origEventMode, origTZ,+ "CREATE EVENT e ON SCHEDULE EVERY 1 HOUR DISABLE DO SET @x = 1")++ metadata := syncDBToMetadata(ctx, t, srv, dbName)++ userSDL := "CREATE EVENT e ON SCHEDULE EVERY 1 HOUR DISABLE DO SET @x = 2;"+ migrationSQL, err := schema.SDLMigration(storepb.Engine_MYSQL, userSDL, metadata, srv.version)+ require.NoError(t, err)+ require.NotEmpty(t, migrationSQL, "[%s] expected an event modify migration", srv.name)+ t.Logf("[%s] event migration:\n%s", srv.name, migrationSQL)+ require.Contains(t, migrationSQL, "SET sql_mode",+ "[%s] event migration lacks sql_mode framing:\n%s", srv.name, migrationSQL)++ applyMigrationUnderDeployMode(ctx, t, conn, srv.name, migrationSQL)++ gotMode, gotTZ := readEventModeTZ(ctx, t, conn, dbName, "e")+ require.Equal(t, origEventMode, gotMode,+ "[%s] event sql_mode not preserved\nmigration:\n%s", srv.name, migrationSQL)+ require.Equal(t, origTZ, gotTZ,+ "[%s] event time_zone not preserved\nmigration:\n%s", srv.name, migrationSQL)+ })+ }+}++// TestSDLSessionContextNewObjectDefaultLive proves a routine ABSENT from the source (a+// first-time create) is emitted BARE — no session framing — so it adopts the server default+// mode. STAGE 2 must only preserve context for objects that already exist in the source.+//+//nolint:tparallel+func TestSDLSessionContextNewObjectDefaultLive(t *testing.T) {+ skipUnlessLiveOracle(t)+ ctx := context.Background()++ for _, srv := range liveServers {+ srv := srv+ t.Run(srv.name, func(t *testing.T) {+ dbName := newSCDatabase(ctx, t, srv, "sc_new")+ conn := scConn(ctx, t, openLiveDB(t, srv, dbName), srv)++ // Source has only a table; the routine is brand new in the desired SDL.+ execUnderMode(ctx, t, conn, srv, deploySessionMode, "",+ "CREATE TABLE t (id INT PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")++ metadata := syncDBToMetadata(ctx, t, srv, dbName)++ userSDL := strings.Join([]string{+ "CREATE TABLE t (id INT PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",+ "CREATE FUNCTION g(a INT) RETURNS INT DETERMINISTIC RETURN a + 5;",+ }, "\n")+ migrationSQL, err := schema.SDLMigration(storepb.Engine_MYSQL, userSDL, metadata, srv.version)+ require.NoError(t, err)+ require.NotEmpty(t, migrationSQL, "[%s] expected a create migration", srv.name)+ t.Logf("[%s] new-object migration:\n%s", srv.name, migrationSQL)+ // A first-time create must NOT be wrapped in session framing.+ require.NotContains(t, migrationSQL, "SET sql_mode",+ "[%s] first-time create should be bare (no session framing):\n%s", srv.name, migrationSQL)++ // applyMigrationUnderDeployMode runs it on a session whose sql_mode is+ // deploySessionMode; a bare CREATE therefore captures that mode. This proves a+ // brand-new object adopts the deploy session default (no preserved context).+ applyMigrationUnderDeployMode(ctx, t, conn, srv.name, migrationSQL)++ got := readRoutineSQLMode(ctx, t, conn, dbName, "g")+ require.Equal(t, deploySessionMode, got,+ "[%s] new routine should adopt the deploy session mode, got %q", srv.name, got)+ })+ }+}++// TestSDLSessionContextNoChurnLive proves that an identical source and desired routine —+// same body, with the source's session context carried in from synced metadata — produces+// NO migration. The session context is deliberately excluded from declarative identity, so+// a mode-only carry must never manufacture a phantom recreate.+//+//nolint:tparallel+func TestSDLSessionContextNoChurnLive(t *testing.T) {+ skipUnlessLiveOracle(t)+ ctx := context.Background()++ for _, srv := range liveServers {+ srv := srv+ t.Run(srv.name, func(t *testing.T) {+ dbName := newSCDatabase(ctx, t, srv, "sc_noop")+ conn := scConn(ctx, t, openLiveDB(t, srv, dbName), srv)++ execUnderMode(ctx, t, conn, srv, origRoutineMode, "",+ "CREATE FUNCTION f(a INT) RETURNS INT DETERMINISTIC RETURN a + 1")++ metadata := syncDBToMetadata(ctx, t, srv, dbName)++ // Desired SDL == the dumped current object (same body). No change intended.+ userSDL, err := schema.MetadataToSDL(storepb.Engine_MYSQL, metadata)+ require.NoError(t, err)++ migrationSQL, err := schema.SDLMigration(storepb.Engine_MYSQL, userSDL, metadata, srv.version)+ require.NoError(t, err)+ require.Empty(t, migrationSQL,+ "[%s] identical schema (context carried) must produce no migration, got:\n%s", srv.name, migrationSQL)+ })+ }+}diff --git a/backend/plugin/schema/pg/sdl_migration_omni.go b/backend/plugin/schema/pg/sdl_migration_omni.goindex 7005939cf4..cbd8fb2408 100644--- a/backend/plugin/schema/pg/sdl_migration_omni.go+++ b/backend/plugin/schema/pg/sdl_migration_omni.go@@ -63,7 +63,9 @@ func buildMigrationPlan(sourceText, targetText string) (*catalog.MigrationPlan,// pgDiffSDLMigration is the core migration function: two schema texts in, migration SQL// out. The engine version is unused: PostgreSQL canonicalizes identically across versions.-func pgDiffSDLMigration(sourceSDL, targetSDL string, _ string) (string, error) {+// The session-context map is unused: PostgreSQL routines carry no per-object session+// context (it is a MySQL-only concern), so the recreate is always bare.+func pgDiffSDLMigration(sourceSDL, targetSDL string, _ string, _ *schema.SDLSessionContextMap) (string, error) {plan, err := buildMigrationPlan(sourceSDL, targetSDL)if err != nil {return "", errdiff --git a/backend/plugin/schema/schema.go b/backend/plugin/schema/schema.goindex 78f5d52289..3680ba9ecb 100644--- a/backend/plugin/schema/schema.go+++ b/backend/plugin/schema/schema.go@@ -2,6 +2,7 @@ package schemaimport ("fmt"+ "strings""sync""github.com/pkg/errors"@@ -52,7 +53,15 @@ type sdlDropAdvices func(userSDLText string, currentSchema *model.DatabaseMetada// use it to select the correct normalizer, and engines that do not (PostgreSQL) take// `_ string`. An empty/unparseable version must fall back to the engine's default// stored form.-type diffSDLMigration func(sourceSDL, targetSDL, engineVersion string) (string, error)+//+// sessionCtx is the per-object session context (sql_mode / charset / collation, and+// time_zone for events) captured on the SOURCE (current) schema. The declarative SDL+// text is bare (a clean export carries no `SET sql_mode` framing), so the context that a+// routine/trigger/event must be re-created under enters out-of-band here. Only MySQL+// consumes it (to wrap recreates in a save/restore of the OLD object's context); other+// engines have no session context and take a nil-safe `_`. A nil map means "no context"+// (bare recreates) — the metadata↔metadata and SDL↔SDL callers pass nil.+type diffSDLMigration func(sourceSDL, targetSDL, engineVersion string, sessionCtx *SDLSessionContextMap) (string, error)type diffMetadataMigration func(oldSchema, newSchema *model.DatabaseMetadata) (string, error)type walkThrough func(*model.DatabaseMetadata, []base.AST) *storepb.Advicetype walkThroughWithContext func(WalkThroughContext, *model.DatabaseMetadata, []base.AST) *storepb.Advice@@ -272,18 +281,112 @@ func GetSDLDiff(engine storepb.Engine, currentSDLText, previousUserSDLText strinreturn f(currentSDLText, previousUserSDLText, currentSchema)}+// SDLSessionContext is the session state a routine/trigger/event was created under, as+// stored in the synced metadata: sql_mode, character_set_client, collation_connection,+// and — events only — the session time_zone. It is the engine-neutral mirror of omni's+// catalog.SessionContext (the MySQL SDL implementation converts to it); other engines+// never populate it. Empty strings are legal and preserved verbatim.+type SDLSessionContext struct {+ SQLMode string+ CharacterSetClient string+ CollationConnection string+ TimeZone string // events only+}++// SDLSessionContextMap carries per-object session context for a whole schema, keyed by+// lower-cased object name within each object kind. It is the out-of-band structured input+// bytebase hands to the MySQL SDL diff so a declarative recreate re-emits an object under+// its ORIGINAL session context (the bare SDL text carries none). A nil map or a missing+// entry simply leaves that object without context (a bare recreate). This lives in the+// engine-neutral schema layer so SDLMigration can build it from synced metadata without+// importing any engine's omni catalog; only the MySQL implementation consumes it.+type SDLSessionContextMap struct {+ Functions map[string]SDLSessionContext+ Procedures map[string]SDLSessionContext+ Triggers map[string]SDLSessionContext+ Events map[string]SDLSessionContext+}++// buildSDLSessionContextMap extracts per-object session context from the synced current+// schema. MySQL stores functions/procedures/events on the schema and triggers on their+// owning table; a routine/trigger carries sql_mode/charset/collation and an event also+// carries time_zone. Keys are lower-cased object names (matching omni's identity folding).+// Returns nil only when there is no metadata to read; otherwise it returns an allocated+// map (with empty submaps when the schema has no such objects), which the consumer applies+// as "no context for any object". Engines without session context (their metadata leaves+// these fields empty) still produce a map, but only MySQL's diff consumes it.+func buildSDLSessionContextMap(currentSchema *model.DatabaseMetadata) *SDLSessionContextMap {+ if currentSchema == nil {+ return nil+ }+ proto := currentSchema.GetProto()+ if proto == nil {+ return nil+ }+ m := &SDLSessionContextMap{+ Functions: map[string]SDLSessionContext{},+ Procedures: map[string]SDLSessionContext{},+ Triggers: map[string]SDLSessionContext{},+ Events: map[string]SDLSessionContext{},+ }+ for _, sm := range proto.GetSchemas() {+ for _, fn := range sm.GetFunctions() {+ m.Functions[strings.ToLower(fn.GetName())] = SDLSessionContext{+ SQLMode: fn.GetSqlMode(),+ CharacterSetClient: fn.GetCharacterSetClient(),+ CollationConnection: fn.GetCollationConnection(),+ }+ }+ for _, proc := range sm.GetProcedures() {+ m.Procedures[strings.ToLower(proc.GetName())] = SDLSessionContext{+ SQLMode: proc.GetSqlMode(),+ CharacterSetClient: proc.GetCharacterSetClient(),+ CollationConnection: proc.GetCollationConnection(),+ }+ }+ for _, event := range sm.GetEvents() {+ m.Events[strings.ToLower(event.GetName())] = SDLSessionContext{+ SQLMode: event.GetSqlMode(),+ CharacterSetClient: event.GetCharacterSetClient(),+ CollationConnection: event.GetCollationConnection(),+ TimeZone: event.GetTimeZone(),+ }+ }+ for _, table := range sm.GetTables() {+ for _, trigger := range table.GetTriggers() {+ // Keyed by lower-cased name to match omni's trigger identity, which is+ // itself lower-folded (catalog stores triggers as map[string]*Trigger by+ // toLower(name)). Triggers whose names differ only by case therefore+ // collapse to one entry — an inherited omni limitation, not introduced+ // here; MySQL trigger names can be case-sensitive on lower_case_table_names=0.+ m.Triggers[strings.ToLower(trigger.GetName())] = SDLSessionContext{+ SQLMode: trigger.GetSqlMode(),+ CharacterSetClient: trigger.GetCharacterSetClient(),+ CollationConnection: trigger.GetCollationConnection(),+ }+ }+ }+ }+ return m+}+// SDLMigration computes the migration SQL from a user-provided SDL text and the// current database schema. It converts the current metadata to SDL, then diffs// against the user SDL. engineVersion is the target server's version string (e.g.// "5.7.25"); for engines that canonicalize per version (MySQL) it selects the// version-correct normalizer. An empty/unparseable version falls back to the// engine default, and engines without a version-aware path ignore it entirely.+//+// The per-object session context (sql_mode/charset/collation, and event time_zone) is+// extracted from currentSchema and threaded to the diff so MySQL re-creates a routine/+// trigger/event under its ORIGINAL session context — the bare SDL source carries none.+// Other engines ignore it.func SDLMigration(engine storepb.Engine, userSDLText string, currentSchema *model.DatabaseMetadata, engineVersion string) (string, error) {sourceSDL, err := MetadataToSDL(engine, currentSchema)if err != nil {return "", errors.Wrap(err, "failed to convert current schema to SDL")}- return DiffSDLMigration(engine, sourceSDL, userSDLText, engineVersion)+ return diffSDLMigrationWithContext(engine, sourceSDL, userSDLText, engineVersion, buildSDLSessionContextMap(currentSchema))}func RegisterSDLDropAdvices(engine storepb.Engine, f sdlDropAdvices) {@@ -373,12 +476,24 @@ func RegisterDiffSDLMigration(engine storepb.Engine, f diffSDLMigration) {// target server's version string, threaded to engines that canonicalize per version// (MySQL) and ignored by the rest (PostgreSQL); pass "" when no version is known to get// the engine's default stored form.+//+// This SDL↔SDL entry point carries no per-object session context (there is no synced+// metadata to source it from), so a MySQL recreate through this path is bare. The+// live rollout uses SDLMigration, which builds the context from the current schema.func DiffSDLMigration(engine storepb.Engine, sourceSDL, targetSDL, engineVersion string) (string, error) {+ return diffSDLMigrationWithContext(engine, sourceSDL, targetSDL, engineVersion, nil)+}++// diffSDLMigrationWithContext is DiffSDLMigration plus the optional per-object session+// context threaded to the engine's registered diff. sessionCtx is nil for the callers+// without synced metadata (SDL↔SDL DiffSchema, metadata↔metadata DiffMigration); only+// SDLMigration supplies it.+func diffSDLMigrationWithContext(engine storepb.Engine, sourceSDL, targetSDL, engineVersion string, sessionCtx *SDLSessionContextMap) (string, error) {f, ok := diffSDLMigrations[engine]if !ok {return "", errors.Errorf("engine %s is not supported for SDL diff migration", engine)}- return f(sourceSDL, targetSDL, engineVersion)+ return f(sourceSDL, targetSDL, engineVersion, sessionCtx)}func RegisterGetMultiFileDatabaseDefinition(engine storepb.Engine, f getMultiFileDatabaseDefinition) {diff --git a/go.mod b/go.modindex ab8de58b43..cf05a961b5 100644--- a/go.mod+++ b/go.mod@@ -33,7 +33,7 @@ require (github.com/bmatcuk/doublestar/v4 v4.10.0github.com/bytebase/gomongo v0.0.0-20260510192859-8526a440b352github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0- github.com/bytebase/omni v0.0.0-20260703065817-5796ec6b6257+ github.com/bytebase/omni v0.0.0-20260708021240-171d8abc36d7github.com/caarlos0/env/v11 v11.4.1github.com/cenkalti/backoff/v5 v5.0.3github.com/cockroachdb/cockroachdb-parser v0.25.2diff --git a/go.sum b/go.sumindex 4aa98e2f46..c7eb6d0f59 100644--- a/go.sum+++ b/go.sum@@ -250,8 +250,8 @@ github.com/bytebase/gomongo v0.0.0-20260510192859-8526a440b352 h1:3sC5pdvJ7bNAhRgithub.com/bytebase/gomongo v0.0.0-20260510192859-8526a440b352/go.mod h1:eyWrxE51HCbjGIChvty/mYaNcAroXshnIiR6SIqlxfY=github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0 h1:bJ8NSf2K+pccl5m/wuu97fiYjDwpJH6IzURAq/3XA2U=github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0/go.mod h1:BEWMfiZtqshdmulKJcIsWb45MUaEvDO4CROcgi8dfFg=-github.com/bytebase/omni v0.0.0-20260703065817-5796ec6b6257 h1:yY9Z9DkND9Bo75ejzoYlXRjpEWhFrjNufa1BmjEqLpU=-github.com/bytebase/omni v0.0.0-20260703065817-5796ec6b6257/go.mod h1:Gp5RN3FM07f9/FFOTZCeu8duTAIMeuinkjjBCrs2Dw4=+github.com/bytebase/omni v0.0.0-20260708021240-171d8abc36d7 h1:VcZGq9HvaVTo0rBTdr1CMjjuARYHSkv2TnlE5Y06Ikk=+github.com/bytebase/omni v0.0.0-20260708021240-171d8abc36d7/go.mod h1:Gp5RN3FM07f9/FFOTZCeu8duTAIMeuinkjjBCrs2Dw4=github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767 h1:YuR5G3LcxpO5ScSTA+Kdirxg9RW4TRc/v1t7N2Hfmbw=github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=github.com/bytebase/pkcs8 v0.0.0-20240612095628-fcd0a7484c94 h1:6PNsuNmSqCuR8Z616uQLzDIvujWCFsKzeVc3ECmVubk=