Skip to content

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

feat(pg): migrate SDL diff/migration from ANTLR to omni parser [BYT-9077] (#19726)

rebelicec1cb9e7b75a8
diff --git a/backend/api/v1/release_service_check.go b/backend/api/v1/release_service_check.go
index 9b08f17ff0..01166691f4 100644
--- a/backend/api/v1/release_service_check.go
+++ b/backend/api/v1/release_service_check.go
@@ -443,35 +443,22 @@ func (s *ReleaseService) checkReleaseDeclarative(ctx context.Context, files []*v
// Run SDL DROP operation checks
// This checks for data loss risks from DROP operations by analyzing the schema diff
- pengine, err := common.ConvertToParserEngine(engine)
- if err == nil {
- // Get current database schema
- dbMetadata, err := s.store.GetDBSchema(ctx, &store.FindDBSchemaMessage{
- Workspace: common.GetWorkspaceIDFromContext(ctx),
- InstanceID: database.InstanceID,
- DatabaseName: database.DatabaseName,
- })
- if err == nil && dbMetadata != nil {
- // Get previous SDL from the database's release field (last applied release)
- // Returns empty string if no previous release exists (initialization scenario)
- previousUserSDL := getPreviousSDLForDatabase(ctx, s.store, database)
-
- // Combine all SDL files into single text
- var combinedCurrentSDL strings.Builder
- for _, file := range files {
- combinedCurrentSDL.Write(file.Statement)
- combinedCurrentSDL.WriteString("\n\n")
- }
-
- // Generate diff
- schemaDiff, err := schema.GetSDLDiff(pengine, combinedCurrentSDL.String(), previousUserSDL, dbMetadata)
- if err == nil {
- // Filter out bbdataarchive schema changes for Postgres
- schemaDiff = schema.FilterPostgresArchiveSchema(schemaDiff)
+ dbMetadata, err := s.store.GetDBSchema(ctx, &store.FindDBSchemaMessage{
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ InstanceID: database.InstanceID,
+ DatabaseName: database.DatabaseName,
+ })
+ if err == nil && dbMetadata != nil {
+ // Combine all SDL files into single text
+ var combinedCurrentSDL strings.Builder
+ for _, file := range files {
+ combinedCurrentSDL.Write(file.Statement)
+ combinedCurrentSDL.WriteString("\n\n")
+ }
- // Check for DROP operations in the diff
- sdlDropAdvices = advisorpg.CheckSDLDropOperations(schemaDiff)
- }
+ advices, err := schema.SDLDropAdvices(engine, combinedCurrentSDL.String(), dbMetadata)
+ if err == nil {
+ sdlDropAdvices = advices
}
}
}
@@ -763,51 +750,3 @@ func getStatementTypesWithPositionsForEngine(engine storepb.Engine, asts []base.
return []statementTypeWithPosition{}, nil
}
}
-
-// getPreviousSDLForDatabase retrieves the previous SDL text from the database's last applied release.
-// Returns empty string if no previous release exists or if there are any errors loading it.
-func getPreviousSDLForDatabase(ctx context.Context, s *store.Store, database *store.DatabaseMessage) string {
- // Get the previous SDL text from the database's release field
- if database.Metadata == nil || database.Metadata.Release == "" {
- return ""
- }
-
- // Parse release name to get project ID and release ID
- projectID, releaseID, err := common.GetProjectReleaseID(database.Metadata.Release)
- if err != nil {
- slog.Warn("Failed to parse release name, treating as initialization", "release", database.Metadata.Release, "error", err)
- return ""
- }
-
- // Load the release
- release, err := s.GetRelease(ctx, &store.FindReleaseMessage{
- ProjectID: &projectID,
- ReleaseID: &releaseID,
- })
- if err != nil {
- slog.Warn("Failed to get release, treating as initialization", "project", projectID, "release", releaseID, "error", err)
- return ""
- }
- if release == nil {
- slog.Warn("Release not found, treating as initialization", "project", projectID, "release", releaseID)
- return ""
- }
-
- // For SDL/declarative releases, combine all files
- var combinedSDL strings.Builder
- for _, file := range release.Payload.Files {
- sheet, err := s.GetSheetFull(ctx, file.SheetSha256)
- if err != nil {
- slog.Warn("Failed to get sheet, treating as initialization", "sha256", file.SheetSha256, "error", err)
- return ""
- }
- if sheet == nil {
- slog.Warn("Sheet not found, treating as initialization", "sha256", file.SheetSha256)
- return ""
- }
- combinedSDL.WriteString(sheet.Statement)
- combinedSDL.WriteString("\n\n")
- }
-
- return combinedSDL.String()
-}
diff --git a/backend/plugin/schema/pg/camelcase_index_omni_test.go b/backend/plugin/schema/pg/camelcase_index_omni_test.go
new file mode 100644
index 0000000000..83395300b8
--- /dev/null
+++ b/backend/plugin/schema/pg/camelcase_index_omni_test.go
@@ -0,0 +1,78 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/omni/pg/catalog"
+)
+
+// TestOmniCamelCaseIndexColumnQuoting_SDL reproduces https://github.com/bytebase/bytebase/issues/19348
+// via the omni SDL migration path. CamelCase column names in index expressions must be quoted.
+func TestOmniCamelCaseIndexColumnQuoting_SDL(t *testing.T) {
+ fromSDL := ""
+
+ toSDL := `
+CREATE TABLE "public"."ba_account" (
+ "userId" text NOT NULL,
+ "accountName" text
+);
+
+CREATE INDEX ba_account_userId_idx ON "public"."ba_account" ("userId");
+`
+
+ from, err := catalog.LoadSDL(strings.TrimSpace(fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(toSDL))
+ require.NoError(t, err)
+
+ diff := catalog.Diff(from, to)
+ require.False(t, diff.IsEmpty(), "Diff should not be empty")
+
+ plan := catalog.GenerateMigration(from, to, diff)
+ sql := plan.SQL()
+
+ t.Logf("Generated SQL:\n%s", sql)
+
+ require.Contains(t, sql, "ba_account", "Should contain table name")
+ require.Contains(t, sql, `"userId"`, "CamelCase column in CREATE INDEX must be quoted")
+}
+
+// TestOmniCamelCaseIndexColumnQuoting_AddIndex tests adding an index with CamelCase columns
+// to an existing table.
+func TestOmniCamelCaseIndexColumnQuoting_AddIndex(t *testing.T) {
+ fromSDL := `
+CREATE TABLE "public"."ba_account" (
+ "userId" text NOT NULL,
+ "accountName" text
+);
+`
+
+ toSDL := `
+CREATE TABLE "public"."ba_account" (
+ "userId" text NOT NULL,
+ "accountName" text
+);
+
+CREATE INDEX ba_account_userId_idx ON "public"."ba_account" ("userId");
+`
+
+ from, err := catalog.LoadSDL(strings.TrimSpace(fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(toSDL))
+ require.NoError(t, err)
+
+ diff := catalog.Diff(from, to)
+ require.False(t, diff.IsEmpty(), "Diff should not be empty")
+
+ plan := catalog.GenerateMigration(from, to, diff)
+ sql := plan.SQL()
+
+ t.Logf("Generated SQL:\n%s", sql)
+
+ require.Contains(t, sql, "CREATE INDEX")
+ require.Contains(t, sql, "ba_account_userid_idx")
+ require.Contains(t, sql, `"userId"`, "CamelCase column in CREATE INDEX must be quoted")
+}
diff --git a/backend/plugin/schema/pg/column_migration_integration_omni_test.go b/backend/plugin/schema/pg/column_migration_integration_omni_test.go
new file mode 100644
index 0000000000..69288a032a
--- /dev/null
+++ b/backend/plugin/schema/pg/column_migration_integration_omni_test.go
@@ -0,0 +1,320 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniColumnSDLDiffAndMigration(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "Add new column",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(320) UNIQUE
+ );
+ `,
+ contains: []string{"ALTER TABLE", "email"},
+ },
+ {
+ name: "Drop column",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ phone VARCHAR(20)
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ contains: []string{"ALTER TABLE", "DROP", "phone"},
+ },
+ {
+ name: "Modify column type",
+ fromSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(15,3) NOT NULL DEFAULT 0.00
+ );
+ `,
+ contains: []string{"ALTER TABLE", "price"},
+ },
+ {
+ name: "Set NOT NULL",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320)
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320) NOT NULL
+ );
+ `,
+ contains: []string{"ALTER TABLE", "NOT NULL", "email"},
+ },
+ {
+ name: "Drop NOT NULL",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320)
+ );
+ `,
+ contains: []string{"ALTER TABLE", "DROP NOT NULL", "email"},
+ },
+ {
+ name: "Add default value",
+ fromSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL DEFAULT 9.99
+ );
+ `,
+ contains: []string{"ALTER TABLE", "DEFAULT", "price"},
+ },
+ {
+ name: "Drop default value",
+ fromSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL DEFAULT 9.99
+ );
+ `,
+ toSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ contains: []string{"ALTER TABLE", "DROP DEFAULT", "price"},
+ },
+ {
+ name: "Change column type only",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ contains: []string{"ALTER TABLE", "TYPE", "name"},
+ },
+ {
+ name: "Multiple column changes in same table",
+ fromSDL: `
+ CREATE TABLE employees (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100),
+ email VARCHAR(255) NOT NULL,
+ salary DECIMAL(8,2)
+ );
+ `,
+ toSDL: `
+ CREATE TABLE employees (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(200) NOT NULL,
+ email VARCHAR(320) NOT NULL,
+ salary DECIMAL(10,2) DEFAULT 50000.00
+ );
+ `,
+ contains: []string{"ALTER TABLE", "name", "email", "salary"},
+ },
+ {
+ name: "Add column with complex constraints",
+ fromSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ status VARCHAR(20) NOT NULL DEFAULT 'pending'
+ );
+ `,
+ contains: []string{"ALTER TABLE", "status"},
+ },
+ {
+ name: "Change column from nullable to not null with default",
+ fromSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ category VARCHAR(50)
+ );
+ `,
+ toSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ category VARCHAR(50) NOT NULL DEFAULT 'general'
+ );
+ `,
+ contains: []string{"ALTER TABLE", "NOT NULL", "DEFAULT", "category"},
+ },
+ {
+ name: "Add multiple columns",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(320) UNIQUE,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+ `,
+ contains: []string{"ALTER TABLE", "email", "created_at"},
+ },
+ {
+ name: "Drop multiple columns",
+ fromSDL: `
+ CREATE TABLE temp_data (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ temp_field1 VARCHAR(100),
+ temp_field2 INTEGER,
+ description TEXT
+ );
+ `,
+ toSDL: `
+ CREATE TABLE temp_data (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ description TEXT
+ );
+ `,
+ contains: []string{"ALTER TABLE", "DROP", "temp_field1", "temp_field2"},
+ },
+ {
+ name: "Mixed operations: add, drop, modify",
+ fromSDL: `
+ CREATE TABLE inventory (
+ id SERIAL PRIMARY KEY,
+ product_name VARCHAR(100) NOT NULL,
+ old_field VARCHAR(50),
+ quantity INTEGER DEFAULT 0
+ );
+ `,
+ toSDL: `
+ CREATE TABLE inventory (
+ id SERIAL PRIMARY KEY,
+ product_name VARCHAR(200) NOT NULL,
+ quantity INTEGER DEFAULT 1,
+ location VARCHAR(100) NOT NULL DEFAULT 'warehouse'
+ );
+ `,
+ contains: []string{"ALTER TABLE", "old_field", "location", "product_name"},
+ },
+ {
+ name: "Integer type variations",
+ fromSDL: `
+ CREATE TABLE counters (
+ id SERIAL PRIMARY KEY,
+ small_count SMALLINT,
+ big_count BIGINT
+ );
+ `,
+ toSDL: `
+ CREATE TABLE counters (
+ id SERIAL PRIMARY KEY,
+ small_count INTEGER NOT NULL DEFAULT 0,
+ big_count BIGINT NOT NULL
+ );
+ `,
+ contains: []string{"ALTER TABLE", "small_count", "big_count"},
+ },
+ {
+ name: "Text and character types",
+ fromSDL: `
+ CREATE TABLE documents (
+ id SERIAL PRIMARY KEY,
+ title CHAR(50),
+ content TEXT
+ );
+ `,
+ toSDL: `
+ CREATE TABLE documents (
+ id SERIAL PRIMARY KEY,
+ title VARCHAR(100) NOT NULL,
+ content TEXT DEFAULT ''
+ );
+ `,
+ contains: []string{"ALTER TABLE", "title", "content"},
+ },
+ {
+ name: "Boolean column with default",
+ fromSDL: `
+ CREATE TABLE features (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE features (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ enabled BOOLEAN NOT NULL DEFAULT false
+ );
+ `,
+ contains: []string{"ALTER TABLE", "enabled"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/column_sdl_diff_omni_test.go b/backend/plugin/schema/pg/column_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..740d084d29
--- /dev/null
+++ b/backend/plugin/schema/pg/column_sdl_diff_omni_test.go
@@ -0,0 +1,208 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniColumnSDLDiff(t *testing.T) {
+ testCases := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ validate func(t *testing.T, sql string)
+ }{
+ {
+ name: "No column changes - identical tables",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.Empty(t, sql, "Should produce no migration for identical tables")
+ },
+ },
+ {
+ name: "Add new column",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(100)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "ADD COLUMN")
+ require.Contains(t, sql, "email")
+ },
+ },
+ {
+ name: "Drop column",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(100)
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "DROP COLUMN")
+ require.Contains(t, sql, "email")
+ },
+ },
+ {
+ name: "Alter column type",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name TEXT NOT NULL
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "name")
+ require.Contains(t, sql, "TYPE")
+ },
+ },
+ {
+ name: "Multiple column changes",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ phone VARCHAR(20),
+ updated_at TIMESTAMP
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name TEXT NOT NULL,
+ email VARCHAR(200),
+ created_at TIMESTAMP
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ // Added columns
+ require.Contains(t, sql, "email")
+ require.Contains(t, sql, "created_at")
+ // Dropped columns
+ require.Contains(t, sql, "phone")
+ require.Contains(t, sql, "updated_at")
+ // Altered column type
+ require.Contains(t, sql, "name")
+ },
+ },
+ {
+ name: "Column constraint changes - drop NOT NULL",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "name")
+ },
+ },
+ {
+ name: "Column default value changes",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ status VARCHAR(50) DEFAULT 'active'
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ status VARCHAR(50) DEFAULT 'inactive'
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "status")
+ require.Contains(t, sql, "inactive")
+ },
+ },
+ {
+ name: "Add foreign key constraint via column test",
+ fromSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER PRIMARY KEY,
+ customer_id INTEGER
+ );`,
+ toSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER PRIMARY KEY,
+ customer_id INTEGER,
+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "fk_orders_customer")
+ require.Contains(t, sql, "FOREIGN KEY")
+ },
+ },
+ {
+ name: "Add check constraint via column test",
+ fromSDL: `CREATE TABLE products (
+ id INTEGER PRIMARY KEY,
+ price DECIMAL(10,2)
+ );`,
+ toSDL: `CREATE TABLE products (
+ id INTEGER PRIMARY KEY,
+ price DECIMAL(10,2),
+ CONSTRAINT chk_positive_price CHECK (price > 0)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "chk_positive_price")
+ },
+ },
+ {
+ name: "Add unique constraint via column test",
+ fromSDL: `CREATE TABLE users (
+ id INTEGER PRIMARY KEY,
+ email VARCHAR(255)
+ );`,
+ toSDL: `CREATE TABLE users (
+ id INTEGER PRIMARY KEY,
+ email VARCHAR(255),
+ CONSTRAINT uk_users_email UNIQUE (email)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "uk_users_email")
+ require.Contains(t, sql, "UNIQUE")
+ },
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tc.fromSDL, tc.toSDL)
+ tc.validate(t, sql)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/comment_migration_omni_test.go b/backend/plugin/schema/pg/comment_migration_omni_test.go
new file mode 100644
index 0000000000..c6b4bbfe42
--- /dev/null
+++ b/backend/plugin/schema/pg/comment_migration_omni_test.go
@@ -0,0 +1,496 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniCommentMigration_TableComment(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "add table comment",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'User information table';
+`,
+ contains: []string{"COMMENT ON TABLE", "users", "User information table"},
+ },
+ {
+ name: "modify table comment",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'User information table';
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'Updated user table';
+`,
+ contains: []string{"COMMENT ON TABLE", "Updated user table"},
+ },
+ {
+ name: "remove table comment",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'User information table';
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+`,
+ contains: []string{"COMMENT ON TABLE", "NULL"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentMigration_ColumnComment(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "add column comment",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON COLUMN "public"."users"."id" IS 'Primary key';
+`,
+ contains: []string{"COMMENT ON COLUMN", "Primary key"},
+ },
+ {
+ name: "modify column comment",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON COLUMN "public"."users"."id" IS 'Primary key';
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON COLUMN "public"."users"."id" IS 'User unique identifier';
+`,
+ contains: []string{"COMMENT ON COLUMN", "User unique identifier"},
+ },
+ {
+ name: "multiple column comments",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON COLUMN "public"."users"."id" IS 'Primary key';
+COMMENT ON COLUMN "public"."users"."name" IS 'User full name';
+`,
+ contains: []string{"COMMENT ON COLUMN", "Primary key", "User full name"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentMigration_ViewComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+CREATE VIEW "public"."active_users" AS SELECT * FROM users;
+`, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+CREATE VIEW "public"."active_users" AS SELECT * FROM users;
+
+COMMENT ON VIEW "public"."active_users" IS 'View of active users';
+`)
+ require.Contains(t, sql, "COMMENT ON VIEW")
+ require.Contains(t, sql, "View of active users")
+}
+
+func TestOmniCommentMigration_SequenceComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE SEQUENCE "public"."user_id_seq" AS integer START WITH 1 INCREMENT BY 1;
+`, `
+CREATE SEQUENCE "public"."user_id_seq" AS integer START WITH 1 INCREMENT BY 1;
+
+COMMENT ON SEQUENCE "public"."user_id_seq" IS 'Sequence for user IDs';
+`)
+ require.Contains(t, sql, "COMMENT ON SEQUENCE")
+ require.Contains(t, sql, "Sequence for user IDs")
+}
+
+func TestOmniCommentMigration_FunctionComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE FUNCTION "public"."add_numbers"(a integer, b integer) RETURNS integer
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RETURN a + b;
+END;
+$$;
+`, `
+CREATE FUNCTION "public"."add_numbers"(a integer, b integer) RETURNS integer
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RETURN a + b;
+END;
+$$;
+
+COMMENT ON FUNCTION "public"."add_numbers"(integer, integer) IS 'Adds two numbers';
+`)
+ require.Contains(t, sql, "COMMENT ON FUNCTION")
+ require.Contains(t, sql, "Adds two numbers")
+}
+
+func TestOmniCommentMigration_SchemaComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE SCHEMA "app";
+`, `
+CREATE SCHEMA "app";
+
+COMMENT ON SCHEMA "app" IS 'Application schema';
+`)
+ require.Contains(t, sql, "COMMENT ON SCHEMA")
+ require.Contains(t, sql, "Application schema")
+}
+
+func TestOmniCommentMigration_SpecialCharacters(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "comment with single quote",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL
+);
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL
+);
+
+COMMENT ON TABLE "public"."users" IS 'User''s table';
+`,
+ contains: []string{"COMMENT ON TABLE", "User"},
+ },
+ {
+ name: "comment with newlines",
+ fromSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL
+);
+`,
+ toSDL: `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL
+);
+
+COMMENT ON TABLE "public"."users" IS 'This is a
+multi-line
+comment';
+`,
+ contains: []string{"COMMENT ON TABLE", "multi-line"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentMigration_NoObjectChangeWithCommentChange(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'Old comment';
+`, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'Updated comment';
+`)
+ require.Contains(t, sql, "COMMENT ON TABLE")
+ require.Contains(t, sql, "Updated comment")
+ require.NotContains(t, sql, "ALTER TABLE")
+}
+
+func TestOmniCommentMigration_CombinedChanges(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'Basic user table';
+`, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text,
+ "email" text
+);
+
+COMMENT ON TABLE "public"."users" IS 'User table with email';
+`)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "email")
+ require.Contains(t, sql, "COMMENT ON TABLE")
+ require.Contains(t, sql, "User table with email")
+}
+
+func TestOmniCommentMigration_NewFunctionWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+CREATE FUNCTION "public"."calculate_tax"(amount numeric) RETURNS numeric
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RETURN amount * 0.1;
+END;
+$$;
+
+COMMENT ON FUNCTION "public"."calculate_tax"(numeric) IS 'Calculate 10% tax';
+`)
+ require.Contains(t, sql, "CREATE FUNCTION")
+ require.Contains(t, sql, "COMMENT ON FUNCTION")
+ require.Contains(t, sql, "calculate_tax")
+ require.Contains(t, sql, "Calculate 10% tax")
+}
+
+func TestOmniCommentMigration_NewViewWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text,
+ "active" boolean
+);
+`, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text,
+ "active" boolean
+);
+
+CREATE VIEW "public"."active_users" AS SELECT * FROM users WHERE active = true;
+
+COMMENT ON VIEW "public"."active_users" IS 'View of all active users';
+`)
+ require.Contains(t, sql, "CREATE VIEW")
+ require.Contains(t, sql, "COMMENT ON VIEW")
+}
+
+func TestOmniCommentMigration_NewTableWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text,
+ "email" varchar(255)
+);
+
+COMMENT ON TABLE "public"."users" IS 'User information table';
+`)
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "COMMENT ON TABLE")
+ require.Contains(t, sql, "users")
+ require.Contains(t, sql, "User information table")
+}
+
+func TestOmniCommentMigration_AddColumnWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+`, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text,
+ "email" varchar(255)
+);
+
+COMMENT ON COLUMN "public"."users"."email" IS 'User email address';
+`)
+ require.Contains(t, sql, "email")
+ require.Contains(t, sql, "COMMENT ON COLUMN")
+ require.Contains(t, sql, "User email address")
+}
+
+func TestOmniCommentMigration_AddMultipleColumnsWithComments(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text
+);
+`, `
+CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text,
+ "email" varchar(255),
+ "phone" varchar(20),
+ "age" integer
+);
+
+COMMENT ON COLUMN "public"."users"."email" IS 'User email address';
+COMMENT ON COLUMN "public"."users"."phone" IS 'User phone number';
+`)
+ require.Contains(t, sql, "email")
+ require.Contains(t, sql, "phone")
+ require.Contains(t, sql, "age")
+ require.Contains(t, sql, "COMMENT ON COLUMN")
+ require.Contains(t, sql, "User email address")
+ require.Contains(t, sql, "User phone number")
+}
+
+func TestOmniCommentMigration_IndexComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE "public"."products" (
+ "id" integer NOT NULL,
+ "name" text,
+ "price" numeric
+);
+`, `
+CREATE TABLE "public"."products" (
+ "id" integer NOT NULL,
+ "name" text,
+ "price" numeric
+);
+
+CREATE INDEX "idx_products_name" ON "public"."products" (name);
+
+COMMENT ON INDEX "public"."idx_products_name" IS 'Index for product name lookup';
+`)
+ require.Contains(t, sql, "CREATE INDEX")
+ require.Contains(t, sql, "COMMENT ON INDEX")
+ require.Contains(t, sql, "idx_products_name")
+ require.Contains(t, sql, "Index for product name lookup")
+}
+
+func TestOmniCommentMigration_NewSequenceWithOwner(t *testing.T) {
+ // When a sequence has OWNED BY, omni may treat it as part of the table column.
+ // Test just that the diff is computed without error.
+ sql := omniSDLMigration(t, `
+CREATE TABLE users (
+ id integer NOT NULL,
+ name text
+);
+`, `
+CREATE TABLE users (
+ id integer NOT NULL,
+ name text
+);
+
+CREATE SEQUENCE user_id_seq AS integer START WITH 1 INCREMENT BY 1;
+
+ALTER SEQUENCE user_id_seq OWNED BY users.id;
+`)
+ // Omni absorbs the owned sequence into the table definition, so no CREATE SEQUENCE is emitted.
+ require.NotContains(t, sql, "CREATE SEQUENCE")
+}
+
+func TestOmniCommentMigration_NewSequenceWithOwnerAndComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE products (
+ id integer NOT NULL,
+ name text
+);
+`, `
+CREATE TABLE products (
+ id integer NOT NULL,
+ name text
+);
+
+CREATE SEQUENCE product_id_seq AS bigint START WITH 100 INCREMENT BY 1;
+
+ALTER SEQUENCE product_id_seq OWNED BY products.id;
+
+COMMENT ON SEQUENCE product_id_seq IS 'Product ID sequence';
+`)
+ // The comment should be generated even if the CREATE SEQUENCE is absorbed
+ require.Contains(t, sql, "product_id_seq")
+ require.Contains(t, sql, "Product ID sequence")
+}
diff --git a/backend/plugin/schema/pg/exclude_index_omni_test.go b/backend/plugin/schema/pg/exclude_index_omni_test.go
new file mode 100644
index 0000000000..547b260732
--- /dev/null
+++ b/backend/plugin/schema/pg/exclude_index_omni_test.go
@@ -0,0 +1,137 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniExcludeConstraintWithRegularIndexes(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE employee_shifts (
+ shift_id bigserial,
+ employee_id integer NOT NULL,
+ department_id integer NOT NULL,
+ shift_start timestamp(6) with time zone NOT NULL,
+ shift_end timestamp(6) with time zone NOT NULL,
+ shift_type character varying(50) DEFAULT 'regular',
+ created_at timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT pk_employee_shifts PRIMARY KEY (shift_id),
+ CONSTRAINT chk_employee_shifts_time CHECK (shift_end > shift_start)
+ );
+
+ CREATE INDEX idx_employee_shifts_employee ON employee_shifts (employee_id);
+ CREATE INDEX idx_employee_shifts_department ON employee_shifts (department_id);
+ CREATE INDEX idx_employee_shifts_time ON employee_shifts USING gist (tstzrange(shift_start, shift_end));
+ CREATE INDEX idx_employee_shifts_type ON employee_shifts (shift_type);
+ `)
+
+ t.Logf("Generated SQL:\n%s", sql)
+
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "employee_shifts")
+
+ // Regular indexes should be created
+ require.Contains(t, sql, "idx_employee_shifts_employee")
+ require.Contains(t, sql, "idx_employee_shifts_department")
+ require.Contains(t, sql, "idx_employee_shifts_time")
+ require.Contains(t, sql, "idx_employee_shifts_type")
+}
+
+func TestOmniExcludeConstraintIndexNotDuplicated(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE meetings (
+ meeting_id serial PRIMARY KEY,
+ room_id integer NOT NULL,
+ meeting_start timestamp NOT NULL,
+ meeting_end timestamp NOT NULL
+ );
+ `)
+
+ t.Logf("Generated SQL:\n%s", sql)
+
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "meetings")
+ // Should NOT create a separate index named after the constraint
+ require.NotContains(t, sql, "CREATE INDEX excl_room_no_overlap")
+}
+
+func TestOmniMaterializedViewWithRegularIndexes(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE orders (
+ order_id serial PRIMARY KEY,
+ customer_id integer NOT NULL,
+ order_date date NOT NULL,
+ total_amount numeric(10,2) NOT NULL
+ );
+
+ CREATE MATERIALIZED VIEW order_summary AS
+ SELECT
+ customer_id,
+ DATE_TRUNC('month', order_date) as order_month,
+ COUNT(*) as order_count,
+ SUM(total_amount) as total_sales
+ FROM orders
+ GROUP BY customer_id, DATE_TRUNC('month', order_date);
+
+ CREATE INDEX idx_order_summary_customer ON order_summary (customer_id);
+ CREATE INDEX idx_order_summary_month ON order_summary (order_month);
+ CREATE UNIQUE INDEX idx_order_summary_unique ON order_summary (customer_id, order_month);
+ `)
+
+ t.Logf("Generated SQL:\n%s", sql)
+
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "orders")
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.Contains(t, sql, "order_summary")
+
+ require.Contains(t, sql, "idx_order_summary_customer")
+ require.Contains(t, sql, "idx_order_summary_month")
+ require.Contains(t, sql, "idx_order_summary_unique")
+}
+
+func TestOmniIndexCreatedBeforeForeignKey(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE customers (
+ id serial PRIMARY KEY,
+ email varchar(255) NOT NULL,
+ name varchar(100) NOT NULL
+ );
+
+ CREATE INDEX idx_customers_id ON customers (id);
+ CREATE INDEX idx_customers_email ON customers (email);
+
+ CREATE TABLE orders (
+ id serial PRIMARY KEY,
+ customer_id integer NOT NULL,
+ order_date date NOT NULL,
+ total_amount numeric(10,2) NOT NULL,
+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id)
+ );
+
+ CREATE INDEX idx_orders_customer ON orders (customer_id);
+ `)
+
+ t.Logf("Generated SQL:\n%s", sql)
+
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "customers")
+ require.Contains(t, sql, "orders")
+
+ require.Contains(t, sql, "idx_customers_id")
+ require.Contains(t, sql, "idx_customers_email")
+ require.Contains(t, sql, "idx_orders_customer")
+ require.Contains(t, sql, "fk_orders_customer")
+
+ // The omni engine correctly includes FK constraints inline in CREATE TABLE.
+ // The index is created after the table.
+ customersTablePos := strings.Index(sql, `"customers"`)
+ ordersTablePos := strings.Index(sql, `"orders"`)
+
+ require.NotEqual(t, -1, customersTablePos, "customers table should exist")
+ require.NotEqual(t, -1, ordersTablePos, "orders table should exist")
+ require.Less(t, customersTablePos, ordersTablePos,
+ "Referenced table (customers) should be created BEFORE the table with FK (orders)")
+}
diff --git a/backend/plugin/schema/pg/function_migration_integration_omni_test.go b/backend/plugin/schema/pg/function_migration_integration_omni_test.go
new file mode 100644
index 0000000000..ade44ea40a
--- /dev/null
+++ b/backend/plugin/schema/pg/function_migration_integration_omni_test.go
@@ -0,0 +1,348 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniFunctionSDLDiffAndMigration(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "Create new function",
+ fromSDL: ``,
+ toSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ contains: []string{"CREATE FUNCTION", "calculate_area"},
+ },
+ {
+ name: "Drop function",
+ fromSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ toSDL: ``,
+ contains: []string{"DROP FUNCTION", "calculate_area"},
+ },
+ {
+ name: "Modify function (CREATE OR REPLACE)",
+ fromSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ toSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159265 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ contains: []string{"CREATE OR REPLACE FUNCTION", "calculate_area"},
+ },
+ {
+ name: "Create new procedure",
+ fromSDL: ``,
+ toSDL: `
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ NULL;
+ END;
+ $$;
+ `,
+ contains: []string{"CREATE PROCEDURE", "log_message"},
+ },
+ {
+ name: "Overloaded functions with different signatures",
+ fromSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ toSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION add_numbers(a FLOAT, b FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ // Omni normalizes FLOAT to double precision
+ contains: []string{"CREATE FUNCTION", "add_numbers", "double precision"},
+ },
+ {
+ name: "Drop one overloaded function",
+ fromSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION add_numbers(a FLOAT, b FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ toSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ contains: []string{"DROP FUNCTION", "add_numbers"},
+ },
+ {
+ name: "Modify one overloaded function",
+ fromSDL: `
+ CREATE FUNCTION calculate(x INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN x * 2;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION calculate(x FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN x * 2.0;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ toSDL: `
+ CREATE FUNCTION calculate(x INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN x * 3;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION calculate(x FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN x * 2.0;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ contains: []string{"CREATE OR REPLACE FUNCTION", "calculate"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniFunctionASTOnlyModeValidation(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE FUNCTION get_total(amount DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN amount * 1.1;
+ END;
+ $$ LANGUAGE plpgsql;
+ `)
+ require.Contains(t, sql, "CREATE FUNCTION")
+ require.Contains(t, sql, "get_total")
+}
+
+func TestOmniOverloadedFunctionSignatureHandling(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE FUNCTION format_value(val INTEGER)
+ RETURNS TEXT AS $$
+ BEGIN
+ RETURN val::TEXT;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION format_value(val DECIMAL, precision_digits INTEGER)
+ RETURNS TEXT AS $$
+ BEGIN
+ RETURN ROUND(val, precision_digits)::TEXT;
+ END;
+ $$ LANGUAGE plpgsql;
+ `)
+ require.Contains(t, sql, "format_value")
+ functionCount := strings.Count(sql, "format_value")
+ require.Equal(t, 2, functionCount, "Should reference format_value exactly twice (one per overload)")
+}
+
+func TestOmniProcedureDropMigration(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "Drop procedure should use DROP PROCEDURE",
+ fromSDL: `
+ CREATE PROCEDURE update_user_name(IN user_id integer, IN new_name character varying)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ UPDATE users SET name = new_name WHERE id = user_id;
+ END;
+ $$;
+ `,
+ toSDL: ``,
+ contains: []string{"DROP PROCEDURE", "update_user_name"},
+ },
+ {
+ name: "Drop function should use DROP FUNCTION",
+ fromSDL: `
+ CREATE FUNCTION calculate_tax(amount numeric) RETURNS numeric
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RETURN amount * 0.1;
+ END;
+ $$;
+ `,
+ toSDL: ``,
+ contains: []string{"DROP FUNCTION", "calculate_tax"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniDropProcedureShouldNotAffectFunctionComment(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ }{
+ {
+ name: "Drop procedure without comment should not affect function comment",
+ fromSDL: `
+ CREATE OR REPLACE FUNCTION test_function()
+ RETURNS void
+ LANGUAGE plpgsql
+ AS $function$
+ BEGIN
+ RAISE NOTICE 'Test function executed';
+ END
+ $function$;
+
+ COMMENT ON FUNCTION "public"."test_function"() IS 'A test function that raises a notice';
+
+ CREATE PROCEDURE new_procedure()
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ NULL;
+ END;
+ $$;
+ `,
+ toSDL: `
+ CREATE OR REPLACE FUNCTION test_function()
+ RETURNS void
+ LANGUAGE plpgsql
+ AS $function$
+ BEGIN
+ RAISE NOTICE 'Test function executed';
+ END
+ $function$;
+
+ COMMENT ON FUNCTION "public"."test_function"() IS 'A test function that raises a notice';
+ `,
+ },
+ {
+ name: "Drop procedure with comment should not affect function comment",
+ fromSDL: `
+ CREATE OR REPLACE FUNCTION test_function()
+ RETURNS void
+ LANGUAGE plpgsql
+ AS $function$
+ BEGIN
+ RAISE NOTICE 'Test function executed';
+ END
+ $function$;
+
+ COMMENT ON FUNCTION "public"."test_function"() IS 'A test function that raises a notice';
+
+ CREATE PROCEDURE new_procedure()
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ NULL;
+ END;
+ $$;
+
+ COMMENT ON PROCEDURE "public"."new_procedure"() IS 'A test procedure';
+ `,
+ toSDL: `
+ CREATE OR REPLACE FUNCTION test_function()
+ RETURNS void
+ LANGUAGE plpgsql
+ AS $function$
+ BEGIN
+ RAISE NOTICE 'Test function executed';
+ END
+ $function$;
+
+ COMMENT ON FUNCTION "public"."test_function"() IS 'A test function that raises a notice';
+ `,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+
+ // Should drop the procedure
+ require.Contains(t, sql, "DROP PROCEDURE")
+ require.Contains(t, sql, "new_procedure")
+
+ // Should NOT contain any COMMENT statement about test_function
+ if strings.Contains(sql, "test_function") && strings.Contains(sql, "COMMENT") {
+ require.Fail(t, "Found unexpected COMMENT statement about test_function in migration: "+sql)
+ }
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/function_sdl_diff_omni_test.go b/backend/plugin/schema/pg/function_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..c9afe5076f
--- /dev/null
+++ b/backend/plugin/schema/pg/function_sdl_diff_omni_test.go
@@ -0,0 +1,480 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/omni/pg/catalog"
+)
+
+func TestOmniFunctionSDLDiff(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ wantEmpty bool
+ wantAddCount int
+ wantDropCount int
+ wantModifyCount int
+ }{
+ {
+ name: "Create new function",
+ fromSDL: ``,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+);
+
+CREATE OR REPLACE FUNCTION get_user_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+END;
+$$ LANGUAGE plpgsql;`,
+ wantContains: []string{"CREATE FUNCTION", "get_user_count"},
+ wantAddCount: 1,
+ },
+ {
+ name: "Drop function",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+);
+
+CREATE OR REPLACE FUNCTION get_user_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+END;
+$$ LANGUAGE plpgsql;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+);`,
+ wantContains: []string{"DROP FUNCTION", "get_user_count"},
+ wantDropCount: 1,
+ },
+ {
+ name: "Modify function body",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE OR REPLACE FUNCTION get_user_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+END;
+$$ LANGUAGE plpgsql;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE OR REPLACE FUNCTION get_user_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users WHERE active = true);
+END;
+$$ LANGUAGE plpgsql;`,
+ wantContains: []string{"get_user_count"},
+ wantModifyCount: 1,
+ },
+ {
+ name: "No changes to function",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+);
+
+CREATE OR REPLACE FUNCTION get_user_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+END;
+$$ LANGUAGE plpgsql;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+);
+
+CREATE OR REPLACE FUNCTION get_user_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+END;
+$$ LANGUAGE plpgsql;`,
+ wantEmpty: true,
+ },
+ {
+ name: "Multiple functions with different changes",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+);
+
+CREATE OR REPLACE FUNCTION get_all_users()
+RETURNS SETOF users AS $$
+BEGIN
+ RETURN QUERY SELECT * FROM users;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION get_user_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+END;
+$$ LANGUAGE plpgsql;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+);
+
+CREATE OR REPLACE FUNCTION get_all_users()
+RETURNS SETOF users AS $$
+BEGIN
+ RETURN QUERY SELECT * FROM users;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION get_admin_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM users WHERE role = 'admin');
+END;
+$$ LANGUAGE plpgsql;`,
+ wantContains: []string{"get_admin_count", "get_user_count"},
+ wantAddCount: 1, // get_admin_count
+ wantDropCount: 1, // get_user_count
+ },
+ {
+ name: "Schema-qualified function names",
+ fromSDL: `
+CREATE SCHEMA test_schema;
+CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+);`,
+ toSDL: `
+CREATE SCHEMA test_schema;
+CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+);
+
+CREATE OR REPLACE FUNCTION test_schema.get_product_count()
+RETURNS INTEGER AS $$
+BEGIN
+ RETURN (SELECT COUNT(*) FROM test_schema.products);
+END;
+$$ LANGUAGE plpgsql;`,
+ wantContains: []string{"CREATE FUNCTION", "get_product_count"},
+ wantAddCount: 1,
+ },
+ {
+ name: "Function with complex signature",
+ fromSDL: `
+CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ amount DECIMAL(10,2),
+ created_at TIMESTAMP DEFAULT NOW()
+);`,
+ toSDL: `
+CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ amount DECIMAL(10,2),
+ created_at TIMESTAMP DEFAULT NOW()
+);
+
+CREATE OR REPLACE FUNCTION calculate_total(
+ p_start_date DATE,
+ p_end_date DATE,
+ p_discount_rate DECIMAL DEFAULT 0.0
+)
+RETURNS DECIMAL(10,2) AS $$
+BEGIN
+ RETURN (
+ SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)
+ FROM orders
+ WHERE created_at::DATE BETWEEN p_start_date AND p_end_date
+ );
+END;
+$$ LANGUAGE plpgsql;`,
+ wantContains: []string{"CREATE FUNCTION", "calculate_total"},
+ wantAddCount: 1,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+
+ if tt.wantEmpty {
+ require.Empty(t, sql)
+ return
+ }
+
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+
+ // Verify diff counts.
+ from, err := catalog.LoadSDL(strings.TrimSpace(tt.fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(tt.toSDL))
+ require.NoError(t, err)
+ diff := catalog.Diff(from, to)
+
+ addCount, dropCount, modifyCount := 0, 0, 0
+ for _, f := range diff.Functions {
+ switch f.Action {
+ case catalog.DiffAdd:
+ addCount++
+ case catalog.DiffDrop:
+ dropCount++
+ case catalog.DiffModify:
+ modifyCount++
+ default:
+ }
+ }
+
+ require.Equal(t, tt.wantAddCount, addCount, "function ADD count mismatch")
+ require.Equal(t, tt.wantDropCount, dropCount, "function DROP count mismatch")
+ require.Equal(t, tt.wantModifyCount, modifyCount, "function MODIFY count mismatch")
+ })
+ }
+}
+
+func TestOmniSameNameFunctionsWithDifferentSignatures(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantAddCount int
+ wantDropCount int
+ wantModifyCount int
+ description string
+ }{
+ {
+ name: "Add second function with same name but different signature",
+ fromSDL: `
+CREATE FUNCTION "public"."my_procedure"(p_id integer) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Function with one parameter: %', p_id;
+END;
+$$;`,
+ toSDL: `
+CREATE FUNCTION "public"."my_procedure"(p_id integer) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Function with one parameter: %', p_id;
+END;
+$$;
+
+CREATE FUNCTION "public"."my_procedure"(p_id integer, p_name text) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Function with two parameters: % - %', p_id, p_name;
+END;
+$$;`,
+ wantAddCount: 1,
+ wantDropCount: 0,
+ description: "Should add the new function without dropping the old one",
+ },
+ {
+ name: "Three overloaded functions with same name",
+ fromSDL: `
+CREATE FUNCTION "public"."calculate"(x integer) RETURNS integer
+ LANGUAGE sql
+ AS $$
+ SELECT x * 2;
+$$;`,
+ toSDL: `
+CREATE FUNCTION "public"."calculate"(x integer) RETURNS integer
+ LANGUAGE sql
+ AS $$
+ SELECT x * 2;
+$$;
+
+CREATE FUNCTION "public"."calculate"(x integer, y integer) RETURNS integer
+ LANGUAGE sql
+ AS $$
+ SELECT x + y;
+$$;
+
+CREATE FUNCTION "public"."calculate"(x numeric, y numeric, z numeric) RETURNS numeric
+ LANGUAGE sql
+ AS $$
+ SELECT x + y + z;
+$$;`,
+ wantAddCount: 2,
+ wantDropCount: 0,
+ description: "Should add two new overloaded functions",
+ },
+ {
+ name: "Remove one overloaded function, keep others",
+ fromSDL: `
+CREATE FUNCTION "public"."process"(p_id integer) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Process one param';
+END;
+$$;
+
+CREATE FUNCTION "public"."process"(p_id integer, p_name text) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Process two params';
+END;
+$$;
+
+CREATE FUNCTION "public"."process"(p_id integer, p_name text, p_email text) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Process three params';
+END;
+$$;`,
+ toSDL: `
+CREATE FUNCTION "public"."process"(p_id integer) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Process one param';
+END;
+$$;
+
+CREATE FUNCTION "public"."process"(p_id integer, p_name text, p_email text) RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ RAISE NOTICE 'Process three params';
+END;
+$$;`,
+ wantAddCount: 0,
+ wantDropCount: 1,
+ description: "Should drop only the middle function (2 params), keep others",
+ },
+ {
+ name: "Modify one overloaded function, keep others unchanged",
+ fromSDL: `
+CREATE FUNCTION "public"."get_info"(p_id integer) RETURNS text
+ LANGUAGE sql
+ AS $$
+ SELECT 'User ID: ' || p_id::text;
+$$;
+
+CREATE FUNCTION "public"."get_info"(p_name text) RETURNS text
+ LANGUAGE sql
+ AS $$
+ SELECT 'User Name: ' || p_name;
+$$;`,
+ toSDL: `
+CREATE FUNCTION "public"."get_info"(p_id integer) RETURNS text
+ LANGUAGE sql
+ AS $$
+ SELECT 'Updated User ID: ' || p_id::text;
+$$;
+
+CREATE FUNCTION "public"."get_info"(p_name text) RETURNS text
+ LANGUAGE sql
+ AS $$
+ SELECT 'User Name: ' || p_name;
+$$;`,
+ wantAddCount: 0,
+ wantDropCount: 0,
+ wantModifyCount: 1,
+ description: "Should modify only the first function, keep second unchanged",
+ },
+ {
+ name: "Procedures with same name but different signatures",
+ fromSDL: `
+CREATE PROCEDURE "public"."update_status"(p_id integer)
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ UPDATE users SET status = 'active' WHERE id = p_id;
+END;
+$$;`,
+ toSDL: `
+CREATE PROCEDURE "public"."update_status"(p_id integer)
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ UPDATE users SET status = 'active' WHERE id = p_id;
+END;
+$$;
+
+CREATE PROCEDURE "public"."update_status"(p_id integer, p_new_status text)
+ LANGUAGE plpgsql
+ AS $$
+BEGIN
+ UPDATE users SET status = p_new_status WHERE id = p_id;
+END;
+$$;`,
+ wantAddCount: 1,
+ wantDropCount: 0,
+ description: "Should add the new procedure without dropping the old one",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ t.Logf("Description: %s", tt.description)
+ t.Logf("Migration SQL:\n%s", sql)
+
+ from, err := catalog.LoadSDL(strings.TrimSpace(tt.fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(tt.toSDL))
+ require.NoError(t, err)
+ diff := catalog.Diff(from, to)
+
+ addCount, dropCount, modifyCount := 0, 0, 0
+ for _, f := range diff.Functions {
+ switch f.Action {
+ case catalog.DiffAdd:
+ addCount++
+ case catalog.DiffDrop:
+ dropCount++
+ case catalog.DiffModify:
+ modifyCount++
+ default:
+ }
+ }
+
+ require.Equal(t, tt.wantAddCount, addCount, "function ADD count mismatch")
+ require.Equal(t, tt.wantDropCount, dropCount, "function DROP count mismatch")
+ require.Equal(t, tt.wantModifyCount, modifyCount, "function MODIFY count mismatch")
+
+ // Ensure no unexpected drops (BYT-7994 regression check).
+ if dropCount > tt.wantDropCount {
+ t.Errorf("BUG: Found %d DROP action(s), expected %d. "+
+ "Functions with same name but different signatures should be identified separately.",
+ dropCount, tt.wantDropCount)
+ }
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/get_sdl_diff_comment_omni_test.go b/backend/plugin/schema/pg/get_sdl_diff_comment_omni_test.go
new file mode 100644
index 0000000000..201059498f
--- /dev/null
+++ b/backend/plugin/schema/pg/get_sdl_diff_comment_omni_test.go
@@ -0,0 +1,514 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/omni/pg/catalog"
+)
+
+func TestOmniCommentDiff_TableComment(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ wantEmpty bool
+ }{
+ {
+ name: "add table comment",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'User information table';`,
+ wantContains: []string{"COMMENT ON TABLE", "users", "User information table"},
+ },
+ {
+ name: "modify table comment",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'Old comment';`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'New comment';`,
+ wantContains: []string{"COMMENT ON TABLE", "New comment"},
+ },
+ {
+ name: "remove table comment",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'User table';`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS NULL;`,
+ wantContains: []string{"COMMENT ON TABLE", "IS NULL"},
+ },
+ {
+ name: "no comment change",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'Same comment';`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'Same comment';`,
+ wantEmpty: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+
+ if tt.wantEmpty {
+ require.Empty(t, sql)
+ return
+ }
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentDiff_ColumnComment(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ }{
+ {
+ name: "add column comment",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'User full name';`,
+ wantContains: []string{"COMMENT ON COLUMN", "name", "User full name"},
+ },
+ {
+ name: "modify column comment",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'Old name';`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'New name';`,
+ wantContains: []string{"COMMENT ON COLUMN", "New name"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentDiff_MultipleColumnComments(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT,
+ email TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'User name';`, `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT,
+ email TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'Full name';
+COMMENT ON COLUMN users.email IS 'Email address';`)
+
+ require.Contains(t, sql, "COMMENT ON COLUMN")
+ require.Contains(t, sql, "Full name")
+ require.Contains(t, sql, "Email address")
+
+ // Also verify via diff counts.
+ from, err := catalog.LoadSDL(strings.TrimSpace(`
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT,
+ email TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'User name';`))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(`
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT,
+ email TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'Full name';
+COMMENT ON COLUMN users.email IS 'Email address';`))
+ require.NoError(t, err)
+ diff := catalog.Diff(from, to)
+ require.GreaterOrEqual(t, len(diff.Comments), 2, "expected at least 2 comment changes")
+}
+
+func TestOmniCommentDiff_ViewComment(t *testing.T) {
+ sql := omniSDLMigration(t,
+ `CREATE VIEW user_view AS SELECT 1;`,
+ `CREATE VIEW user_view AS SELECT 1;
+
+COMMENT ON VIEW user_view IS 'User view description';`)
+
+ require.Contains(t, sql, "COMMENT ON VIEW")
+ require.Contains(t, sql, "user_view")
+ require.Contains(t, sql, "User view description")
+}
+
+func TestOmniCommentDiff_SequenceComment(t *testing.T) {
+ sql := omniSDLMigration(t,
+ `CREATE SEQUENCE user_id_seq;`,
+ `CREATE SEQUENCE user_id_seq;
+
+COMMENT ON SEQUENCE user_id_seq IS 'User ID sequence';`)
+
+ require.Contains(t, sql, "COMMENT ON SEQUENCE")
+ require.Contains(t, sql, "User ID sequence")
+}
+
+func TestOmniCommentDiff_FunctionComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE FUNCTION add_numbers(a INT, b INT) RETURNS INT AS $$
+BEGIN
+ RETURN a + b;
+END;
+$$ LANGUAGE plpgsql;`, `
+CREATE FUNCTION add_numbers(a INT, b INT) RETURNS INT AS $$
+BEGIN
+ RETURN a + b;
+END;
+$$ LANGUAGE plpgsql;
+
+COMMENT ON FUNCTION add_numbers(INT, INT) IS 'Adds two numbers';`)
+
+ require.Contains(t, sql, "COMMENT ON FUNCTION")
+ require.Contains(t, sql, "Adds two numbers")
+}
+
+func TestOmniCommentDiff_ObjectCreateWithComment(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ }{
+ {
+ name: "create table with comment",
+ fromSDL: ``,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'User table';`,
+ wantContains: []string{"CREATE TABLE", "COMMENT ON TABLE", "User table"},
+ },
+ {
+ name: "create table with column comment",
+ fromSDL: ``,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'User name';`,
+ wantContains: []string{"CREATE TABLE", "COMMENT ON COLUMN", "User name"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentDiff_ObjectDropWithComment(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ wantNotContains []string
+ }{
+ {
+ name: "drop table with comment",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'User table';`,
+ toSDL: ``,
+ wantContains: []string{"DROP TABLE"},
+ },
+ {
+ name: "drop table with column comment",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'User name';`,
+ toSDL: ``,
+ wantContains: []string{"DROP TABLE"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentDiff_CommentOnlyChange(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ wantNotContains []string
+ }{
+ {
+ name: "only table comment changes",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'Old comment';`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'New comment';`,
+ wantContains: []string{"COMMENT ON TABLE", "New comment"},
+ wantNotContains: []string{"ALTER TABLE", "DROP TABLE", "CREATE TABLE"},
+ },
+ {
+ name: "only column comment changes",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'Old name';`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN users.name IS 'New name';`,
+ wantContains: []string{"COMMENT ON COLUMN", "New name"},
+ wantNotContains: []string{"ALTER TABLE", "DROP TABLE", "CREATE TABLE"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ for _, s := range tt.wantNotContains {
+ require.NotContains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentDiff_TableChangeWithCommentChange(t *testing.T) {
+ sql := omniSDLMigration(t, `
+CREATE TABLE users (
+ id INT PRIMARY KEY
+);
+
+COMMENT ON TABLE users IS 'Old comment';`, `
+CREATE TABLE users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON TABLE users IS 'New comment';`)
+
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "COMMENT ON TABLE")
+ require.Contains(t, sql, "New comment")
+}
+
+func TestOmniCommentDiff_SpecialCharacters(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ }{
+ {
+ name: "comment with single quote",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY
+);`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY
+);
+
+COMMENT ON TABLE users IS 'User''s table';`,
+ wantContains: []string{"COMMENT ON TABLE", "User"},
+ },
+ {
+ name: "comment with newlines",
+ fromSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY
+);`,
+ toSDL: `
+CREATE TABLE users (
+ id INT PRIMARY KEY
+);
+
+COMMENT ON TABLE users IS 'Line 1
+Line 2';`,
+ wantContains: []string{"COMMENT ON TABLE"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniCommentDiff_SchemaQualified(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ }{
+ {
+ name: "schema qualified table comment",
+ fromSDL: `
+CREATE SCHEMA myschema;
+CREATE TABLE myschema.users (
+ id INT PRIMARY KEY
+);`,
+ toSDL: `
+CREATE SCHEMA myschema;
+CREATE TABLE myschema.users (
+ id INT PRIMARY KEY
+);
+
+COMMENT ON TABLE myschema.users IS 'Users table';`,
+ wantContains: []string{"COMMENT ON TABLE", "myschema", "users", "Users table"},
+ },
+ {
+ name: "schema qualified column comment",
+ fromSDL: `
+CREATE SCHEMA myschema;
+CREATE TABLE myschema.users (
+ id INT PRIMARY KEY,
+ name TEXT
+);`,
+ toSDL: `
+CREATE SCHEMA myschema;
+CREATE TABLE myschema.users (
+ id INT PRIMARY KEY,
+ name TEXT
+);
+
+COMMENT ON COLUMN myschema.users.name IS 'User name';`,
+ wantContains: []string{"COMMENT ON COLUMN", "myschema", "User name"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/get_sdl_diff_omni_test.go b/backend/plugin/schema/pg/get_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..c4bdddde6b
--- /dev/null
+++ b/backend/plugin/schema/pg/get_sdl_diff_omni_test.go
@@ -0,0 +1,135 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/omni/pg/catalog"
+)
+
+func TestOmniGetSDLDiff_InitializationScenario(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ // What to check in the migration SQL.
+ wantEmpty bool
+ wantContains []string
+ wantNotContains []string
+ }{
+ {
+ name: "initialization_with_empty_previous_SDL",
+ fromSDL: "",
+ toSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);",
+ wantContains: []string{
+ "CREATE TABLE",
+ "users",
+ },
+ },
+ {
+ name: "initialization_with_complex_schema",
+ fromSDL: "",
+ toSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);\nCREATE VIEW user_view AS SELECT * FROM users;",
+ wantContains: []string{
+ "CREATE TABLE",
+ "users",
+ "CREATE VIEW",
+ "user_view",
+ },
+ },
+ {
+ name: "non_initialization_normal_diff",
+ fromSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);",
+ toSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT);",
+ wantContains: []string{
+ "ALTER TABLE",
+ "email",
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+
+ if tt.wantEmpty {
+ require.Empty(t, sql)
+ return
+ }
+
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+ for _, s := range tt.wantNotContains {
+ require.NotContains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniGetSDLDiff_InitializationDiffCounts(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantRelations int
+ wantFunctions int
+ wantSequences int
+ wantRelationNames []string
+ }{
+ {
+ name: "initialization_with_empty_previous_SDL",
+ fromSDL: "",
+ toSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);",
+ // Table creation generates a relation entry.
+ wantRelations: 1,
+ wantFunctions: 0,
+ wantRelationNames: []string{"users"},
+ },
+ {
+ name: "initialization_with_complex_schema",
+ fromSDL: "",
+ toSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);\nCREATE VIEW user_view AS SELECT * FROM users;",
+ wantRelations: 2, // table + view
+ wantFunctions: 0,
+ wantRelationNames: []string{"users", "user_view"},
+ },
+ {
+ name: "non_initialization_normal_diff",
+ fromSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);",
+ toSDL: "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT);",
+ wantRelations: 1, // one table modified
+ wantRelationNames: []string{"users"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ from, err := catalog.LoadSDL(strings.TrimSpace(tt.fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(tt.toSDL))
+ require.NoError(t, err)
+ diff := catalog.Diff(from, to)
+
+ require.Equal(t, tt.wantRelations, len(diff.Relations), "unexpected relation count")
+ require.Equal(t, tt.wantFunctions, len(diff.Functions), "unexpected function count")
+
+ var names []string
+ for _, r := range diff.Relations {
+ names = append(names, r.Name)
+ }
+ require.ElementsMatch(t, tt.wantRelationNames, names)
+ })
+ }
+}
+
+func TestOmniGetSDLDiff_MinimalChangesScenario(t *testing.T) {
+ // Same table definition, no semantic change -> empty diff.
+ sql := omniSDLMigration(t,
+ "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);",
+ "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);",
+ )
+ require.Empty(t, sql)
+}
diff --git a/backend/plugin/schema/pg/materialized_view_sdl_diff_omni_test.go b/backend/plugin/schema/pg/materialized_view_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..cf14adfcce
--- /dev/null
+++ b/backend/plugin/schema/pg/materialized_view_sdl_diff_omni_test.go
@@ -0,0 +1,429 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniMaterializedViewSDLDiff_CreateNew(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW active_users_mv AS
+ SELECT id, name
+ FROM users
+ WHERE active = true;
+ `)
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.Contains(t, sql, "active_users_mv")
+}
+
+func TestOmniMaterializedViewSDLDiff_Drop(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW active_users_mv AS
+ SELECT id, name
+ FROM users
+ WHERE active = true;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+ `)
+ require.Contains(t, sql, "DROP MATERIALIZED VIEW")
+ require.Contains(t, sql, "active_users_mv")
+}
+
+func TestOmniMaterializedViewSDLDiff_Modify(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW active_users_mv AS
+ SELECT id, name
+ FROM users
+ WHERE active = true;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW active_users_mv AS
+ SELECT id, name, 'active' as status
+ FROM users
+ WHERE active = true;
+ `)
+ require.Contains(t, sql, "DROP MATERIALIZED VIEW")
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.Contains(t, sql, "active_users_mv")
+}
+
+func TestOmniMaterializedViewSDLDiff_NoChange(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW active_users_mv AS
+ SELECT id, name
+ FROM users
+ WHERE active = true;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW active_users_mv AS
+ SELECT id, name
+ FROM users
+ WHERE active = true;
+ `)
+ require.Empty(t, sql)
+}
+
+func TestOmniMaterializedViewSDLDiff_MultipleViews(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW all_users_mv AS
+ SELECT * FROM users;
+
+ CREATE MATERIALIZED VIEW active_users_mv AS
+ SELECT id, name FROM users WHERE active = true;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE MATERIALIZED VIEW all_users_mv AS
+ SELECT * FROM users;
+
+ CREATE MATERIALIZED VIEW admin_users_mv AS
+ SELECT id, name FROM users WHERE name = 'admin';
+ `)
+ require.Contains(t, sql, "DROP MATERIALIZED VIEW")
+ require.Contains(t, sql, "active_users_mv")
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.Contains(t, sql, "admin_users_mv")
+}
+
+func TestOmniMaterializedViewSDLDiff_SchemaQualified(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE SCHEMA test_schema;
+ CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ `, `
+ CREATE SCHEMA test_schema;
+ CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW test_schema.product_summary_mv AS
+ SELECT id, name FROM test_schema.products;
+ `)
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.Contains(t, sql, "product_summary_mv")
+}
+
+func TestOmniMaterializedViewSDLDiff_WithComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE MATERIALIZED VIEW user_summary_mv AS
+ SELECT id, name FROM users;
+
+ COMMENT ON MATERIALIZED VIEW user_summary_mv IS 'Summary of all users';
+ `)
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.Contains(t, sql, "user_summary_mv")
+ require.Contains(t, sql, "COMMENT ON MATERIALIZED VIEW")
+ require.Contains(t, sql, "Summary of all users")
+}
+
+func TestOmniMaterializedViewMigration_Create(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+ `)
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.NotContains(t, sql, "DROP MATERIALIZED VIEW")
+}
+
+func TestOmniMaterializedViewMigration_DropOnly(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+ `, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ `)
+ require.Contains(t, sql, "DROP MATERIALIZED VIEW")
+}
+
+func TestOmniMaterializedViewMigration_ModifyDropAndCreate(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+ `, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255),
+ price DECIMAL
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name, price FROM products;
+ `)
+ require.Contains(t, sql, "DROP MATERIALIZED VIEW")
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+}
+
+func TestOmniMaterializedViewCommentMigration_CreateWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+
+ COMMENT ON MATERIALIZED VIEW product_mv IS 'Product summary view';
+ `)
+ require.Contains(t, sql, "CREATE MATERIALIZED VIEW")
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "Product summary view")
+}
+
+func TestOmniMaterializedViewCommentMigration_AddComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+ `, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+
+ COMMENT ON MATERIALIZED VIEW product_mv IS 'Product summary view';
+ `)
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "Product summary view")
+}
+
+func TestOmniMaterializedViewCommentMigration_RemoveComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+
+ COMMENT ON MATERIALIZED VIEW product_mv IS 'Product summary view';
+ `, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+ `)
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "product_mv")
+ require.Contains(t, sql, "NULL")
+}
+
+func TestOmniMaterializedViewCommentMigration_UpdateComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+
+ COMMENT ON MATERIALIZED VIEW product_mv IS 'Old comment';
+ `, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE MATERIALIZED VIEW product_mv AS
+ SELECT id, name FROM products;
+
+ COMMENT ON MATERIALIZED VIEW product_mv IS 'New comment';
+ `)
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "New comment")
+}
+
+func TestOmniMaterializedViewDependencyOrder_Create(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE customers (
+ customer_id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255),
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE orders (
+ order_id SERIAL PRIMARY KEY,
+ customer_id INTEGER REFERENCES customers(customer_id),
+ amount DECIMAL(10,2),
+ order_date DATE
+ );
+
+ CREATE VIEW customer_stats_view AS
+ SELECT
+ c.customer_id,
+ c.name,
+ c.email,
+ COUNT(o.order_id) as order_count,
+ SUM(o.amount) as total_spent
+ FROM customers c
+ LEFT JOIN orders o ON c.customer_id = o.customer_id
+ GROUP BY c.customer_id, c.name, c.email;
+
+ CREATE MATERIALIZED VIEW customer_segmentation_mv AS
+ SELECT
+ csv.customer_id,
+ csv.name,
+ csv.total_spent,
+ CASE
+ WHEN csv.total_spent >= 1000 THEN 'Premium'
+ WHEN csv.total_spent >= 500 THEN 'Standard'
+ ELSE 'Basic'
+ END as segment
+ FROM customer_stats_view csv;
+ `)
+
+ customersIdx := strings.Index(sql, "CREATE TABLE")
+ viewIdx := strings.Index(sql, "CREATE VIEW")
+ mvIdx := strings.Index(sql, "CREATE MATERIALIZED VIEW")
+
+ require.NotEqual(t, -1, customersIdx, "customers table should be created")
+ require.NotEqual(t, -1, viewIdx, "view should be created")
+ require.NotEqual(t, -1, mvIdx, "materialized view should be created")
+
+ // Tables must be created before views and materialized views
+ require.Less(t, customersIdx, viewIdx, "tables must be created before view")
+ require.Less(t, customersIdx, mvIdx, "tables must be created before materialized view")
+}
+
+func TestOmniMaterializedViewDependencyOrder_Drop(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE customers (
+ customer_id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255),
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE orders (
+ order_id SERIAL PRIMARY KEY,
+ customer_id INTEGER REFERENCES customers(customer_id),
+ amount DECIMAL(10,2),
+ order_date DATE
+ );
+
+ CREATE VIEW customer_stats_view AS
+ SELECT
+ c.customer_id,
+ c.name,
+ c.email,
+ COUNT(o.order_id) as order_count,
+ SUM(o.amount) as total_spent
+ FROM customers c
+ LEFT JOIN orders o ON c.customer_id = o.customer_id
+ GROUP BY c.customer_id, c.name, c.email;
+
+ CREATE MATERIALIZED VIEW customer_segmentation_mv AS
+ SELECT
+ csv.customer_id,
+ csv.name,
+ csv.total_spent,
+ CASE
+ WHEN csv.total_spent >= 1000 THEN 'Premium'
+ WHEN csv.total_spent >= 500 THEN 'Standard'
+ ELSE 'Basic'
+ END as segment
+ FROM customer_stats_view csv;
+ `, "")
+
+ // The omni engine drops objects; verify all types are represented
+ require.Contains(t, sql, "DROP MATERIALIZED VIEW")
+ require.Contains(t, sql, "DROP VIEW")
+ require.Contains(t, sql, "DROP TABLE")
+
+ require.Contains(t, sql, "customer_segmentation_mv")
+ require.Contains(t, sql, "customer_stats_view")
+}
diff --git a/backend/plugin/schema/pg/omni_diff_audit_test.go b/backend/plugin/schema/pg/omni_diff_audit_test.go
new file mode 100644
index 0000000000..b316d84967
--- /dev/null
+++ b/backend/plugin/schema/pg/omni_diff_audit_test.go
@@ -0,0 +1,328 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// ============================================================================
+// Audit of claimed behavior differences between old ANTLR SDL engine and omni.
+// Each test calls omniSDLMigration, logs the SQL, and asserts the specific
+// behavior being investigated.
+// ============================================================================
+
+// 1. Drop cascade: "omni uses DROP TABLE CASCADE instead of dropping dependent
+// objects first"
+func TestOmniDiffAudit_DropCascade(t *testing.T) {
+ // Drop a table that has a dependent view. Check if CASCADE is used.
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+ CREATE VIEW active_users AS SELECT id, name FROM users WHERE active = true;
+ `, `
+ CREATE VIEW active_users AS SELECT 1 AS id, 'placeholder'::text AS name WHERE false;
+ `)
+ t.Logf("SQL output (drop table with dependent view):\n%s", sql)
+
+ // Also test dropping table when the view is also dropped.
+ sql2 := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ CREATE VIEW user_view AS SELECT * FROM users;
+ `, "")
+ t.Logf("SQL output (drop table + view):\n%s", sql2)
+
+ hasCascade := strings.Contains(strings.ToUpper(sql2), "CASCADE")
+ t.Logf("Contains CASCADE: %v", hasCascade)
+
+ if hasCascade {
+ require.Contains(t, strings.ToUpper(sql2), "CASCADE",
+ "CONFIRMED: omni uses CASCADE on DROP TABLE")
+ } else {
+ t.Log("NOT CONFIRMED: omni does NOT use CASCADE on DROP TABLE")
+ }
+}
+
+// 2. View Comment: "omni uses COMMENT ON TABLE for views instead of COMMENT ON VIEW"
+func TestOmniDiffAudit_ViewComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE VIEW user_view AS SELECT 1;
+ `, `
+ CREATE VIEW user_view AS SELECT 1;
+ COMMENT ON VIEW user_view IS 'A view comment';
+ `)
+ t.Logf("SQL output (view comment):\n%s", sql)
+
+ hasCommentOnView := strings.Contains(sql, "COMMENT ON VIEW")
+ hasCommentOnTable := strings.Contains(sql, "COMMENT ON TABLE")
+ t.Logf("Contains 'COMMENT ON VIEW': %v", hasCommentOnView)
+ t.Logf("Contains 'COMMENT ON TABLE': %v", hasCommentOnTable)
+
+ // The claim is that omni uses COMMENT ON TABLE for views.
+ // If it actually uses COMMENT ON VIEW, the claim is wrong.
+ if hasCommentOnView {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni correctly uses COMMENT ON VIEW")
+ } else if hasCommentOnTable {
+ t.Log("Verdict: CONFIRMED - omni uses COMMENT ON TABLE instead of COMMENT ON VIEW")
+ } else {
+ t.Log("Verdict: UNEXPECTED - no COMMENT statement found at all")
+ }
+
+ // Assert at least one comment form is present
+ require.True(t, hasCommentOnView || hasCommentOnTable,
+ "expected a COMMENT statement in output")
+}
+
+// 3. Materialized View Comment: "omni uses COMMENT ON TABLE for materialized views
+// instead of COMMENT ON MATERIALIZED VIEW"
+func TestOmniDiffAudit_MaterializedViewComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE MATERIALIZED VIEW product_mv AS SELECT id, name FROM products;
+ `, `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE MATERIALIZED VIEW product_mv AS SELECT id, name FROM products;
+ COMMENT ON MATERIALIZED VIEW product_mv IS 'Product summary view';
+ `)
+ t.Logf("SQL output (materialized view comment):\n%s", sql)
+
+ hasCommentOnMV := strings.Contains(sql, "COMMENT ON MATERIALIZED VIEW")
+ hasCommentOnTable := strings.Contains(sql, "COMMENT ON TABLE")
+ t.Logf("Contains 'COMMENT ON MATERIALIZED VIEW': %v", hasCommentOnMV)
+ t.Logf("Contains 'COMMENT ON TABLE': %v", hasCommentOnTable)
+
+ if hasCommentOnMV {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni correctly uses COMMENT ON MATERIALIZED VIEW")
+ } else if hasCommentOnTable {
+ t.Log("Verdict: CONFIRMED - omni uses COMMENT ON TABLE instead of COMMENT ON MATERIALIZED VIEW")
+ } else {
+ t.Log("Verdict: UNEXPECTED - no COMMENT statement found at all")
+ }
+
+ require.True(t, hasCommentOnMV || hasCommentOnTable,
+ "expected a COMMENT statement in output")
+}
+
+// 4. Trigger modification: "omni uses DROP+CREATE instead of CREATE OR REPLACE TRIGGER"
+func TestOmniDiffAudit_TriggerModification(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT OR UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `)
+ t.Logf("SQL output (trigger modification):\n%s", sql)
+
+ hasDropTrigger := strings.Contains(sql, "DROP TRIGGER")
+ hasCreateTrigger := strings.Contains(sql, "CREATE TRIGGER")
+ hasCreateOrReplace := strings.Contains(sql, "CREATE OR REPLACE TRIGGER")
+ t.Logf("Contains 'DROP TRIGGER': %v", hasDropTrigger)
+ t.Logf("Contains 'CREATE TRIGGER': %v", hasCreateTrigger)
+ t.Logf("Contains 'CREATE OR REPLACE TRIGGER': %v", hasCreateOrReplace)
+
+ if hasDropTrigger && hasCreateTrigger && !hasCreateOrReplace {
+ t.Log("Verdict: CONFIRMED - omni uses DROP+CREATE for trigger modification")
+ } else if hasCreateOrReplace {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni uses CREATE OR REPLACE TRIGGER")
+ } else {
+ t.Log("Verdict: UNEXPECTED pattern")
+ }
+
+ require.Contains(t, sql, "TRIGGER")
+}
+
+// 5. Trigger column ref: "omni doesn't preserve UPDATE OF column syntax"
+func TestOmniDiffAudit_TriggerColumnRef(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE inventory (id SERIAL PRIMARY KEY, stock INT);
+ CREATE FUNCTION check_stock() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER stock_check
+ BEFORE UPDATE OF stock ON inventory
+ FOR EACH ROW EXECUTE FUNCTION check_stock();
+ `)
+ t.Logf("SQL output (trigger with UPDATE OF):\n%s", sql)
+
+ hasUpdateOf := strings.Contains(sql, "UPDATE OF")
+ t.Logf("Contains 'UPDATE OF': %v", hasUpdateOf)
+
+ if hasUpdateOf {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni preserves UPDATE OF column syntax")
+ } else {
+ t.Log("Verdict: CONFIRMED - omni does not preserve UPDATE OF column syntax")
+ }
+}
+
+// 6. FK in CREATE TABLE: "omni inlines FK in CREATE TABLE instead of separate
+// ALTER TABLE ADD CONSTRAINT"
+func TestOmniDiffAudit_FKInCreateTable(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE categories (
+ id SERIAL PRIMARY KEY,
+ name TEXT NOT NULL
+ );
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ category_id INTEGER,
+ CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id)
+ );
+ `)
+ t.Logf("SQL output (new table with FK):\n%s", sql)
+
+ hasAlterTableFK := strings.Contains(sql, "ALTER TABLE") && strings.Contains(sql, "FOREIGN KEY")
+ hasInlineFK := false
+ // Check if FOREIGN KEY appears inside a CREATE TABLE block
+ createTableIdx := strings.Index(sql, "CREATE TABLE")
+ if createTableIdx >= 0 {
+ // Find the second CREATE TABLE (the products table)
+ rest := sql[createTableIdx+len("CREATE TABLE"):]
+ secondCreate := strings.Index(rest, "CREATE TABLE")
+ if secondCreate >= 0 {
+ // Look for FOREIGN KEY within the products CREATE TABLE statement
+ afterSecondCreate := rest[secondCreate:]
+ // Find the closing );
+ closeParen := strings.Index(afterSecondCreate, ");")
+ if closeParen > 0 {
+ createBlock := afterSecondCreate[:closeParen]
+ if strings.Contains(createBlock, "FOREIGN KEY") {
+ hasInlineFK = true
+ }
+ }
+ }
+ }
+
+ t.Logf("Has ALTER TABLE ... FOREIGN KEY: %v", hasAlterTableFK)
+ t.Logf("Has inline FOREIGN KEY in CREATE TABLE: %v", hasInlineFK)
+
+ if hasInlineFK && !hasAlterTableFK {
+ t.Log("Verdict: CONFIRMED - omni inlines FK in CREATE TABLE")
+ } else if hasAlterTableFK {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni uses separate ALTER TABLE ADD CONSTRAINT")
+ } else {
+ t.Log("Verdict: UNEXPECTED pattern")
+ }
+}
+
+// 7. Sequence OWNED BY: "omni absorbs sequences into SERIAL/GENERATED"
+func TestOmniDiffAudit_SequenceOwnedBy(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id integer NOT NULL,
+ name text
+ );
+ `, `
+ CREATE TABLE users (
+ id integer NOT NULL,
+ name text
+ );
+ CREATE SEQUENCE user_id_seq AS integer START WITH 1 INCREMENT BY 1;
+ ALTER SEQUENCE user_id_seq OWNED BY users.id;
+ `)
+ t.Logf("SQL output (sequence OWNED BY):\n%s", sql)
+
+ hasCreateSequence := strings.Contains(sql, "CREATE SEQUENCE")
+ hasAlterSequenceOwnedBy := strings.Contains(sql, "OWNED BY")
+ t.Logf("Contains 'CREATE SEQUENCE': %v", hasCreateSequence)
+ t.Logf("Contains 'OWNED BY': %v", hasAlterSequenceOwnedBy)
+
+ if !hasCreateSequence {
+ t.Log("Verdict: CONFIRMED - omni absorbs owned sequences (no CREATE SEQUENCE emitted)")
+ } else if hasAlterSequenceOwnedBy {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni keeps sequences + ALTER SEQUENCE OWNED BY")
+ } else {
+ t.Log("Verdict: PARTIAL - CREATE SEQUENCE emitted but no OWNED BY")
+ }
+}
+
+// 8. Sequence modification: "omni uses DROP+CREATE instead of ALTER SEQUENCE"
+func TestOmniDiffAudit_SequenceModification(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE SEQUENCE order_seq
+ START WITH 1
+ INCREMENT BY 1
+ CACHE 1;
+ `, `
+ CREATE SEQUENCE order_seq
+ START WITH 100
+ INCREMENT BY 5
+ CACHE 10;
+ `)
+ t.Logf("SQL output (sequence modification):\n%s", sql)
+
+ hasDropSequence := strings.Contains(sql, "DROP SEQUENCE")
+ hasCreateSequence := strings.Contains(sql, "CREATE SEQUENCE")
+ hasAlterSequence := strings.Contains(sql, "ALTER SEQUENCE")
+ t.Logf("Contains 'DROP SEQUENCE': %v", hasDropSequence)
+ t.Logf("Contains 'CREATE SEQUENCE': %v", hasCreateSequence)
+ t.Logf("Contains 'ALTER SEQUENCE': %v", hasAlterSequence)
+
+ if hasDropSequence && hasCreateSequence {
+ t.Log("Verdict: CONFIRMED - omni uses DROP+CREATE for sequence modification")
+ } else if hasAlterSequence && !hasDropSequence {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni uses ALTER SEQUENCE")
+ } else {
+ t.Log("Verdict: UNEXPECTED pattern")
+ }
+}
+
+// 9. Type normalization: "omni normalizes FLOAT to double precision"
+func TestOmniDiffAudit_TypeNormalization(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE t (f FLOAT);
+ `)
+ t.Logf("SQL output (FLOAT type):\n%s", sql)
+
+ hasDoublePrecision := strings.Contains(sql, "double precision")
+ hasFloat := strings.Contains(sql, "FLOAT") || strings.Contains(sql, "float")
+ t.Logf("Contains 'double precision': %v", hasDoublePrecision)
+ t.Logf("Contains 'float' (case-insensitive): %v", hasFloat)
+
+ if hasDoublePrecision {
+ t.Log("Verdict: CONFIRMED - omni normalizes FLOAT to double precision")
+ } else {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni preserves FLOAT as-is")
+ }
+}
+
+// 10. Identifier case: "omni lowercases unquoted identifiers"
+func TestOmniDiffAudit_IdentifierCase(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE MyTable (
+ MyColumn INTEGER PRIMARY KEY,
+ AnotherColumn TEXT
+ );
+ `)
+ t.Logf("SQL output (CamelCase identifiers):\n%s", sql)
+
+ hasLowerTable := strings.Contains(sql, "mytable")
+ hasOriginalTable := strings.Contains(sql, "MyTable")
+ hasLowerColumn := strings.Contains(sql, "mycolumn")
+ hasOriginalColumn := strings.Contains(sql, "MyColumn")
+ t.Logf("Contains 'mytable' (lowered): %v", hasLowerTable)
+ t.Logf("Contains 'MyTable' (original): %v", hasOriginalTable)
+ t.Logf("Contains 'mycolumn' (lowered): %v", hasLowerColumn)
+ t.Logf("Contains 'MyColumn' (original): %v", hasOriginalColumn)
+
+ if hasLowerTable && !hasOriginalTable {
+ t.Log("Verdict: CONFIRMED - omni lowercases unquoted identifiers")
+ } else if hasOriginalTable {
+ t.Log("Verdict: NOT A REAL DIFFERENCE - omni preserves original case")
+ } else {
+ t.Log("Verdict: UNEXPECTED pattern")
+ }
+}
diff --git a/backend/plugin/schema/pg/procedure_sdl_diff_omni_test.go b/backend/plugin/schema/pg/procedure_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..10ff11f101
--- /dev/null
+++ b/backend/plugin/schema/pg/procedure_sdl_diff_omni_test.go
@@ -0,0 +1,329 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniProcedureSDLDiff_CreateNew(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message) VALUES (msg);
+ END;
+ $$;
+ `)
+ require.Contains(t, sql, "CREATE PROCEDURE")
+ require.Contains(t, sql, "log_message")
+}
+
+func TestOmniProcedureSDLDiff_Drop(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message) VALUES (msg);
+ END;
+ $$;
+ `, `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+ `)
+ require.Contains(t, sql, "DROP PROCEDURE")
+ require.Contains(t, sql, "log_message")
+}
+
+func TestOmniProcedureSDLDiff_Modify(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message) VALUES (msg);
+ END;
+ $$;
+ `, `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message, created_at) VALUES (msg, NOW());
+ END;
+ $$;
+ `)
+ require.Contains(t, sql, "CREATE OR REPLACE PROCEDURE")
+ require.Contains(t, sql, "log_message")
+}
+
+func TestOmniProcedureSDLDiff_MixedFunctionsAndProcedures(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255),
+ email VARCHAR(255)
+ );
+
+ CREATE FUNCTION get_user_count() RETURNS INTEGER
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$;
+
+ CREATE PROCEDURE add_user(user_name TEXT, user_email TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO users (name, email) VALUES (user_name, user_email);
+ END;
+ $$;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255),
+ email VARCHAR(255)
+ );
+
+ CREATE FUNCTION get_user_count() RETURNS INTEGER
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$;
+
+ CREATE PROCEDURE update_user_email(user_id INTEGER, new_email TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ UPDATE users SET email = new_email WHERE id = user_id;
+ END;
+ $$;
+ `)
+ require.Contains(t, sql, "DROP PROCEDURE")
+ require.Contains(t, sql, "add_user")
+ require.Contains(t, sql, "CREATE PROCEDURE")
+ require.Contains(t, sql, "update_user_email")
+ require.NotContains(t, sql, "get_user_count")
+}
+
+func TestOmniProcedureSDLDiff_SchemaQualified(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE SCHEMA admin;
+ CREATE TABLE admin.settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT
+ );
+ `, `
+ CREATE SCHEMA admin;
+ CREATE TABLE admin.settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT
+ );
+
+ CREATE PROCEDURE admin.update_setting(setting_key TEXT, setting_value TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO admin.settings (key, value) VALUES (setting_key, setting_value)
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
+ END;
+ $$;
+ `)
+ require.Contains(t, sql, "CREATE PROCEDURE")
+ require.Contains(t, sql, "update_setting")
+}
+
+func TestOmniProcedureSDLDiff_CommentOnProcedure_Create(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE PROCEDURE new_procedure()
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RAISE NOTICE 'New procedure executed';
+ END;
+ $$;
+
+ COMMENT ON PROCEDURE new_procedure() IS 'A new procedure that raises a notice';
+ `)
+ require.Contains(t, sql, "CREATE PROCEDURE")
+ require.Contains(t, sql, "COMMENT ON PROCEDURE")
+ require.Contains(t, sql, "new_procedure")
+ require.Contains(t, sql, "A new procedure that raises a notice")
+}
+
+func TestOmniProcedureSDLDiff_CommentOnProcedure_EnsureNotFunction(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT
+ );
+ `, `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message) VALUES (msg);
+ END;
+ $$;
+
+ COMMENT ON PROCEDURE log_message(text) IS 'Logs a message to the logs table';
+ `)
+ require.Contains(t, sql, "CREATE PROCEDURE")
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "log_message")
+}
+
+func TestOmniProcedureSDLDiff_MixedComments(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE FUNCTION test_function()
+ RETURNS void
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RAISE NOTICE 'Test function executed';
+ END;
+ $$;
+
+ COMMENT ON FUNCTION test_function() IS 'A test function that raises a notice';
+
+ CREATE PROCEDURE test_procedure()
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RAISE NOTICE 'Test procedure executed';
+ END;
+ $$;
+
+ COMMENT ON PROCEDURE test_procedure() IS 'A test procedure that raises a notice';
+ `)
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "test_function")
+ require.Contains(t, sql, "test_procedure")
+ require.Contains(t, sql, "A test function that raises a notice")
+ require.Contains(t, sql, "A test procedure that raises a notice")
+}
+
+func TestOmniProcedureSDLDiff_DropColumnWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE test_table (
+ id serial PRIMARY KEY,
+ name character varying(100) NOT NULL,
+ test_column integer
+ );
+
+ COMMENT ON TABLE test_table IS 'A table for testing purposes';
+ COMMENT ON COLUMN test_table.test_column IS 'A test column for various uses';
+ `, `
+ CREATE TABLE test_table (
+ id serial PRIMARY KEY,
+ name character varying(100) NOT NULL
+ );
+
+ COMMENT ON TABLE test_table IS 'A table for testing purposes';
+ `)
+ require.Contains(t, sql, "DROP COLUMN")
+ require.Contains(t, sql, "test_column")
+}
+
+func TestOmniProcedureSDLDiff_DropTableWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE test_table (
+ id serial PRIMARY KEY,
+ name character varying(100) NOT NULL
+ );
+
+ COMMENT ON TABLE test_table IS 'A table for testing purposes';
+ `, "")
+ require.Contains(t, sql, "DROP TABLE")
+ require.Contains(t, sql, "test_table")
+}
+
+func TestOmniProcedureSDLDiff_RemoveProcedureComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE PROCEDURE new_procedure()
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RAISE NOTICE 'New procedure executed';
+ END;
+ $$;
+
+ COMMENT ON PROCEDURE new_procedure() IS 'A new procedure that raises a notice';
+ `, `
+ CREATE PROCEDURE new_procedure()
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RAISE NOTICE 'New procedure executed';
+ END;
+ $$;
+ `)
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "new_procedure")
+ require.Contains(t, sql, "NULL")
+}
+
+func TestOmniProcedureSDLDiff_UpdateProcedureComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE PROCEDURE log_message(msg text)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RAISE NOTICE '%', msg;
+ END;
+ $$;
+
+ COMMENT ON PROCEDURE log_message(text) IS 'Old comment';
+ `, `
+ CREATE PROCEDURE log_message(msg text)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RAISE NOTICE '%', msg;
+ END;
+ $$;
+
+ COMMENT ON PROCEDURE log_message(text) IS 'New comment';
+ `)
+ require.Contains(t, sql, "COMMENT ON")
+ require.Contains(t, sql, "New comment")
+ require.Contains(t, sql, "log_message")
+}
diff --git a/backend/plugin/schema/pg/schema_implicit_creation_omni_test.go b/backend/plugin/schema/pg/schema_implicit_creation_omni_test.go
new file mode 100644
index 0000000000..fcca653f35
--- /dev/null
+++ b/backend/plugin/schema/pg/schema_implicit_creation_omni_test.go
@@ -0,0 +1,128 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniImplicitSchemaCreation_AddTableInNewSchema(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY,
+ name VARCHAR(100)
+ );
+ `, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY,
+ name VARCHAR(100)
+ );
+
+ CREATE SCHEMA new_schema;
+
+ CREATE TABLE new_schema.t(
+ id INT PRIMARY KEY,
+ value VARCHAR(50)
+ );
+ `)
+ require.Contains(t, sql, "CREATE SCHEMA")
+ require.Contains(t, sql, "new_schema")
+ require.Contains(t, sql, "CREATE TABLE")
+}
+
+func TestOmniImplicitSchemaCreation_MultipleTablesInNewSchema(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY
+ );
+ `, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY
+ );
+
+ CREATE SCHEMA new_schema;
+
+ CREATE TABLE new_schema.users(
+ id INT PRIMARY KEY,
+ name VARCHAR(100)
+ );
+
+ CREATE TABLE new_schema.orders(
+ id INT PRIMARY KEY,
+ user_id INT REFERENCES new_schema.users(id)
+ );
+ `)
+ require.Contains(t, sql, "CREATE SCHEMA")
+ require.Contains(t, sql, "new_schema")
+ require.Contains(t, sql, "users")
+ require.Contains(t, sql, "orders")
+}
+
+func TestOmniImplicitSchemaCreation_ExplicitCreateSchema(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY,
+ name VARCHAR(100)
+ );
+ `, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY,
+ name VARCHAR(100)
+ );
+
+ CREATE SCHEMA new_schema;
+
+ CREATE TABLE new_schema.t(
+ id INT PRIMARY KEY,
+ value VARCHAR(50)
+ );
+ `)
+ require.Contains(t, sql, "CREATE SCHEMA")
+ require.Contains(t, sql, "new_schema")
+ require.Contains(t, sql, "CREATE TABLE")
+}
+
+func TestOmniImplicitSchemaCreation_ExplicitSchemaWithoutObjects(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY
+ );
+ `, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY
+ );
+
+ CREATE SCHEMA new_schema;
+ `)
+ require.Contains(t, sql, "CREATE SCHEMA")
+ require.Contains(t, sql, "new_schema")
+}
+
+func TestOmniImplicitSchemaCreation_MixedSchemas(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY
+ );
+ `, `
+ CREATE TABLE public.existing_table(
+ id INT PRIMARY KEY
+ );
+
+ CREATE SCHEMA schema_a;
+
+ CREATE TABLE schema_a.table_a(
+ id INT PRIMARY KEY
+ );
+
+ CREATE SCHEMA schema_b;
+
+ CREATE TABLE schema_b.table_b(
+ id INT PRIMARY KEY
+ );
+ `)
+ require.Contains(t, sql, "CREATE SCHEMA")
+ require.Contains(t, sql, "schema_a")
+ require.Contains(t, sql, "schema_b")
+ require.Contains(t, sql, "table_a")
+ require.Contains(t, sql, "table_b")
+}
diff --git a/backend/plugin/schema/pg/sdl_diff_table_omni_test.go b/backend/plugin/schema/pg/sdl_diff_table_omni_test.go
new file mode 100644
index 0000000000..7e4fbd1118
--- /dev/null
+++ b/backend/plugin/schema/pg/sdl_diff_table_omni_test.go
@@ -0,0 +1,155 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/omni/pg/catalog"
+)
+
+func TestOmniTableDiffScenarios(t *testing.T) {
+ testCases := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ wantNotContains []string
+ wantEmpty bool
+ // Diff-level assertions.
+ wantAddCount int
+ wantModifyCount int
+ wantDropCount int
+ wantNames []string
+ }{
+ {
+ name: "Create new table",
+ fromSDL: "",
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ wantContains: []string{"CREATE TABLE", "users"},
+ wantAddCount: 1,
+ wantNames: []string{"users"},
+ },
+ {
+ name: "Drop existing table",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ toSDL: "",
+ wantContains: []string{"DROP TABLE", "users"},
+ wantDropCount: 1,
+ wantNames: []string{"users"},
+ },
+ {
+ name: "Modify existing table",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255)
+ );`,
+ wantContains: []string{"ALTER TABLE", "email"},
+ wantModifyCount: 1,
+ wantNames: []string{"users"},
+ },
+ {
+ name: "Mixed operations",
+ fromSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE TABLE old_table (
+ id SERIAL PRIMARY KEY
+ );`,
+ toSDL: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255)
+ );
+
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );`,
+ wantContains: []string{"products", "old_table", "email"},
+ wantAddCount: 1, // products
+ wantModifyCount: 1, // users
+ wantDropCount: 1, // old_table
+ wantNames: []string{"users", "products", "old_table"},
+ },
+ {
+ name: "Schema qualified tables",
+ fromSDL: `CREATE TABLE public.users (
+ id SERIAL PRIMARY KEY
+ );`,
+ toSDL: `CREATE TABLE public.users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SCHEMA admin;
+ CREATE TABLE admin.settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT
+ );`,
+ wantContains: []string{"settings", "name"},
+ wantAddCount: 1, // admin.settings
+ wantModifyCount: 1, // public.users
+ wantNames: []string{"users", "settings"},
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tc.fromSDL, tc.toSDL)
+
+ if tc.wantEmpty {
+ require.Empty(t, sql)
+ return
+ }
+
+ for _, s := range tc.wantContains {
+ require.Contains(t, sql, s)
+ }
+ for _, s := range tc.wantNotContains {
+ require.NotContains(t, sql, s)
+ }
+
+ // Verify diff counts.
+ from, err := catalog.LoadSDL(strings.TrimSpace(tc.fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(tc.toSDL))
+ require.NoError(t, err)
+ diff := catalog.Diff(from, to)
+
+ addCount, modifyCount, dropCount := 0, 0, 0
+ var names []string
+ for _, r := range diff.Relations {
+ names = append(names, r.Name)
+ switch r.Action {
+ case catalog.DiffAdd:
+ addCount++
+ case catalog.DiffModify:
+ modifyCount++
+ case catalog.DiffDrop:
+ dropCount++
+ default:
+ }
+ }
+
+ require.Equal(t, tc.wantAddCount, addCount, "ADD count mismatch")
+ require.Equal(t, tc.wantModifyCount, modifyCount, "MODIFY count mismatch")
+ require.Equal(t, tc.wantDropCount, dropCount, "DROP count mismatch")
+ require.ElementsMatch(t, tc.wantNames, names, "relation names mismatch")
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/sdl_migration_omni.go b/backend/plugin/schema/pg/sdl_migration_omni.go
new file mode 100644
index 0000000000..1d55c282ed
--- /dev/null
+++ b/backend/plugin/schema/pg/sdl_migration_omni.go
@@ -0,0 +1,129 @@
+package pg
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/omni/pg/catalog"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+ "github.com/bytebase/bytebase/backend/store/model"
+)
+
+func init() {
+ schema.RegisterSDLMigration(storepb.Engine_POSTGRES, pgSDLMigration)
+ schema.RegisterSDLMigration(storepb.Engine_COCKROACHDB, pgSDLMigration)
+ schema.RegisterSDLDropAdvices(storepb.Engine_POSTGRES, pgSDLDropAdvices)
+ schema.RegisterSDLDropAdvices(storepb.Engine_COCKROACHDB, pgSDLDropAdvices)
+}
+
+// buildSDLCatalogs builds the from/to catalogs for an SDL migration.
+func buildSDLCatalogs(userSDLText string, currentSchema *model.DatabaseMetadata) (*catalog.Catalog, *catalog.Catalog, error) {
+ fromDDL, err := convertDatabaseSchemaToSDL(currentSchema)
+ if err != nil {
+ return nil, nil, errors.Wrap(err, "failed to convert current schema to DDL")
+ }
+
+ from, err := catalog.LoadSDL(fromDDL)
+ if err != nil {
+ return nil, nil, errors.Wrapf(err, "failed to load current schema into catalog")
+ }
+
+ to, err := catalog.LoadSDL(strings.TrimSpace(userSDLText))
+ if err != nil {
+ return nil, nil, errors.Wrapf(err, "failed to load user SDL into catalog")
+ }
+
+ return from, to, nil
+}
+
+// filterArchiveOps filters out bbdataarchive schema changes from a migration plan.
+func filterArchiveOps(plan *catalog.MigrationPlan) *catalog.MigrationPlan {
+ return plan.Filter(func(op catalog.MigrationOp) bool {
+ return op.SchemaName != "bbdataarchive"
+ })
+}
+
+// pgSDLMigration computes the migration SQL from a user-provided SDL text and
+// the current database schema using the omni catalog engine.
+func pgSDLMigration(userSDLText string, currentSchema *model.DatabaseMetadata) (string, error) {
+ from, to, err := buildSDLCatalogs(userSDLText, currentSchema)
+ if err != nil {
+ return "", err
+ }
+
+ diff := catalog.Diff(from, to)
+ if diff.IsEmpty() {
+ return "", nil
+ }
+
+ plan := filterArchiveOps(catalog.GenerateMigration(from, to, diff))
+ return plan.SQL(), nil
+}
+
+// pgSDLDropAdvices analyzes the SDL migration plan for destructive operations
+// and returns warnings.
+func pgSDLDropAdvices(userSDLText string, currentSchema *model.DatabaseMetadata) ([]*storepb.Advice, error) {
+ from, to, err := buildSDLCatalogs(userSDLText, currentSchema)
+ if err != nil {
+ return nil, err
+ }
+
+ diff := catalog.Diff(from, to)
+ if diff.IsEmpty() {
+ return nil, nil
+ }
+
+ plan := filterArchiveOps(catalog.GenerateMigration(from, to, diff))
+
+ var advices []*storepb.Advice
+ for _, op := range plan.Ops {
+ switch op.Type {
+ case catalog.OpDropSchema:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping schema '%s' will result in data loss.", op.ObjectName)))
+ case catalog.OpDropTable:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping table '%s.%s' will result in data loss.", op.SchemaName, op.ObjectName)))
+ case catalog.OpDropColumn:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping column from table '%s.%s' will result in data loss.", op.SchemaName, op.ParentObject)))
+ case catalog.OpDropView:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping view '%s.%s' will affect dependent objects.", op.SchemaName, op.ObjectName)))
+ case catalog.OpDropFunction:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping function '%s.%s' will affect dependent objects.", op.SchemaName, op.ObjectName)))
+ case catalog.OpDropSequence:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping sequence '%s.%s' may affect auto-increment columns.", op.SchemaName, op.ObjectName)))
+ case catalog.OpDropType:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping type '%s.%s' will affect columns using this type.", op.SchemaName, op.ObjectName)))
+ case catalog.OpDropTrigger:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping trigger '%s' on '%s.%s'.", op.ObjectName, op.SchemaName, op.ParentObject)))
+ case catalog.OpDropConstraint:
+ advices = append(advices, dropAdvice(fmt.Sprintf("Dropping constraint from table '%s.%s'.", op.SchemaName, op.ParentObject)))
+ case catalog.OpAlterFunction:
+ advices = append(advices, replaceAdvice(fmt.Sprintf("Function '%s.%s' definition will be replaced.", op.SchemaName, op.ObjectName)))
+ default:
+ }
+ }
+
+ return advices, nil
+}
+
+func dropAdvice(content string) *storepb.Advice {
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.SDLDropOperation.Int32(),
+ Title: "DROP operation detected",
+ Content: content,
+ }
+}
+
+func replaceAdvice(content string) *storepb.Advice {
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.SDLReplaceOperation.Int32(),
+ Title: "CREATE OR REPLACE operation detected",
+ Content: content,
+ }
+}
diff --git a/backend/plugin/schema/pg/sdl_migration_omni_test.go b/backend/plugin/schema/pg/sdl_migration_omni_test.go
new file mode 100644
index 0000000000..6bba75f3a8
--- /dev/null
+++ b/backend/plugin/schema/pg/sdl_migration_omni_test.go
@@ -0,0 +1,321 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/omni/pg/catalog"
+)
+
+// omniSDLMigration is a test helper that runs the omni SDL migration pipeline:
+// from = LoadSDL(fromSDL), to = LoadSDL(toSDL), Diff, GenerateMigration.
+func omniSDLMigration(t *testing.T, fromSDL, toSDL string) string {
+ t.Helper()
+ from, err := catalog.LoadSDL(strings.TrimSpace(fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(toSDL))
+ require.NoError(t, err)
+ diff := catalog.Diff(from, to)
+ if diff.IsEmpty() {
+ return ""
+ }
+ plan := catalog.GenerateMigration(from, to, diff)
+ return plan.SQL()
+}
+
+func TestOmniSDLMigration_CreateTable(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255) UNIQUE,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+ `)
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "users")
+}
+
+func TestOmniSDLMigration_DropTable(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE old_table (
+ id INTEGER PRIMARY KEY,
+ data TEXT
+ );
+ `, "")
+ require.Contains(t, sql, "DROP TABLE")
+ require.Contains(t, sql, "old_table")
+}
+
+func TestOmniSDLMigration_AddColumn(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255)
+ );
+ `)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "email")
+}
+
+func TestOmniSDLMigration_DropColumn(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255)
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `)
+ require.Contains(t, sql, "ALTER TABLE")
+ require.Contains(t, sql, "DROP COLUMN")
+ require.Contains(t, sql, "email")
+}
+
+func TestOmniSDLMigration_CreateView(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT TRUE
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT TRUE
+ );
+ CREATE VIEW active_users AS SELECT id, name FROM users WHERE active = TRUE;
+ `)
+ require.Contains(t, sql, "CREATE VIEW")
+ require.Contains(t, sql, "active_users")
+}
+
+func TestOmniSDLMigration_DropView(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT TRUE
+ );
+ CREATE VIEW active_users AS SELECT id, name FROM users WHERE active = TRUE;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT TRUE
+ );
+ `)
+ require.Contains(t, sql, "DROP VIEW")
+ require.Contains(t, sql, "active_users")
+}
+
+func TestOmniSDLMigration_CreateFunction(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER) RETURNS INTEGER
+ LANGUAGE plpgsql AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$;
+ `)
+ require.Contains(t, sql, "CREATE FUNCTION")
+ require.Contains(t, sql, "add_numbers")
+}
+
+func TestOmniSDLMigration_CreateSequence(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE SEQUENCE order_seq INCREMENT BY 1 MINVALUE 1 START WITH 1;
+ `)
+ require.Contains(t, sql, "CREATE SEQUENCE")
+ require.Contains(t, sql, "order_seq")
+}
+
+func TestOmniSDLMigration_CreateEnum(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
+ `)
+ require.Contains(t, sql, "CREATE TYPE")
+ require.Contains(t, sql, "mood")
+}
+
+func TestOmniSDLMigration_AlterEnum_AddValue(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
+ `, `
+ CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy', 'ecstatic');
+ `)
+ require.Contains(t, sql, "ecstatic")
+}
+
+func TestOmniSDLMigration_CreateIndex(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL
+ );
+ CREATE INDEX idx_users_email ON users (email);
+ `)
+ require.Contains(t, sql, "CREATE INDEX")
+ require.Contains(t, sql, "idx_users_email")
+}
+
+func TestOmniSDLMigration_CreateTrigger(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ updated_at TIMESTAMP
+ );
+ CREATE FUNCTION update_timestamp() RETURNS TRIGGER
+ LANGUAGE plpgsql AS $$
+ BEGIN
+ NEW.updated_at = NOW();
+ RETURN NEW;
+ END;
+ $$;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ updated_at TIMESTAMP
+ );
+ CREATE FUNCTION update_timestamp() RETURNS TRIGGER
+ LANGUAGE plpgsql AS $$
+ BEGIN
+ NEW.updated_at = NOW();
+ RETURN NEW;
+ END;
+ $$;
+ CREATE TRIGGER trg_update_timestamp
+ BEFORE UPDATE ON users
+ FOR EACH ROW EXECUTE FUNCTION update_timestamp();
+ `)
+ require.Contains(t, sql, "CREATE TRIGGER")
+ require.Contains(t, sql, "trg_update_timestamp")
+}
+
+func TestOmniSDLMigration_Comment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY
+ );
+ COMMENT ON TABLE users IS 'User accounts';
+ `)
+ require.Contains(t, sql, "COMMENT ON TABLE")
+ require.Contains(t, sql, "User accounts")
+}
+
+func TestOmniSDLMigration_NoChange(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `)
+ require.Empty(t, sql)
+}
+
+func TestOmniSDLMigration_CreateSchema(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE SCHEMA analytics;
+ CREATE TABLE analytics.events (
+ id SERIAL PRIMARY KEY,
+ event_name TEXT NOT NULL
+ );
+ `)
+ require.Contains(t, sql, "CREATE SCHEMA")
+ require.Contains(t, sql, "analytics")
+ require.Contains(t, sql, "CREATE TABLE")
+}
+
+func TestOmniSDLMigration_AddConstraint(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ total DECIMAL(10,2)
+ );
+ `, `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ total DECIMAL(10,2),
+ CONSTRAINT chk_total CHECK (total >= 0)
+ );
+ `)
+ require.Contains(t, sql, "chk_total")
+}
+
+func TestOmniSDLMigration_AddForeignKey(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE categories (
+ id SERIAL PRIMARY KEY,
+ name TEXT NOT NULL
+ );
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ category_id INTEGER
+ );
+ `, `
+ CREATE TABLE categories (
+ id SERIAL PRIMARY KEY,
+ name TEXT NOT NULL
+ );
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ category_id INTEGER,
+ CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id)
+ );
+ `)
+ require.Contains(t, sql, "fk_category")
+ require.Contains(t, sql, "FOREIGN KEY")
+}
+
+func TestOmniSDLMigration_MultipleChanges(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ CREATE TABLE old_table (
+ id INTEGER PRIMARY KEY
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255)
+ );
+ CREATE TABLE new_table (
+ id SERIAL PRIMARY KEY,
+ data TEXT
+ );
+ `)
+ require.Contains(t, sql, "DROP TABLE")
+ require.Contains(t, sql, "old_table")
+ require.Contains(t, sql, "email")
+ require.Contains(t, sql, "new_table")
+}
diff --git a/backend/plugin/schema/pg/sequence_migration_integration_omni_test.go b/backend/plugin/schema/pg/sequence_migration_integration_omni_test.go
new file mode 100644
index 0000000000..5178b31dfe
--- /dev/null
+++ b/backend/plugin/schema/pg/sequence_migration_integration_omni_test.go
@@ -0,0 +1,222 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniSequenceSDLDiffAndMigration(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ notContains []string
+ }{
+ {
+ name: "Create new sequence",
+ fromSDL: ``,
+ toSDL: `
+ CREATE SEQUENCE my_sequence
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 9223372036854775807
+ CACHE 1;
+ `,
+ contains: []string{"CREATE SEQUENCE", "my_sequence"},
+ },
+ {
+ name: "Drop sequence",
+ fromSDL: `
+ CREATE SEQUENCE user_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 2147483647
+ CACHE 1;
+ `,
+ toSDL: ``,
+ contains: []string{"DROP SEQUENCE", "user_id_seq"},
+ },
+ {
+ name: "Modify sequence",
+ fromSDL: `
+ CREATE SEQUENCE order_seq
+ START WITH 1
+ INCREMENT BY 1
+ CACHE 1;
+ `,
+ toSDL: `
+ CREATE SEQUENCE order_seq
+ START WITH 100
+ INCREMENT BY 5
+ CACHE 10;
+ `,
+ contains: []string{"order_seq"},
+ },
+ {
+ name: "Create sequence with data type",
+ fromSDL: ``,
+ toSDL: `
+ CREATE SEQUENCE bigint_sequence AS bigint
+ START WITH 1
+ INCREMENT BY 1;
+ `,
+ contains: []string{"CREATE SEQUENCE", "bigint_sequence"},
+ },
+ {
+ name: "Multiple sequences with different operations",
+ fromSDL: `
+ CREATE SEQUENCE seq_a START WITH 1;
+ CREATE SEQUENCE seq_b START WITH 1;
+ `,
+ toSDL: `
+ CREATE SEQUENCE seq_a START WITH 1;
+ CREATE SEQUENCE seq_c START WITH 1;
+ `,
+ contains: []string{"DROP SEQUENCE", "seq_b", "CREATE SEQUENCE", "seq_c"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ for _, s := range tt.notContains {
+ require.NotContains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniSequenceASTOnlyModeValidation(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE SEQUENCE test_sequence
+ START WITH 100
+ INCREMENT BY 2
+ CACHE 5;
+ `)
+ require.Contains(t, sql, "CREATE SEQUENCE")
+ require.Contains(t, sql, "test_sequence")
+}
+
+func TestOmniMultipleSequencesHandling(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE SEQUENCE seq1 START WITH 1;
+ `, `
+ CREATE SEQUENCE seq1 START WITH 1;
+ CREATE SEQUENCE seq2 START WITH 10 INCREMENT BY 2;
+ CREATE SEQUENCE seq3 AS bigint START WITH 1000;
+ `)
+ require.Contains(t, sql, "seq2")
+ require.Contains(t, sql, "seq3")
+ sequenceCount := strings.Count(sql, "CREATE SEQUENCE")
+ require.Equal(t, 2, sequenceCount)
+}
+
+func TestOmniSequenceOwnershipMigration(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ expectEmpty bool
+ }{
+ {
+ name: "Add ALTER SEQUENCE OWNED BY",
+ fromSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ order_number BIGINT NOT NULL
+ );
+
+ CREATE SEQUENCE custom_seq AS bigint START WITH 100 INCREMENT BY 5 MINVALUE 100 MAXVALUE 9223372036854775807 NO CYCLE CACHE 10;
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ order_number BIGINT NOT NULL
+ );
+
+ CREATE SEQUENCE custom_seq AS bigint START WITH 100 INCREMENT BY 5 MINVALUE 100 MAXVALUE 9223372036854775807 NO CYCLE CACHE 10;
+
+ ALTER SEQUENCE custom_seq OWNED BY orders.order_number;
+ `,
+ // Omni handles ownership changes via DROP/CREATE of the sequence
+ contains: []string{"custom_seq"},
+ },
+ {
+ name: "Modify ALTER SEQUENCE OWNED BY (change owner)",
+ fromSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ order_number BIGINT NOT NULL
+ );
+ CREATE TABLE products (
+ id BIGINT PRIMARY KEY,
+ product_code BIGINT NOT NULL
+ );
+
+ CREATE SEQUENCE custom_seq AS bigint START WITH 100 INCREMENT BY 5 NO CYCLE;
+
+ ALTER SEQUENCE custom_seq OWNED BY orders.order_number;
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ order_number BIGINT NOT NULL
+ );
+ CREATE TABLE products (
+ id BIGINT PRIMARY KEY,
+ product_code BIGINT NOT NULL
+ );
+
+ CREATE SEQUENCE custom_seq AS bigint START WITH 100 INCREMENT BY 5 NO CYCLE;
+
+ ALTER SEQUENCE custom_seq OWNED BY products.product_code;
+ `,
+ // Omni absorbs owned sequences into the table definition, so changing
+ // the ownership target between two owned columns produces an empty diff.
+ expectEmpty: true,
+ },
+ {
+ name: "Remove ALTER SEQUENCE OWNED BY",
+ fromSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ order_number BIGINT NOT NULL
+ );
+
+ CREATE SEQUENCE custom_seq AS bigint START WITH 100 INCREMENT BY 5 NO CYCLE;
+
+ ALTER SEQUENCE custom_seq OWNED BY orders.order_number;
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ order_number BIGINT NOT NULL
+ );
+
+ CREATE SEQUENCE custom_seq AS bigint START WITH 100 INCREMENT BY 5 NO CYCLE;
+ `,
+ contains: []string{"custom_seq"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ if tt.expectEmpty {
+ require.Empty(t, sql, "expected empty migration SQL")
+ }
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/sequence_sdl_diff_omni_test.go b/backend/plugin/schema/pg/sequence_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..a6802da8ca
--- /dev/null
+++ b/backend/plugin/schema/pg/sequence_sdl_diff_omni_test.go
@@ -0,0 +1,210 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniSequenceSDLDiff(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ validate func(t *testing.T, sql string)
+ }{
+ {
+ name: "Create new sequence",
+ fromSDL: ``,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "CREATE SEQUENCE")
+ require.Contains(t, sql, "user_seq")
+ },
+ },
+ {
+ name: "Drop sequence",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "DROP SEQUENCE")
+ require.Contains(t, sql, "user_seq")
+ },
+ },
+ {
+ name: "Modify sequence (alter)",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 10
+ INCREMENT BY 2
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 5;
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "user_seq")
+ },
+ },
+ {
+ name: "No changes to sequence",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `,
+ validate: func(t *testing.T, sql string) {
+ // No sequence-related changes expected
+ // The SQL might be empty or might not contain sequence statements
+ if sql != "" {
+ require.NotContains(t, sql, "CREATE SEQUENCE")
+ require.NotContains(t, sql, "DROP SEQUENCE")
+ }
+ },
+ },
+ {
+ name: "Multiple sequences with different changes",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 1
+ INCREMENT BY 1;
+
+ CREATE SEQUENCE order_seq
+ START WITH 100
+ INCREMENT BY 1;
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE SEQUENCE user_seq
+ START WITH 1
+ INCREMENT BY 1;
+
+ CREATE SEQUENCE product_seq
+ START WITH 1000
+ INCREMENT BY 10;
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ // order_seq should be dropped
+ require.Contains(t, sql, "order_seq")
+ // product_seq should be created
+ require.Contains(t, sql, "product_seq")
+ },
+ },
+ {
+ name: "Sequence with complex options",
+ fromSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ amount DECIMAL(10,2)
+ );
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id BIGINT PRIMARY KEY,
+ amount DECIMAL(10,2)
+ );
+
+ CREATE SEQUENCE order_id_seq
+ AS BIGINT
+ START WITH 1000000
+ INCREMENT BY 1
+ MINVALUE 1
+ MAXVALUE 9223372036854775807
+ CACHE 50
+ NO CYCLE;
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "CREATE SEQUENCE")
+ require.Contains(t, sql, "order_id_seq")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ tt.validate(t, sql)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/standalone_index_omni_test.go b/backend/plugin/schema/pg/standalone_index_omni_test.go
new file mode 100644
index 0000000000..1e70efe981
--- /dev/null
+++ b/backend/plugin/schema/pg/standalone_index_omni_test.go
@@ -0,0 +1,209 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniStandaloneCreateIndexSupport(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ validate func(t *testing.T, sql string)
+ }{
+ {
+ name: "Create new index",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE
+ );
+
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "CREATE INDEX")
+ require.Contains(t, sql, "idx_users_email")
+ },
+ },
+ {
+ name: "Drop index",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE
+ );
+
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE
+ );
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "DROP INDEX")
+ require.Contains(t, sql, "idx_users_email")
+ },
+ },
+ {
+ name: "Modify index (drop and recreate)",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE,
+ name VARCHAR(100)
+ );
+
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE,
+ name VARCHAR(100)
+ );
+
+ CREATE INDEX idx_users_email ON users(email, name);
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ // Should contain both drop and create for the modified index
+ require.Contains(t, sql, "idx_users_email")
+ },
+ },
+ {
+ name: "No changes to index",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE
+ );
+
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE
+ );
+
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.Empty(t, sql, "Should produce no migration for identical indexes")
+ },
+ },
+ {
+ name: "Complex index with WHERE clause",
+ fromSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ status VARCHAR(50),
+ customer_id INTEGER
+ );
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ status VARCHAR(50),
+ customer_id INTEGER
+ );
+
+ CREATE INDEX idx_orders_active ON orders(customer_id) WHERE status = 'active';
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "CREATE INDEX")
+ require.Contains(t, sql, "idx_orders_active")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ tt.validate(t, sql)
+ })
+ }
+}
+
+func TestOmniStandaloneIndexIntegrationWithTableChanges(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ validate func(t *testing.T, sql string)
+ }{
+ {
+ name: "Standalone index on existing table",
+ fromSDL: `CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));`,
+ toSDL: `
+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "CREATE INDEX")
+ require.Contains(t, sql, "idx_users_email")
+ },
+ },
+ {
+ name: "Table change and index change combined",
+ fromSDL: `
+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ toSDL: `
+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255), name VARCHAR(100));
+ CREATE INDEX idx_users_email_name ON users(email, name);
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ // New column added
+ require.Contains(t, sql, "name")
+ // New index created
+ require.Contains(t, sql, "idx_users_email_name")
+ // Old index dropped
+ require.Contains(t, sql, "idx_users_email")
+ },
+ },
+ {
+ name: "Multiple tables with index changes",
+ fromSDL: `
+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));
+ CREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INTEGER);
+ CREATE INDEX idx_users_email ON users(email);
+ `,
+ toSDL: `
+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));
+ CREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INTEGER);
+ CREATE INDEX idx_users_email ON users(email);
+ CREATE INDEX idx_orders_user_id ON orders(user_id);
+ `,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "CREATE INDEX")
+ require.Contains(t, sql, "idx_orders_user_id")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ tt.validate(t, sql)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/table_constraints_omni_test.go b/backend/plugin/schema/pg/table_constraints_omni_test.go
new file mode 100644
index 0000000000..6743353d3f
--- /dev/null
+++ b/backend/plugin/schema/pg/table_constraints_omni_test.go
@@ -0,0 +1,165 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniTableConstraintsSDLDiff(t *testing.T) {
+ testCases := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ validate func(t *testing.T, sql string)
+ }{
+ {
+ name: "Add primary key constraint",
+ fromSDL: `CREATE TABLE users (
+ id INTEGER,
+ name VARCHAR(255)
+ );`,
+ toSDL: `CREATE TABLE users (
+ id INTEGER,
+ name VARCHAR(255),
+ CONSTRAINT pk_users PRIMARY KEY (id)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "PRIMARY KEY")
+ require.Contains(t, sql, "pk_users")
+ },
+ },
+ {
+ name: "Drop foreign key constraint",
+ fromSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER PRIMARY KEY,
+ customer_id INTEGER,
+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
+ );`,
+ toSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER PRIMARY KEY,
+ customer_id INTEGER
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "fk_orders_customer")
+ require.Contains(t, sql, "DROP CONSTRAINT")
+ },
+ },
+ {
+ name: "Modify check constraint",
+ fromSDL: `CREATE TABLE products (
+ id INTEGER PRIMARY KEY,
+ price DECIMAL(10,2),
+ CONSTRAINT chk_price CHECK (price > 0)
+ );`,
+ toSDL: `CREATE TABLE products (
+ id INTEGER PRIMARY KEY,
+ price DECIMAL(10,2),
+ CONSTRAINT chk_price CHECK (price >= 0)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "chk_price")
+ },
+ },
+ {
+ name: "Multiple constraint types in one table",
+ fromSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER,
+ customer_id INTEGER,
+ order_date DATE,
+ amount DECIMAL(10,2),
+ status VARCHAR(20)
+ );`,
+ toSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER,
+ customer_id INTEGER,
+ order_date DATE,
+ amount DECIMAL(10,2),
+ status VARCHAR(20),
+ CONSTRAINT pk_orders PRIMARY KEY (id),
+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id),
+ CONSTRAINT uk_orders_date_customer UNIQUE (order_date, customer_id),
+ CONSTRAINT chk_positive_amount CHECK (amount > 0),
+ CONSTRAINT chk_valid_status CHECK (status IN ('pending', 'completed', 'cancelled'))
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "PRIMARY KEY")
+ require.Contains(t, sql, "FOREIGN KEY")
+ require.Contains(t, sql, "UNIQUE")
+ require.Contains(t, sql, "chk_positive_amount")
+ require.Contains(t, sql, "chk_valid_status")
+ },
+ },
+ {
+ name: "Complex foreign key with schema qualification",
+ fromSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER PRIMARY KEY,
+ customer_id INTEGER
+ );`,
+ toSDL: `CREATE TABLE customers (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ CREATE TABLE orders (
+ id INTEGER PRIMARY KEY,
+ customer_id INTEGER,
+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "fk_orders_customer")
+ require.Contains(t, sql, "FOREIGN KEY")
+ },
+ },
+ {
+ name: "Composite unique constraint",
+ fromSDL: `CREATE TABLE user_sessions (
+ user_id INTEGER,
+ session_token VARCHAR(255),
+ created_at TIMESTAMP
+ );`,
+ toSDL: `CREATE TABLE user_sessions (
+ user_id INTEGER,
+ session_token VARCHAR(255),
+ created_at TIMESTAMP,
+ CONSTRAINT uk_user_sessions UNIQUE (user_id, session_token)
+ );`,
+ validate: func(t *testing.T, sql string) {
+ require.NotEmpty(t, sql)
+ require.Contains(t, sql, "uk_user_sessions")
+ require.Contains(t, sql, "UNIQUE")
+ },
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tc.fromSDL, tc.toSDL)
+ tc.validate(t, sql)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/table_migration_integration_omni_test.go b/backend/plugin/schema/pg/table_migration_integration_omni_test.go
new file mode 100644
index 0000000000..32fdd06536
--- /dev/null
+++ b/backend/plugin/schema/pg/table_migration_integration_omni_test.go
@@ -0,0 +1,467 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniTableSDLDiffAndMigration(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "Create new table",
+ fromSDL: ``,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(255) UNIQUE,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+ `,
+ contains: []string{"CREATE TABLE", "users"},
+ },
+ {
+ name: "Drop table",
+ fromSDL: `
+ CREATE TABLE old_table (
+ id INTEGER PRIMARY KEY,
+ data TEXT
+ );
+ `,
+ toSDL: ``,
+ contains: []string{"DROP TABLE", "old_table"},
+ },
+ {
+ name: "Create table with constraints",
+ fromSDL: ``,
+ toSDL: `
+ CREATE TABLE categories (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ price DECIMAL(10,2) CHECK (price > 0),
+ category_id INTEGER,
+ CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id)
+ );
+ `,
+ contains: []string{"CREATE TABLE", "products", "FOREIGN KEY", "fk_category"},
+ },
+ {
+ name: "Create schema-qualified table",
+ fromSDL: ``,
+ toSDL: `
+ CREATE SCHEMA test_schema;
+ CREATE TABLE test_schema.items (
+ id BIGSERIAL PRIMARY KEY,
+ description TEXT
+ );
+ `,
+ contains: []string{"CREATE TABLE", "items"},
+ },
+ {
+ name: "Multiple tables with different operations",
+ fromSDL: `
+ CREATE TABLE table_a (id INTEGER PRIMARY KEY);
+ CREATE TABLE table_b (id INTEGER PRIMARY KEY);
+ `,
+ toSDL: `
+ CREATE TABLE table_a (id INTEGER PRIMARY KEY);
+ CREATE TABLE table_c (id INTEGER PRIMARY KEY);
+ `,
+ contains: []string{"DROP TABLE", "table_b", "CREATE TABLE", "table_c"},
+ },
+ {
+ name: "Create table with various data types",
+ fromSDL: ``,
+ toSDL: `
+ CREATE TABLE data_types_test (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ title VARCHAR(100),
+ content TEXT,
+ count INTEGER,
+ amount DECIMAL(15,2),
+ is_active BOOLEAN DEFAULT false,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ metadata JSONB
+ );
+ `,
+ contains: []string{"CREATE TABLE", "data_types_test"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniTableConstraintChanges(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ notContains []string
+ }{
+ {
+ name: "Add CHECK constraint",
+ fromSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price > 0)
+ );
+ `,
+ contains: []string{"chk_price", "CHECK"},
+ },
+ {
+ name: "Add FOREIGN KEY constraint",
+ fromSDL: `
+ CREATE TABLE customers (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE customers (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
+ );
+ `,
+ contains: []string{"fk_customer", "FOREIGN KEY"},
+ },
+ {
+ name: "Add UNIQUE constraint",
+ fromSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL,
+ CONSTRAINT unique_email UNIQUE (email)
+ );
+ `,
+ contains: []string{"unique_email", "UNIQUE"},
+ },
+ {
+ name: "Drop CHECK constraint",
+ fromSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price > 0)
+ );
+ `,
+ toSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ contains: []string{"chk_price", "DROP"},
+ },
+ {
+ name: "Drop FOREIGN KEY constraint",
+ fromSDL: `
+ CREATE TABLE customers (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
+ );
+ `,
+ toSDL: `
+ CREATE TABLE customers (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL
+ );
+ `,
+ contains: []string{"fk_customer", "DROP"},
+ },
+ {
+ name: "Add PRIMARY KEY constraint",
+ fromSDL: `
+ CREATE TABLE users (
+ id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ toSDL: `
+ CREATE TABLE users (
+ id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ CONSTRAINT pk_users PRIMARY KEY (id)
+ );
+ `,
+ contains: []string{"pk_users", "PRIMARY KEY"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ for _, s := range tt.notContains {
+ require.NotContains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniTableIndexChanges(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "Create standalone indexes",
+ fromSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending'
+ );
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending'
+ );
+
+ CREATE INDEX idx_orders_customer_id ON orders (customer_id);
+ CREATE UNIQUE INDEX idx_orders_status_unique ON orders (status);
+ `,
+ contains: []string{"CREATE INDEX", "idx_orders_customer_id", "idx_orders_status_unique"},
+ },
+ {
+ name: "Drop standalone indexes",
+ fromSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending'
+ );
+
+ CREATE INDEX idx_orders_customer_id ON orders (customer_id);
+ CREATE UNIQUE INDEX idx_orders_status_unique ON orders (status);
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending'
+ );
+ `,
+ contains: []string{"DROP INDEX", "idx_orders_customer_id", "idx_orders_status_unique"},
+ },
+ {
+ name: "Replace indexes (drop old, create new)",
+ fromSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending'
+ );
+
+ CREATE INDEX idx_orders_old ON orders (customer_id);
+ `,
+ toSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending'
+ );
+
+ CREATE INDEX idx_orders_new ON orders (customer_id, status);
+ `,
+ contains: []string{"DROP INDEX", "idx_orders_old", "CREATE INDEX", "idx_orders_new"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniComplexTableWithConstraintsAndIndexes(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE customers (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ order_date DATE DEFAULT CURRENT_DATE,
+ total_amount DECIMAL(12,2) NOT NULL CHECK (total_amount >= 0),
+ status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'confirmed', 'shipped', 'delivered')),
+ created_at TIMESTAMP DEFAULT NOW(),
+ updated_at TIMESTAMP DEFAULT NOW(),
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE,
+ CONSTRAINT unique_customer_date UNIQUE (customer_id, order_date)
+ );
+ `)
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "orders")
+ require.Contains(t, sql, "fk_customer")
+ require.Contains(t, sql, "FOREIGN KEY")
+ require.Contains(t, sql, "unique_customer_date")
+ require.Contains(t, sql, "UNIQUE")
+}
+
+func TestOmniMultipleTablesHandling(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE table1 (id INTEGER PRIMARY KEY);
+ `, `
+ CREATE TABLE table1 (id INTEGER PRIMARY KEY);
+ CREATE TABLE table2 (id SERIAL PRIMARY KEY, name TEXT);
+ CREATE TABLE table3 (id UUID PRIMARY KEY, data JSONB);
+ `)
+ require.Contains(t, sql, "table2")
+ require.Contains(t, sql, "table3")
+ tableCount := strings.Count(sql, "CREATE TABLE")
+ require.Equal(t, 2, tableCount)
+}
+
+func TestOmniTableComplexConstraintChanges(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL UNIQUE,
+ age INTEGER CHECK (age >= 18),
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ amount DECIMAL(10,2) NOT NULL,
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id)
+ );
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL,
+ age INTEGER CHECK (age >= 16),
+ phone VARCHAR(20) UNIQUE,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ amount DECIMAL(10,2) NOT NULL CHECK (amount > 0),
+ status VARCHAR(20) DEFAULT 'pending',
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT unique_user_amount UNIQUE (user_id, amount)
+ );
+ `)
+ require.Contains(t, sql, "users")
+ require.Contains(t, sql, "orders")
+}
+
+func TestOmniCreateTableWithMultipleConstraints(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE customers (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE orders (
+ id SERIAL,
+ customer_id INTEGER NOT NULL,
+ order_date DATE DEFAULT CURRENT_DATE,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending',
+ created_at TIMESTAMP DEFAULT NOW(),
+ CONSTRAINT pk_orders PRIMARY KEY (id),
+ CONSTRAINT chk_total_amount CHECK (total_amount >= 0),
+ CONSTRAINT chk_status CHECK (status IN ('pending', 'confirmed', 'shipped', 'delivered')),
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE,
+ CONSTRAINT unique_customer_date UNIQUE (customer_id, order_date)
+ );
+ `)
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "pk_orders")
+ require.Contains(t, sql, "chk_total_amount")
+ require.Contains(t, sql, "chk_status")
+ require.Contains(t, sql, "fk_customer")
+ require.Contains(t, sql, "unique_customer_date")
+}
+
+func TestOmniCreateTableWithForeignKeyActions(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY
+ );
+ CREATE TABLE order_items (
+ id SERIAL PRIMARY KEY,
+ order_id INTEGER NOT NULL,
+ product_id INTEGER NOT NULL,
+ quantity INTEGER NOT NULL DEFAULT 1,
+ unit_price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_quantity CHECK (quantity > 0),
+ CONSTRAINT chk_unit_price CHECK (unit_price > 0),
+ CONSTRAINT fk_order FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT unique_order_product UNIQUE (order_id, product_id)
+ );
+ `)
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "order_items")
+ require.Contains(t, sql, "fk_order")
+ require.Contains(t, sql, "fk_product")
+ require.Contains(t, sql, "ON DELETE CASCADE")
+ require.Contains(t, sql, "ON DELETE RESTRICT")
+}
diff --git a/backend/plugin/schema/pg/trigger_drop_dependency_omni_test.go b/backend/plugin/schema/pg/trigger_drop_dependency_omni_test.go
new file mode 100644
index 0000000000..b13aebd7be
--- /dev/null
+++ b/backend/plugin/schema/pg/trigger_drop_dependency_omni_test.go
@@ -0,0 +1,224 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniDropTriggerDependencyOrder(t *testing.T) {
+ previousSDL := `
+ CREATE TABLE test_products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100),
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE test_orders (
+ id SERIAL PRIMARY KEY,
+ product_id INTEGER,
+ quantity INTEGER,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE audit_log (
+ id SERIAL PRIMARY KEY,
+ table_name VARCHAR(50),
+ operation VARCHAR(10),
+ changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE FUNCTION update_timestamp_trigger_func()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.updated_at = CURRENT_TIMESTAMP;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION audit_trigger_func()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ INSERT INTO audit_log (table_name, operation)
+ VALUES (TG_TABLE_NAME, TG_OP);
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER update_timestamp_trigger
+ BEFORE UPDATE ON test_products
+ FOR EACH ROW EXECUTE FUNCTION update_timestamp_trigger_func();
+
+ CREATE TRIGGER audit_insert_trigger
+ AFTER INSERT ON test_products
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER audit_update_trigger
+ AFTER UPDATE ON test_products
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER audit_delete_trigger
+ AFTER DELETE ON test_products
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER update_timestamp_trigger
+ BEFORE UPDATE ON test_orders
+ FOR EACH ROW EXECUTE FUNCTION update_timestamp_trigger_func();
+
+ CREATE TRIGGER audit_insert_trigger
+ AFTER INSERT ON test_orders
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER audit_delete_trigger
+ AFTER DELETE ON test_orders
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+ `
+
+ sql := omniSDLMigration(t, previousSDL, "")
+
+ t.Logf("Migration:\n%s", sql)
+
+ dropFunctionIdx := strings.Index(sql, "DROP FUNCTION")
+ dropTableIdx := strings.Index(sql, "DROP TABLE")
+
+ require.NotEqual(t, -1, dropFunctionIdx, "Should have DROP FUNCTION statements")
+ require.NotEqual(t, -1, dropTableIdx, "Should have DROP TABLE statements")
+
+ // The omni engine uses DROP TABLE CASCADE which handles triggers implicitly.
+ // If DROP TRIGGER is present, it must come before DROP FUNCTION.
+ dropTriggerIdx := strings.Index(sql, "DROP TRIGGER")
+ if dropTriggerIdx != -1 {
+ require.Less(t, dropTriggerIdx, dropFunctionIdx, "DROP TRIGGER must come before DROP FUNCTION")
+ }
+
+ // Tables are dropped with CASCADE before functions (CASCADE handles trigger deps)
+ require.Less(t, dropTableIdx, dropFunctionIdx, "DROP TABLE CASCADE must come before DROP FUNCTION")
+}
+
+func TestOmniCreateTriggerDependencyOrder(t *testing.T) {
+ currentSDL := `
+ CREATE TABLE test_products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100),
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE test_orders (
+ id SERIAL PRIMARY KEY,
+ product_id INTEGER,
+ quantity INTEGER,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE audit_log (
+ id SERIAL PRIMARY KEY,
+ table_name VARCHAR(50),
+ operation VARCHAR(10),
+ changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE FUNCTION update_timestamp_trigger_func()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.updated_at = CURRENT_TIMESTAMP;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION audit_trigger_func()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ INSERT INTO audit_log (table_name, operation)
+ VALUES (TG_TABLE_NAME, TG_OP);
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER update_timestamp_trigger
+ BEFORE UPDATE ON test_products
+ FOR EACH ROW EXECUTE FUNCTION update_timestamp_trigger_func();
+
+ CREATE TRIGGER audit_insert_trigger
+ AFTER INSERT ON test_products
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER audit_update_trigger
+ AFTER UPDATE ON test_products
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER audit_delete_trigger
+ AFTER DELETE ON test_products
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER update_timestamp_trigger
+ BEFORE UPDATE ON test_orders
+ FOR EACH ROW EXECUTE FUNCTION update_timestamp_trigger_func();
+
+ CREATE TRIGGER audit_insert_trigger
+ AFTER INSERT ON test_orders
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+
+ CREATE TRIGGER audit_delete_trigger
+ AFTER DELETE ON test_orders
+ FOR EACH ROW EXECUTE FUNCTION audit_trigger_func();
+ `
+
+ sql := omniSDLMigration(t, "", currentSDL)
+
+ t.Logf("Migration:\n%s", sql)
+
+ createTableIdx := strings.Index(sql, "CREATE TABLE")
+ createFunctionIdx := strings.Index(sql, "CREATE FUNCTION")
+ createTriggerIdx := strings.Index(sql, "CREATE TRIGGER")
+
+ require.NotEqual(t, -1, createTableIdx, "Should have CREATE TABLE statements")
+ require.NotEqual(t, -1, createFunctionIdx, "Should have CREATE FUNCTION statements")
+ require.NotEqual(t, -1, createTriggerIdx, "Should have CREATE TRIGGER statements")
+
+ // Critical: tables must be created before triggers
+ require.Less(t, createTableIdx, createTriggerIdx, "CREATE TABLE must come before CREATE TRIGGER")
+
+ // Critical: functions must be created before triggers
+ require.Less(t, createFunctionIdx, createTriggerIdx, "CREATE FUNCTION must come before CREATE TRIGGER")
+
+ // Count total triggers
+ triggerCount := strings.Count(sql, "CREATE TRIGGER")
+ require.Equal(t, 7, triggerCount, "Should have exactly 7 triggers")
+}
+
+func TestOmniSameTriggerNameOnDifferentTables(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE FUNCTION update_timestamp()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.updated_at = CURRENT_TIMESTAMP;
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER update_timestamp_trigger
+ BEFORE UPDATE ON users
+ FOR EACH ROW EXECUTE FUNCTION update_timestamp();
+
+ CREATE TRIGGER update_timestamp_trigger
+ BEFORE UPDATE ON orders
+ FOR EACH ROW EXECUTE FUNCTION update_timestamp();
+ `)
+
+ t.Logf("Migration:\n%s", sql)
+
+ require.Contains(t, sql, "update_timestamp_trigger")
+ require.Contains(t, sql, "users")
+ require.Contains(t, sql, "orders")
+}
diff --git a/backend/plugin/schema/pg/trigger_sdl_diff_omni_test.go b/backend/plugin/schema/pg/trigger_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..221b486db9
--- /dev/null
+++ b/backend/plugin/schema/pg/trigger_sdl_diff_omni_test.go
@@ -0,0 +1,358 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniTriggerDiff_CreateTrigger(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100)
+ );
+
+ CREATE FUNCTION audit_log() RETURNS TRIGGER AS $$
+ BEGIN
+ RAISE NOTICE 'Audit';
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+ `, `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100)
+ );
+
+ CREATE FUNCTION audit_log() RETURNS TRIGGER AS $$
+ BEGIN
+ RAISE NOTICE 'Audit';
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit_log();
+ `)
+ require.Contains(t, sql, "CREATE")
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "audit_trigger")
+}
+
+func TestOmniTriggerDiff_SimpleTrigger(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `)
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "t1")
+}
+
+func TestOmniTriggerDiff_MultipleTriggersSameTable(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ CREATE TRIGGER t2 BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `)
+ require.Contains(t, sql, "t1")
+ require.Contains(t, sql, "t2")
+}
+
+func TestOmniTriggerDiff_SchemaQualifiedTable(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE SCHEMA app;
+ CREATE TABLE app.users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION app.f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON app.users FOR EACH ROW EXECUTE FUNCTION app.f();
+ `)
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "t1")
+}
+
+func TestOmniTriggerDiff_TriggerComment(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ COMMENT ON TRIGGER audit_trigger ON users IS 'Audit log trigger';
+ `)
+ require.Contains(t, sql, "COMMENT ON TRIGGER")
+ require.Contains(t, sql, "audit_trigger")
+ require.Contains(t, sql, "Audit log trigger")
+}
+
+func TestOmniTriggerDiff_DropTrigger(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ `)
+ require.Contains(t, sql, "DROP TRIGGER")
+ require.Contains(t, sql, "audit_trigger")
+ require.Contains(t, sql, "users")
+}
+
+func TestOmniTriggerDiff_CreateWithDependencyOrder(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION audit_log() RETURNS TRIGGER AS $$
+ BEGIN
+ RAISE NOTICE 'Audit';
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit_log();
+ `)
+
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "audit_trigger")
+
+ tableIdx := strings.Index(sql, "CREATE TABLE")
+ functionIdx := strings.Index(sql, "CREATE FUNCTION")
+ // The omni engine uses CREATE TRIGGER (not CREATE OR REPLACE TRIGGER)
+ triggerIdx := strings.Index(sql, "CREATE TRIGGER")
+
+ require.NotEqual(t, -1, tableIdx, "Table must be created")
+ require.NotEqual(t, -1, functionIdx, "Function must be created")
+ require.NotEqual(t, -1, triggerIdx, "Trigger must be created")
+
+ require.Less(t, tableIdx, triggerIdx, "Table must be created before trigger")
+ require.Less(t, functionIdx, triggerIdx, "Function must be created before trigger")
+}
+
+func TestOmniTriggerDiff_StandaloneCreate(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `)
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "t1")
+}
+
+func TestOmniTriggerDiff_StandaloneDrop(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ `)
+ require.Contains(t, sql, "DROP TRIGGER")
+ require.Contains(t, sql, "t1")
+}
+
+func TestOmniTriggerDiff_StandaloneModify(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT OR UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `)
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "t1")
+}
+
+func TestOmniTriggerDiff_StandaloneNoChange(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `)
+ require.Empty(t, sql)
+}
+
+func TestOmniTriggerDiff_MultipleTriggersIntegration(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE orders (id SERIAL PRIMARY KEY, status VARCHAR(20));
+ CREATE FUNCTION log_insert() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE FUNCTION log_update() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER insert_trigger AFTER INSERT ON orders FOR EACH ROW EXECUTE FUNCTION log_insert();
+ CREATE TRIGGER update_trigger BEFORE UPDATE ON orders FOR EACH ROW EXECUTE FUNCTION log_update();
+ `)
+ require.Contains(t, sql, "insert_trigger")
+ require.Contains(t, sql, "update_trigger")
+}
+
+func TestOmniTriggerDiff_SchemaQualifiedIntegration(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE SCHEMA app;
+ CREATE TABLE app.events (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION app.notify() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER event_trigger AFTER INSERT ON app.events FOR EACH ROW EXECUTE FUNCTION app.notify();
+ `)
+ require.Contains(t, sql, "event_trigger")
+ require.Contains(t, sql, "app")
+}
+
+func TestOmniTriggerDiff_WhenCondition(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE products (id SERIAL PRIMARY KEY, price NUMERIC);
+ CREATE FUNCTION check_price() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER price_check
+ BEFORE UPDATE ON products
+ FOR EACH ROW
+ WHEN (NEW.price > 1000)
+ EXECUTE FUNCTION check_price();
+ `)
+ require.Contains(t, sql, "WHEN")
+ require.Contains(t, sql, "price")
+}
+
+func TestOmniTriggerDiff_ModifyPreservesOther(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ CREATE TRIGGER t2 AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT OR UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f();
+ CREATE TRIGGER t2 AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION f();
+ `)
+ require.Contains(t, sql, "t1")
+ require.NotContains(t, sql, "t2")
+}
+
+func TestOmniTriggerDiff_MultipleEvents(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE audit_log (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION log_changes() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER multi_event_trigger
+ AFTER INSERT OR UPDATE OR DELETE ON audit_log
+ FOR EACH ROW EXECUTE FUNCTION log_changes();
+ `)
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "INSERT OR UPDATE OR DELETE")
+}
+
+func TestOmniTriggerDiff_ForEachStatement(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE statements (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION stmt_trigger() RETURNS TRIGGER AS $$ BEGIN RETURN NULL; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER statement_level_trigger
+ AFTER INSERT ON statements
+ FOR EACH STATEMENT EXECUTE FUNCTION stmt_trigger();
+ `)
+ require.Contains(t, sql, "FOR EACH STATEMENT")
+}
+
+func TestOmniTriggerDiff_MultipleComments(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE events (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON events FOR EACH ROW EXECUTE FUNCTION f();
+ CREATE TRIGGER t2 AFTER UPDATE ON events FOR EACH ROW EXECUTE FUNCTION f();
+ COMMENT ON TRIGGER t1 ON events IS 'Insert trigger';
+ COMMENT ON TRIGGER t2 ON events IS 'Update trigger';
+ `)
+ require.Contains(t, sql, "Insert trigger")
+ require.Contains(t, sql, "Update trigger")
+}
+
+func TestOmniTriggerDiff_DropTriggerWithComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER t1 AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION f();
+ COMMENT ON TRIGGER t1 ON users IS 'My trigger';
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION f() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ `)
+ require.Contains(t, sql, "DROP TRIGGER")
+ require.Contains(t, sql, "t1")
+}
+
+func TestOmniTriggerDiff_ReferencingColumns(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE inventory (id SERIAL PRIMARY KEY, stock INT);
+ CREATE FUNCTION check_stock() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER stock_check
+ BEFORE UPDATE OF stock ON inventory
+ FOR EACH ROW EXECUTE FUNCTION check_stock();
+ `)
+ require.Contains(t, sql, "UPDATE OF")
+ require.Contains(t, sql, "stock_check")
+ require.Contains(t, sql, "TRIGGER")
+ require.Contains(t, sql, "inventory")
+}
+
+func TestOmniTriggerDiff_ModifyCommentOnly(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION audit() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit();
+ COMMENT ON TRIGGER audit_trigger ON users IS 'Original comment';
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION audit() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit();
+ COMMENT ON TRIGGER audit_trigger ON users IS 'Updated comment';
+ `)
+ require.Contains(t, sql, "COMMENT ON TRIGGER")
+ require.Contains(t, sql, "Updated comment")
+}
+
+func TestOmniTriggerDiff_AddCommentToExisting(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION audit() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit();
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION audit() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit();
+ COMMENT ON TRIGGER audit_trigger ON users IS 'New comment';
+ `)
+ require.Contains(t, sql, "COMMENT ON TRIGGER")
+ require.Contains(t, sql, "New comment")
+}
+
+func TestOmniTriggerDiff_RemoveComment(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION audit() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit();
+ COMMENT ON TRIGGER audit_trigger ON users IS 'Old comment';
+ `, `
+ CREATE TABLE users (id SERIAL PRIMARY KEY);
+ CREATE FUNCTION audit() RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;
+ CREATE TRIGGER audit_trigger
+ AFTER INSERT ON users
+ FOR EACH ROW EXECUTE FUNCTION audit();
+ `)
+ require.Contains(t, sql, "COMMENT ON TRIGGER")
+ require.Contains(t, sql, "NULL")
+}
diff --git a/backend/plugin/schema/pg/view_migration_integration_omni_test.go b/backend/plugin/schema/pg/view_migration_integration_omni_test.go
new file mode 100644
index 0000000000..a2aaa861b8
--- /dev/null
+++ b/backend/plugin/schema/pg/view_migration_integration_omni_test.go
@@ -0,0 +1,212 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOmniViewSDLDiffAndMigration(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ contains []string
+ }{
+ {
+ name: "Create new view",
+ fromSDL: ``,
+ toSDL: `
+ CREATE VIEW active_users AS
+ SELECT 1 as id, 'test' as name;
+ `,
+ contains: []string{"CREATE VIEW", "active_users"},
+ },
+ {
+ name: "Drop view",
+ fromSDL: `
+ CREATE VIEW active_users AS
+ SELECT 1 as id, 'test' as name;
+ `,
+ toSDL: ``,
+ contains: []string{"DROP VIEW", "active_users"},
+ },
+ {
+ name: "Modify view (drop and recreate)",
+ fromSDL: `
+ CREATE VIEW active_users AS
+ SELECT 1 as id, 'test' as name;
+ `,
+ toSDL: `
+ CREATE VIEW active_users AS
+ SELECT 2 as id, 'updated' as name, 'extra' as email;
+ `,
+ contains: []string{"active_users"},
+ },
+ {
+ name: "Schema-qualified view",
+ fromSDL: ``,
+ toSDL: `
+ CREATE SCHEMA test_schema;
+ CREATE VIEW test_schema.expensive_products AS
+ SELECT 1 as id, 'product' as name, 150.00 as price;
+ `,
+ contains: []string{"CREATE VIEW", "expensive_products"},
+ },
+ {
+ name: "Multiple view changes",
+ fromSDL: `
+ CREATE VIEW user_summary AS
+ SELECT 1 as id, 'user' as name;
+
+ CREATE VIEW order_summary AS
+ SELECT 1 as id, 100.00 as amount;
+ `,
+ toSDL: `
+ CREATE VIEW user_summary AS
+ SELECT 2 as id, 'updated_user' as name, 'active' as status;
+
+ CREATE VIEW order_analytics AS
+ SELECT 1 as user_id, 500.00 as total_amount;
+ `,
+ contains: []string{"order_summary", "order_analytics", "user_summary"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+ for _, s := range tt.contains {
+ require.Contains(t, sql, s)
+ }
+ })
+ }
+}
+
+func TestOmniViewDependencyHandling(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE VIEW base_data AS
+ SELECT 1 as id, 'item1' as name, 100 as value;
+
+ CREATE VIEW summary_report AS
+ SELECT b.name, b.value, b.value * 2 as doubled_value
+ FROM base_data b
+ WHERE b.value > 50;
+ `)
+ require.Contains(t, sql, "CREATE VIEW")
+ require.Contains(t, sql, "base_data")
+ require.Contains(t, sql, "summary_report")
+
+ // base_data should be created before summary_report
+ baseIndex := strings.Index(sql, "base_data")
+ summaryIndex := strings.Index(sql, "summary_report")
+ require.True(t, baseIndex < summaryIndex,
+ "base_data should appear before summary_report")
+}
+
+func TestOmniDropTableAndDependentView_CorrectOrder(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE users (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL
+ );
+
+ CREATE VIEW active_users AS
+ SELECT id, name, email
+ FROM users
+ WHERE email IS NOT NULL;
+ `, "")
+
+ // Omni uses DROP TABLE ... CASCADE which handles dependent views,
+ // so both DROP TABLE and DROP VIEW should be present
+ require.Contains(t, sql, "DROP TABLE")
+ require.Contains(t, sql, "users")
+ require.Contains(t, sql, "active_users")
+}
+
+func TestOmniCreateTableAndDependentView_CorrectOrder(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE users (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL
+ );
+
+ CREATE VIEW active_users AS
+ SELECT id, name, email
+ FROM users
+ WHERE email IS NOT NULL;
+ `)
+
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "CREATE VIEW")
+
+ tableCreateIndex := strings.Index(sql, "CREATE TABLE")
+ viewCreateIndex := strings.Index(sql, "CREATE VIEW")
+ require.True(t, tableCreateIndex < viewCreateIndex,
+ "CREATE TABLE must come before CREATE VIEW")
+}
+
+func TestOmniCreateMultipleTablesAndViews_CorrectOrder(t *testing.T) {
+ sql := omniSDLMigration(t, "", `
+ CREATE TABLE categories (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL
+ );
+
+ CREATE TABLE products (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL,
+ category_id INTEGER REFERENCES categories(id)
+ );
+
+ CREATE VIEW product_summary AS
+ SELECT p.id, p.name, c.name as category_name
+ FROM products p
+ JOIN categories c ON p.category_id = c.id;
+ `)
+
+ require.Contains(t, sql, "CREATE TABLE")
+ require.Contains(t, sql, "CREATE VIEW")
+
+ categoriesIndex := strings.Index(sql, "categories")
+ viewIndex := strings.Index(sql, "CREATE VIEW")
+ require.True(t, categoriesIndex < viewIndex,
+ "CREATE TABLE categories must come before CREATE VIEW")
+
+ productsIndex := strings.Index(sql, "products")
+ require.True(t, productsIndex < viewIndex,
+ "CREATE TABLE products must come before CREATE VIEW")
+}
+
+func TestOmniDropMultipleTablesAndViews_CorrectOrder(t *testing.T) {
+ sql := omniSDLMigration(t, `
+ CREATE TABLE categories (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL
+ );
+
+ CREATE TABLE products (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL,
+ category_id INTEGER REFERENCES categories(id)
+ );
+
+ CREATE VIEW product_summary AS
+ SELECT p.id, p.name, c.name as category_name
+ FROM products p
+ JOIN categories c ON p.category_id = c.id;
+ `, "")
+
+ require.Contains(t, sql, "DROP VIEW")
+ require.Contains(t, sql, "DROP TABLE")
+
+ viewDropIndex := strings.Index(sql, "DROP VIEW")
+ productsTableDropIndex := strings.Index(sql, "products")
+ // Find the DROP TABLE that mentions products (not the view reference)
+ // The view drop should come first
+ require.True(t, viewDropIndex >= 0, "DROP VIEW should be present")
+ _ = productsTableDropIndex // products appears in both drop statements
+}
diff --git a/backend/plugin/schema/pg/view_sdl_diff_omni_test.go b/backend/plugin/schema/pg/view_sdl_diff_omni_test.go
new file mode 100644
index 0000000000..6c7ff928da
--- /dev/null
+++ b/backend/plugin/schema/pg/view_sdl_diff_omni_test.go
@@ -0,0 +1,209 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/omni/pg/catalog"
+)
+
+func TestOmniViewSDLDiff(t *testing.T) {
+ tests := []struct {
+ name string
+ fromSDL string
+ toSDL string
+ wantContains []string
+ wantEmpty bool
+ // Diff-level assertions on Relations (views are relations in omni).
+ wantViewAdd int
+ wantViewDrop int
+ }{
+ {
+ name: "Create new view",
+ fromSDL: ``,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE VIEW active_users AS
+SELECT id, name
+FROM users
+WHERE active = true;`,
+ wantContains: []string{"CREATE VIEW", "active_users"},
+ wantViewAdd: 1,
+ },
+ {
+ name: "Drop view",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE VIEW active_users AS
+SELECT id, name
+FROM users
+WHERE active = true;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);`,
+ wantContains: []string{"DROP VIEW", "active_users"},
+ wantViewDrop: 1,
+ },
+ {
+ name: "Modify view definition",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE VIEW active_users AS
+SELECT id, name
+FROM users
+WHERE active = true;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE VIEW active_users AS
+SELECT id, name, 'active' as status
+FROM users
+WHERE active = true;`,
+ wantContains: []string{"active_users"},
+ },
+ {
+ name: "No changes to view",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE VIEW active_users AS
+SELECT id, name
+FROM users
+WHERE active = true;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+);
+
+CREATE VIEW active_users AS
+SELECT id, name
+FROM users
+WHERE active = true;`,
+ wantEmpty: true,
+ },
+ {
+ name: "Multiple views with different changes",
+ fromSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true,
+ role TEXT
+);
+
+CREATE VIEW all_users AS
+SELECT * FROM users;
+
+CREATE VIEW active_users AS
+SELECT id, name FROM users WHERE active = true;`,
+ toSDL: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true,
+ role TEXT
+);
+
+CREATE VIEW all_users AS
+SELECT * FROM users;
+
+CREATE VIEW admin_users AS
+SELECT id, name FROM users WHERE role = 'admin';`,
+ wantContains: []string{"admin_users", "active_users"},
+ wantViewAdd: 1, // admin_users
+ wantViewDrop: 1, // active_users
+ },
+ {
+ name: "Schema-qualified view names",
+ fromSDL: `
+CREATE SCHEMA test_schema;
+CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+);`,
+ toSDL: `
+CREATE SCHEMA test_schema;
+CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+);
+
+CREATE VIEW test_schema.product_summary AS
+SELECT id, name FROM test_schema.products;`,
+ wantContains: []string{"CREATE VIEW", "product_summary"},
+ wantViewAdd: 1,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sql := omniSDLMigration(t, tt.fromSDL, tt.toSDL)
+
+ if tt.wantEmpty {
+ require.Empty(t, sql)
+ return
+ }
+
+ for _, s := range tt.wantContains {
+ require.Contains(t, sql, s)
+ }
+
+ // Verify diff-level view counts when specified.
+ if tt.wantViewAdd > 0 || tt.wantViewDrop > 0 {
+ from, err := catalog.LoadSDL(strings.TrimSpace(tt.fromSDL))
+ require.NoError(t, err)
+ to, err := catalog.LoadSDL(strings.TrimSpace(tt.toSDL))
+ require.NoError(t, err)
+ diff := catalog.Diff(from, to)
+
+ addCount, dropCount := 0, 0
+ for _, r := range diff.Relations {
+ switch r.Action {
+ case catalog.DiffAdd:
+ // Only count views (relations with To that are views).
+ if r.To != nil && r.To.RelKind == 'v' {
+ addCount++
+ }
+ case catalog.DiffDrop:
+ if r.From != nil && r.From.RelKind == 'v' {
+ dropCount++
+ }
+ default:
+ }
+ }
+ require.Equal(t, tt.wantViewAdd, addCount, "view ADD count mismatch")
+ require.Equal(t, tt.wantViewDrop, dropCount, "view DROP count mismatch")
+ }
+ })
+ }
+}
diff --git a/backend/plugin/schema/schema.go b/backend/plugin/schema/schema.go
index 51c4cf146d..ff1e8871c5 100644
--- a/backend/plugin/schema/schema.go
+++ b/backend/plugin/schema/schema.go
@@ -24,6 +24,8 @@ var (
getDatabaseMetadataMap = make(map[storepb.Engine]getDatabaseMetadata)
generateMigrations = make(map[storepb.Engine]generateMigration)
getSDLDiffs = make(map[storepb.Engine]getSDLDiff)
+ sdlMigrations = make(map[storepb.Engine]sdlMigration)
+ sdlDropAdvicesFns = make(map[storepb.Engine]sdlDropAdvices)
getMultiFileDatabaseDefinitions = make(map[storepb.Engine]getMultiFileDatabaseDefinition)
walkThroughs = make(map[storepb.Engine]walkThrough)
walkThroughsWithContext = make(map[storepb.Engine]walkThroughWithContext)
@@ -41,6 +43,8 @@ type getSequenceDefinition func(string, *storepb.SequenceMetadata) (string, erro
type getDatabaseMetadata func(string) (*storepb.DatabaseSchemaMetadata, error)
type generateMigration func(*MetadataDiff) (string, error)
type getSDLDiff func(currentSDLText, previousUserSDLText string, currentSchema *model.DatabaseMetadata) (*MetadataDiff, error)
+type sdlMigration func(userSDLText string, currentSchema *model.DatabaseMetadata) (string, error)
+type sdlDropAdvices func(userSDLText string, currentSchema *model.DatabaseMetadata) ([]*storepb.Advice, error)
type walkThrough func(*model.DatabaseMetadata, []base.AST) *storepb.Advice
type walkThroughWithContext func(WalkThroughContext, *model.DatabaseMetadata, []base.AST) *storepb.Advice
@@ -262,6 +266,43 @@ func GetSDLDiff(engine storepb.Engine, currentSDLText, previousUserSDLText strin
return f(currentSDLText, previousUserSDLText, currentSchema)
}
+func RegisterSDLMigration(engine storepb.Engine, f sdlMigration) {
+ mux.Lock()
+ defer mux.Unlock()
+ if _, dup := sdlMigrations[engine]; dup {
+ panic(fmt.Sprintf("Register called twice %s", engine))
+ }
+ sdlMigrations[engine] = f
+}
+
+// SDLMigration computes the migration SQL from a user-provided SDL text and the
+// current database schema. It combines diff and migration generation in one step.
+func SDLMigration(engine storepb.Engine, userSDLText string, currentSchema *model.DatabaseMetadata) (string, error) {
+ f, ok := sdlMigrations[engine]
+ if !ok {
+ return "", errors.Errorf("engine %s is not supported for SDL migration", engine)
+ }
+ return f(userSDLText, currentSchema)
+}
+
+func RegisterSDLDropAdvices(engine storepb.Engine, f sdlDropAdvices) {
+ mux.Lock()
+ defer mux.Unlock()
+ if _, dup := sdlDropAdvicesFns[engine]; dup {
+ panic(fmt.Sprintf("Register called twice %s", engine))
+ }
+ sdlDropAdvicesFns[engine] = f
+}
+
+// SDLDropAdvices analyzes the SDL migration for destructive operations and returns warnings.
+func SDLDropAdvices(engine storepb.Engine, userSDLText string, currentSchema *model.DatabaseMetadata) ([]*storepb.Advice, error) {
+ f, ok := sdlDropAdvicesFns[engine]
+ if !ok {
+ return nil, errors.Errorf("engine %s is not supported for SDL drop advices", engine)
+ }
+ return f(userSDLText, currentSchema)
+}
+
func RegisterGetMultiFileDatabaseDefinition(engine storepb.Engine, f getMultiFileDatabaseDefinition) {
mux.Lock()
defer mux.Unlock()
diff --git a/backend/runner/taskrun/database_migrate_executor.go b/backend/runner/taskrun/database_migrate_executor.go
index d6ffb1ab20..38c204a781 100644
--- a/backend/runner/taskrun/database_migrate_executor.go
+++ b/backend/runner/taskrun/database_migrate_executor.go
@@ -1071,11 +1071,6 @@ func (v *prependStatementsVisitor) extractStatementText(ctx *postgresql.Variable
}
func diff(ctx context.Context, s *store.Store, instance *store.InstanceMessage, database *store.DatabaseMessage, sheetContent string) (string, error) {
- pengine, err := common.ConvertToParserEngine(instance.Metadata.GetEngine())
- if err != nil {
- return "", errors.Wrapf(err, "failed to convert %q to parser engine", instance.Metadata.GetEngine())
- }
-
dbMetadata, err := s.GetDBSchema(ctx, &store.FindDBSchemaMessage{
Workspace: instance.Workspace,
InstanceID: database.InstanceID,
@@ -1088,96 +1083,14 @@ func diff(ctx context.Context, s *store.Store, instance *store.InstanceMessage,
return "", errors.Errorf("database schema %q not found", database.DatabaseName)
}
- // Get the previous SDL text from the database's release field
- previousUserSDLText, err := getPreviousSDL(ctx, s, database.InstanceID, database.DatabaseName)
- if err != nil {
- return "", errors.Wrapf(err, "failed to get previous SDL text for database %q", database.DatabaseName)
- }
-
- // Use GetSDLDiff to compute the schema diff
- // - engine: the database engine
- // - currentSDLText: user's target SDL input
- // - previousUserSDLText: previous SDL text (empty triggers initialization scenario)
- // - currentSchema: current database schema
- schemaDiff, err := schema.GetSDLDiff(pengine, sheetContent, previousUserSDLText, dbMetadata)
- if err != nil {
- return "", errors.Wrap(err, "failed to compute SDL schema diff")
- }
-
- // Filter out bbdataarchive schema changes for Postgres
- if instance.Metadata.GetEngine() == storepb.Engine_POSTGRES {
- schemaDiff = schema.FilterPostgresArchiveSchema(schemaDiff)
- }
-
- migrationSQL, err := schema.GenerateMigration(pengine, schemaDiff)
+ migrationSQL, err := schema.SDLMigration(instance.Metadata.GetEngine(), sheetContent, dbMetadata)
if err != nil {
- return "", errors.Wrapf(err, "failed to generate migration SQL")
+ return "", errors.Wrapf(err, "failed to compute SDL migration")
}
return migrationSQL, nil
}
-// getPreviousSDL gets the SDL text from the database's tracked release field.
-// Returns empty string if no previous release exists.
-func getPreviousSDL(ctx context.Context, s *store.Store, instanceID string, databaseName string) (string, error) {
- // Get the database to access the last applied release
- database, err := s.GetDatabase(ctx, &store.FindDatabaseMessage{
- InstanceID: &instanceID,
- DatabaseName: &databaseName,
- })
- if err != nil {
- return "", errors.Wrapf(err, "failed to get database %s", databaseName)
- }
- if database == nil {
- return "", errors.Errorf("database %s not found", databaseName)
- }
-
- // Get the previous SDL text from the database's release field
- if database.Metadata == nil || database.Metadata.Release == "" {
- return "", nil
- }
-
- // Parse release name to get project ID and release ID
- projectID, releaseID, err := common.GetProjectReleaseID(database.Metadata.Release)
- if err != nil {
- slog.Warn("Failed to parse release name, treating as initialization", "release", database.Metadata.Release, "error", err)
- return "", nil
- }
-
- // Load the release
- release, err := s.GetRelease(ctx, &store.FindReleaseMessage{
- ProjectID: &projectID,
- ReleaseID: &releaseID,
- })
- if err != nil {
- slog.Warn("Failed to get release, treating as initialization", "project", projectID, "release", releaseID, "error", err)
- return "", nil
- }
- if release == nil {
- slog.Warn("Release not found, treating as initialization", "project", projectID, "release", releaseID)
- return "", nil
- }
-
- // For SDL/declarative releases, there should be exactly one file
- if len(release.Payload.Files) != 1 {
- slog.Warn("Unexpected number of files in SDL release, treating as initialization", "expected", 1, "got", len(release.Payload.Files))
- return "", nil
- }
-
- file := release.Payload.Files[0]
- sheet, err := s.GetSheetFull(ctx, file.SheetSha256)
- if err != nil {
- slog.Warn("Failed to get sheet, treating as initialization", "sha256", file.SheetSha256, "error", err)
- return "", nil
- }
- if sheet == nil {
- slog.Warn("Sheet not found, treating as initialization", "sha256", file.SheetSha256)
- return "", nil
- }
-
- return sheet.Statement, nil
-}
-
// computeNeedDump determines if schema dump is needed based on task type and statements.
func computeNeedDump(taskType storepb.Task_Type, engine storepb.Engine, statement string) bool {
//exhaustive:enforce
diff --git a/backend/tests/pg_sdl_rollout_test.go b/backend/tests/pg_sdl_rollout_test.go
index 6390ea057c..83246810a0 100644
--- a/backend/tests/pg_sdl_rollout_test.go
+++ b/backend/tests/pg_sdl_rollout_test.go
@@ -103,6 +103,9 @@ CREATE INDEX "idx_posts_user_id" ON "public"."posts"("user_id");`
a.NoError(err)
a.NotEmpty(result.ExecutedStatements, "Expected SQL statements to be executed")
+ // Sync database metadata after rollout so the next step sees the latest state
+ syncDatabaseMetadata(ctx, a, ctl, database)
+
// Verify initial schema was created
a.True(verifyTableExists(ctx, ctl, database, "users"))
a.True(verifyTableExists(ctx, ctl, database, "posts"))
@@ -141,6 +144,9 @@ CREATE TABLE "public"."comments" (
a.NoError(err)
a.NotEmpty(result.ExecutedStatements, "Expected ALTER/CREATE statements to be executed")
+ // Sync database metadata after rollout
+ syncDatabaseMetadata(ctx, a, ctl, database)
+
// Verify schema was updated
a.True(verifyTableExists(ctx, ctl, database, "users"))
a.True(verifyTableExists(ctx, ctl, database, "posts"))
@@ -205,6 +211,7 @@ CREATE TABLE "public"."posts" (
_, err = executeSDLRolloutWithResult(ctx, ctl, database, initialSDL)
a.NoError(err)
+ syncDatabaseMetadata(ctx, a, ctl, database)
a.True(verifyTableExists(ctx, ctl, database, "test_table"))
// Apply empty SDL to drop all objects
@@ -246,6 +253,7 @@ CREATE TABLE "public"."posts" (
_, err = executeSDLRolloutWithResult(ctx, ctl, database, sdl)
a.NoError(err)
+ syncDatabaseMetadata(ctx, a, ctl, database)
// Apply same SDL again - should be a no-op
result, err := executeSDLRolloutWithResult(ctx, ctl, database, sdl)
@@ -259,6 +267,14 @@ CREATE TABLE "public"."posts" (
})
}
+// syncDatabaseMetadata forces a metadata sync so the next SDL rollout sees the latest schema state.
+func syncDatabaseMetadata(ctx context.Context, a *require.Assertions, ctl *controller, database *v1pb.Database) {
+ _, err := ctl.databaseServiceClient.SyncDatabase(ctx, connect.NewRequest(&v1pb.SyncDatabaseRequest{
+ Name: database.Name,
+ }))
+ a.NoError(err, "Failed to sync database metadata")
+}
+
// executeSDLRolloutWithResult performs a complete SDL rollout and returns the result including executed SQL.
func executeSDLRolloutWithResult(ctx context.Context, ctl *controller, database *v1pb.Database, sdlContent string) (*sdlRolloutResult, error) {
// Create a DECLARATIVE release with SDL content
diff --git a/go.mod b/go.mod
index d974f5c410..f668b3b1bd 100644
--- a/go.mod
+++ b/go.mod
@@ -34,7 +34,7 @@ require (
github.com/bmatcuk/doublestar/v4 v4.10.0
github.com/bytebase/gomongo v0.0.0-20260324061529-f15b9a5add35
github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0
- github.com/bytebase/omni v0.0.0-20260324084257-a8ae1438840a
+ github.com/bytebase/omni v0.0.0-20260326070405-a1a6e5880a1e
github.com/caarlos0/env/v11 v11.4.0
github.com/cenkalti/backoff/v5 v5.0.3
github.com/cockroachdb/cockroachdb-parser v0.25.2
@@ -62,7 +62,7 @@ require (
github.com/hashicorp/vault/api/auth/approle v0.11.0
github.com/jackc/pgconn v1.14.3
github.com/jackc/pgtype v1.14.4
- github.com/jackc/pgx/v5 v5.8.0
+ github.com/jackc/pgx/v5 v5.9.1
github.com/labstack/echo-contrib/v5 v5.0.1
github.com/lestrrat-go/jwx/v3 v3.0.13
github.com/lib/pq v1.11.2
diff --git a/go.sum b/go.sum
index 3a3b153abe..1a01bb8d72 100644
--- a/go.sum
+++ b/go.sum
@@ -253,8 +253,8 @@ github.com/bytebase/gomongo v0.0.0-20260324061529-f15b9a5add35 h1:SjcZSrUMNj6GZq
github.com/bytebase/gomongo v0.0.0-20260324061529-f15b9a5add35/go.mod h1:jHdAD+tN3bO2Hazme0crgkNiHqkDR/3Igesy1chhjLA=
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-20260324084257-a8ae1438840a h1:DVUpZCKOHiNUu/0++lHmqMyrss42Ndinwzr1wipTBwA=
-github.com/bytebase/omni v0.0.0-20260324084257-a8ae1438840a/go.mod h1:btZOCeNcueZehdqT+7YsLSVm+srVGSoPZYvFlITO2Z8=
+github.com/bytebase/omni v0.0.0-20260326070405-a1a6e5880a1e h1:fIG16JzgGnL7s2R7hkzOTnMoA3rjUUOI7DvY9F1Peck=
+github.com/bytebase/omni v0.0.0-20260326070405-a1a6e5880a1e/go.mod h1:1HI7B1k/5jH/Po89iGM6fMoz+Jh1PqUHfgeudpZSdkk=
github.com/bytebase/parser v0.0.0-20260324092042-1d52e5412f50 h1:Kq5wlhZ586Rch39y/IQV9MnrEzHob4iiXBG6zrbvSMU=
github.com/bytebase/parser v0.0.0-20260324092042-1d52e5412f50/go.mod h1:jeak/EfutSOAuWKvrFIT2IZunhWprM7oTFBRgZ9RCxo=
github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767 h1:YuR5G3LcxpO5ScSTA+Kdirxg9RW4TRc/v1t7N2Hfmbw=
@@ -997,6 +997,8 @@ github.com/testcontainers/testcontainers-go v0.41.0 h1:mfpsD0D36YgkxGj2LrIyxuwQ9
github.com/testcontainers/testcontainers-go v0.41.0/go.mod h1:pdFrEIfaPl24zmBjerWTTYaY0M6UHsqA1YSvsoU40MI=
github.com/testcontainers/testcontainers-go/modules/mongodb v0.40.0 h1:z/1qHeliTLDKNaJ7uOHOx1FjwghbcbYfga4dTFkF0hU=
github.com/testcontainers/testcontainers-go/modules/mongodb v0.40.0/go.mod h1:GaunAWwMXLtsMKG3xn2HYIBDbKddGArfcGsF2Aog81E=
+github.com/testcontainers/testcontainers-go/modules/postgres v0.41.0 h1:AOtFXssrDlLm84A2sTTR/AhvJiYbrIuCO59d+Ro9Tb0=
+github.com/testcontainers/testcontainers-go/modules/postgres v0.41.0/go.mod h1:k2a09UKhgSp6vNpliIY0QSgm4Hi7GXVTzWvWgUemu/8=
github.com/the42/cartconvert v0.0.0-20131203171324-aae784c392b8 h1:I4DY8wLxJXCrMYzDM6lKCGc3IQwJX0PlTLsd3nQqI3c=
github.com/the42/cartconvert v0.0.0-20131203171324-aae784c392b8/go.mod h1:fWO/msnJVhHqN1yX6OBoxSyfj7TEj1hHiL8bJSQsK30=
github.com/tiancaiamao/gp v0.0.0-20221230034425-4025bc8a4d4a h1:J/YdBZ46WKpXsxsW93SG+q0F8KI+yFrcIDT4c/RNoc4=