(schemaName, tableName string, colDiff *schema.ColumnDiff)
| 725 | } |
| 726 | |
| 727 | func generateAlterColumn(schemaName, tableName string, colDiff *schema.ColumnDiff) string { |
| 728 | var buf strings.Builder |
| 729 | |
| 730 | // In MSSQL, we need to handle different aspects of column changes separately |
| 731 | |
| 732 | // If type changed, alter the column type |
| 733 | if colDiff.OldColumn.Type != colDiff.NewColumn.Type { |
| 734 | _, _ = buf.WriteString("ALTER TABLE [") |
| 735 | _, _ = buf.WriteString(schemaName) |
| 736 | _, _ = buf.WriteString("].[") |
| 737 | _, _ = buf.WriteString(tableName) |
| 738 | _, _ = buf.WriteString("] ALTER COLUMN [") |
| 739 | _, _ = buf.WriteString(colDiff.NewColumn.Name) |
| 740 | _, _ = buf.WriteString("] ") |
| 741 | _, _ = buf.WriteString(colDiff.NewColumn.Type) |
| 742 | if colDiff.NewColumn.Nullable { |
| 743 | _, _ = buf.WriteString(" NULL") |
| 744 | } else { |
| 745 | _, _ = buf.WriteString(" NOT NULL") |
| 746 | } |
| 747 | _, _ = buf.WriteString(";\n") |
| 748 | } else if colDiff.OldColumn.Nullable != colDiff.NewColumn.Nullable { |
| 749 | // If only nullability changed |
| 750 | _, _ = buf.WriteString("ALTER TABLE [") |
| 751 | _, _ = buf.WriteString(schemaName) |
| 752 | _, _ = buf.WriteString("].[") |
| 753 | _, _ = buf.WriteString(tableName) |
| 754 | _, _ = buf.WriteString("] ALTER COLUMN [") |
| 755 | _, _ = buf.WriteString(colDiff.NewColumn.Name) |
| 756 | _, _ = buf.WriteString("] ") |
| 757 | _, _ = buf.WriteString(colDiff.NewColumn.Type) |
| 758 | if colDiff.NewColumn.Nullable { |
| 759 | _, _ = buf.WriteString(" NULL") |
| 760 | } else { |
| 761 | _, _ = buf.WriteString(" NOT NULL") |
| 762 | } |
| 763 | _, _ = buf.WriteString(";\n") |
| 764 | } |
| 765 | |
| 766 | // Handle default value changes |
| 767 | oldDefault := getColumnDefaultValue(colDiff.OldColumn) |
| 768 | newDefault := getColumnDefaultValue(colDiff.NewColumn) |
| 769 | |
| 770 | if oldDefault != newDefault { |
| 771 | // First, drop the existing default constraint if it exists |
| 772 | if oldDefault != "" { |
| 773 | if colDiff.OldColumn.DefaultConstraintName != "" { |
| 774 | // Use the known constraint name directly (when synced from database) |
| 775 | _, _ = buf.WriteString("ALTER TABLE [") |
| 776 | _, _ = buf.WriteString(schemaName) |
| 777 | _, _ = buf.WriteString("].[") |
| 778 | _, _ = buf.WriteString(tableName) |
| 779 | _, _ = buf.WriteString("] DROP CONSTRAINT [") |
| 780 | _, _ = buf.WriteString(colDiff.OldColumn.DefaultConstraintName) |
| 781 | _, _ = buf.WriteString("];\n") |
| 782 | } |
| 783 | // Note: If DefaultConstraintName is empty (e.g., when parsed from SQL), we cannot drop the constraint |
| 784 | // as we don't know its name. The user needs to drop it manually or sync from the database first. |
no test coverage detected