computeDiff computes the difference between current and expected schemas
(current, expected *sdata.DBInfo, opts DiffOptions)
| 207 | |
| 208 | // computeDiff computes the difference between current and expected schemas |
| 209 | func computeDiff(current, expected *sdata.DBInfo, opts DiffOptions) []SchemaOperation { |
| 210 | dialect := getDDLDialect(expected.Type) |
| 211 | if dialect == nil { |
| 212 | dialect = getDDLDialect(current.Type) |
| 213 | } |
| 214 | if dialect == nil { |
| 215 | return nil |
| 216 | } |
| 217 | |
| 218 | var ops []SchemaOperation |
| 219 | |
| 220 | // Build maps for efficient lookup |
| 221 | currentTables := make(map[string]*sdata.DBTable) |
| 222 | for i := range current.Tables { |
| 223 | t := ¤t.Tables[i] |
| 224 | currentTables[t.Name] = t |
| 225 | } |
| 226 | |
| 227 | expectedTables := make(map[string]*sdata.DBTable) |
| 228 | for i := range expected.Tables { |
| 229 | t := &expected.Tables[i] |
| 230 | expectedTables[t.Name] = t |
| 231 | } |
| 232 | |
| 233 | // Find tables to create |
| 234 | // Sort tables to create parent tables before children (FK dependency order) |
| 235 | sortedTables := sortTablesByDependency(expected.Tables) |
| 236 | for _, expTable := range sortedTables { |
| 237 | if _, exists := currentTables[expTable.Name]; !exists { |
| 238 | sql := dialect.CreateTable(expTable) |
| 239 | ops = append(ops, SchemaOperation{ |
| 240 | Type: "create_table", |
| 241 | Table: expTable.Name, |
| 242 | SQL: sql, |
| 243 | }) |
| 244 | |
| 245 | // Add indexes for searchable, unique, and indexed columns |
| 246 | for _, col := range expTable.Columns { |
| 247 | if col.FullText { |
| 248 | sql := dialect.CreateSearchIndex(expTable.Name, col) |
| 249 | if sql != "" { |
| 250 | ops = append(ops, SchemaOperation{ |
| 251 | Type: "add_index", |
| 252 | Table: expTable.Name, |
| 253 | Column: col.Name, |
| 254 | SQL: sql, |
| 255 | }) |
| 256 | } |
| 257 | } |
| 258 | if col.UniqueKey && !col.PrimaryKey { |
| 259 | sql := dialect.CreateUniqueIndex(expTable.Name, col) |
| 260 | if sql != "" { |
| 261 | ops = append(ops, SchemaOperation{ |
| 262 | Type: "add_index", |
| 263 | Table: expTable.Name, |
| 264 | Column: col.Name, |
| 265 | SQL: sql, |
| 266 | }) |