Skip to content

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

feat(schemadiff): support compute schema diff and generate DDLs (#2471)

Joe Chenb598fb2fe8b4
diff --git a/plugin/parser/schemadiff.go b/plugin/parser/schemadiff.go
new file mode 100644
index 0000000000..fcd45de261
--- /dev/null
+++ b/plugin/parser/schemadiff.go
@@ -0,0 +1,43 @@
+package parser
+
+import (
+ "bytes"
+
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+// SchemaDiff computes the schema differences between old and new schema.
+func SchemaDiff(old, new []ast.Node) (string, error) {
+ oldTables := make(map[string]*ast.CreateTableStmt)
+ for _, node := range old {
+ if n, ok := node.(*ast.CreateTableStmt); ok {
+ oldTables[n.Name.Name] = n
+ }
+ }
+
+ var diffs []ast.Node
+ for _, node := range new {
+ if newTable, ok := node.(*ast.CreateTableStmt); ok {
+ _, hasTable := oldTables[newTable.Name.Name]
+ if !hasTable {
+ diffs = append(diffs, node)
+ continue
+ }
+ }
+ }
+
+ // NOTE: Due to limitation of current deparse implementation, we directly
+ // generate the final DDLs here instead of returning []ast.Node to the caller.
+ deparse := func(nodes []ast.Node) string {
+ var buf bytes.Buffer
+ for _, node := range nodes {
+ if n, ok := node.(*ast.CreateTableStmt); ok {
+ _, _ = buf.WriteString(n.Text())
+ _, _ = buf.WriteString("\n")
+ }
+ }
+ return buf.String()
+ }
+
+ return deparse(diffs), nil
+}
diff --git a/plugin/parser/schemadiff_test.go b/plugin/parser/schemadiff_test.go
new file mode 100644
index 0000000000..a6c05ade5c
--- /dev/null
+++ b/plugin/parser/schemadiff_test.go
@@ -0,0 +1,44 @@
+package parser_test
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/plugin/parser"
+ // Register PostgreSQL parser engine.
+ _ "github.com/bytebase/bytebase/plugin/parser/engine/pg"
+)
+
+func TestComputeDiff(t *testing.T) {
+ oldSchema, err := parser.Parse(parser.Postgres, parser.ParseContext{}, `
+CREATE TABLE projects ();
+`)
+ require.NoError(t, err)
+ newSchema, err := parser.Parse(parser.Postgres, parser.ParseContext{}, `
+CREATE TABLE users (
+ id serial PRIMARY KEY,
+ username TEXT NOT NULL
+);
+CREATE TABLE projects ();
+CREATE TABLE repositories (
+ id serial PRIMARY KEY
+);
+`)
+ require.NoError(t, err)
+
+ got, err := parser.SchemaDiff(oldSchema, newSchema)
+ require.NoError(t, err)
+
+ // The DDLs for the diff should be in the exact same order as the DDLs in the new schema.
+ want := `CREATE TABLE users (
+ id serial PRIMARY KEY,
+ username TEXT NOT NULL
+);
+CREATE TABLE repositories (
+ id serial PRIMARY KEY
+);
+`
+ assert.Equal(t, want, got)
+}