|
| 1 | +/* |
| 2 | + Copyright 2025 GitHub Inc. |
| 3 | + See https://github.com/github/gh-ost/blob/master/LICENSE |
| 4 | +*/ |
| 5 | + |
| 6 | +package logic |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "fmt" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "github.com/github/gh-ost/go/binlog" |
| 14 | + "github.com/github/gh-ost/go/sql" |
| 15 | + "github.com/stretchr/testify/suite" |
| 16 | +) |
| 17 | + |
| 18 | +type DeleteInsertTestSuite struct { |
| 19 | + ApplierTestSuite |
| 20 | +} |
| 21 | + |
| 22 | +// TestUpdateModifyingUniqueKeyWithDuplicateOnOtherIndex tests the scenario where: |
| 23 | +// 1. An UPDATE modifies the unique key (converted to DELETE+INSERT) |
| 24 | +// 2. The INSERT would create a duplicate on a NON-migration unique index |
| 25 | +// 3. With INSERT IGNORE, the DELETE succeeds but INSERT skips = DATA LOSS |
| 26 | +func (suite *DeleteInsertTestSuite) TestUpdateModifyingUniqueKeyWithDuplicateOnOtherIndex() { |
| 27 | + ctx := context.Background() |
| 28 | + |
| 29 | + var err error |
| 30 | + |
| 31 | + // Create table with id (PRIMARY) and email (NO unique constraint yet) |
| 32 | + _, err = suite.db.ExecContext(ctx, fmt.Sprintf("CREATE TABLE %s (id INT PRIMARY KEY, email VARCHAR(100));", getTestTableName())) |
| 33 | + suite.Require().NoError(err) |
| 34 | + |
| 35 | + // Create ghost table with id (PRIMARY) AND email unique index (being added) |
| 36 | + _, err = suite.db.ExecContext(ctx, fmt.Sprintf("CREATE TABLE %s (id INT PRIMARY KEY, email VARCHAR(100), UNIQUE KEY email_unique (email));", getTestGhostTableName())) |
| 37 | + suite.Require().NoError(err) |
| 38 | + |
| 39 | + connectionConfig, err := getTestConnectionConfig(ctx, suite.mysqlContainer) |
| 40 | + suite.Require().NoError(err) |
| 41 | + |
| 42 | + migrationContext := newTestMigrationContext() |
| 43 | + migrationContext.ApplierConnectionConfig = connectionConfig |
| 44 | + migrationContext.SetConnectionConfig("innodb") |
| 45 | + |
| 46 | + migrationContext.PanicOnWarnings = true |
| 47 | + |
| 48 | + migrationContext.OriginalTableColumns = sql.NewColumnList([]string{"id", "email"}) |
| 49 | + migrationContext.SharedColumns = sql.NewColumnList([]string{"id", "email"}) |
| 50 | + migrationContext.MappedSharedColumns = sql.NewColumnList([]string{"id", "email"}) |
| 51 | + migrationContext.UniqueKey = &sql.UniqueKey{ |
| 52 | + Name: "PRIMARY", |
| 53 | + NameInGhostTable: "PRIMARY", |
| 54 | + Columns: *sql.NewColumnList([]string{"id"}), |
| 55 | + } |
| 56 | + |
| 57 | + applier := NewApplier(migrationContext) |
| 58 | + suite.Require().NoError(applier.prepareQueries()) |
| 59 | + defer applier.Teardown() |
| 60 | + |
| 61 | + err = applier.InitDBConnections() |
| 62 | + suite.Require().NoError(err) |
| 63 | + |
| 64 | + // Setup: Insert initial rows into ghost table |
| 65 | + // Row 1: id=1, email='bob@example.com' |
| 66 | + // Row 2: id=2, email='charlie@example.com' |
| 67 | + _, err = suite.db.ExecContext(ctx, fmt.Sprintf("INSERT INTO %s (id, email) VALUES (1, 'bob@example.com'), (2, 'charlie@example.com');", getTestGhostTableName())) |
| 68 | + suite.Require().NoError(err) |
| 69 | + |
| 70 | + // Simulate binlog event: UPDATE that changes BOTH PRIMARY KEY and email |
| 71 | + // From: id=2, email='charlie@example.com' |
| 72 | + // To: id=3, email='bob@example.com' (duplicate email with id=1) |
| 73 | + // This will be converted to DELETE (id=2) + INSERT (id=3, 'bob@example.com') |
| 74 | + // With INSERT IGNORE, the INSERT will skip because email='bob@example.com' already exists in id=1 |
| 75 | + // Result: id=2 deleted, id=3 never inserted = DATA LOSS |
| 76 | + dmlEvents := []*binlog.BinlogDMLEvent{ |
| 77 | + { |
| 78 | + DatabaseName: testMysqlDatabase, |
| 79 | + TableName: testMysqlTableName, |
| 80 | + DML: binlog.UpdateDML, |
| 81 | + NewColumnValues: sql.ToColumnValues([]interface{}{3, "bob@example.com"}), // new: id=3, email='bob@example.com' |
| 82 | + WhereColumnValues: sql.ToColumnValues([]interface{}{2, "charlie@example.com"}), // old: id=2, email='charlie@example.com' |
| 83 | + }, |
| 84 | + } |
| 85 | + |
| 86 | + // First verify this would be converted to DELETE+INSERT |
| 87 | + buildResults := applier.buildDMLEventQuery(dmlEvents[0]) |
| 88 | + suite.Require().Len(buildResults, 2, "UPDATE modifying unique key should be converted to DELETE+INSERT") |
| 89 | + |
| 90 | + // Apply the event - this should FAIL because INSERT will have duplicate email warning |
| 91 | + err = applier.ApplyDMLEventQueries(dmlEvents) |
| 92 | + suite.Require().Error(err, "Should fail when DELETE+INSERT causes duplicate on non-migration unique key") |
| 93 | + suite.Require().Contains(err.Error(), "Duplicate entry", "Error should mention duplicate entry") |
| 94 | + |
| 95 | + // Verify that BOTH rows still exist (transaction rolled back) |
| 96 | + rows, err := suite.db.Query("SELECT id, email FROM " + getTestGhostTableName() + " ORDER BY id") |
| 97 | + suite.Require().NoError(err) |
| 98 | + defer rows.Close() |
| 99 | + |
| 100 | + var count int |
| 101 | + var ids []int |
| 102 | + var emails []string |
| 103 | + for rows.Next() { |
| 104 | + var id int |
| 105 | + var email string |
| 106 | + err = rows.Scan(&id, &email) |
| 107 | + suite.Require().NoError(err) |
| 108 | + ids = append(ids, id) |
| 109 | + emails = append(emails, email) |
| 110 | + count++ |
| 111 | + } |
| 112 | + suite.Require().NoError(rows.Err()) |
| 113 | + |
| 114 | + // Transaction should have rolled back, so original 2 rows should still be there |
| 115 | + suite.Require().Equal(2, count, "Should still have 2 rows after failed transaction") |
| 116 | + suite.Require().Equal([]int{1, 2}, ids, "Should have original ids") |
| 117 | + suite.Require().Equal([]string{"bob@example.com", "charlie@example.com"}, emails) |
| 118 | +} |
| 119 | + |
| 120 | +// TestNormalUpdateWithPanicOnWarnings tests that normal UPDATEs (not modifying unique key) work correctly |
| 121 | +func (suite *DeleteInsertTestSuite) TestNormalUpdateWithPanicOnWarnings() { |
| 122 | + ctx := context.Background() |
| 123 | + |
| 124 | + var err error |
| 125 | + |
| 126 | + // Create table with id (PRIMARY) and email |
| 127 | + _, err = suite.db.ExecContext(ctx, fmt.Sprintf("CREATE TABLE %s (id INT PRIMARY KEY, email VARCHAR(100));", getTestTableName())) |
| 128 | + suite.Require().NoError(err) |
| 129 | + |
| 130 | + // Create ghost table with same schema plus unique index on email |
| 131 | + _, err = suite.db.ExecContext(ctx, fmt.Sprintf("CREATE TABLE %s (id INT PRIMARY KEY, email VARCHAR(100), UNIQUE KEY email_unique (email));", getTestGhostTableName())) |
| 132 | + suite.Require().NoError(err) |
| 133 | + |
| 134 | + connectionConfig, err := getTestConnectionConfig(ctx, suite.mysqlContainer) |
| 135 | + suite.Require().NoError(err) |
| 136 | + |
| 137 | + migrationContext := newTestMigrationContext() |
| 138 | + migrationContext.ApplierConnectionConfig = connectionConfig |
| 139 | + migrationContext.SetConnectionConfig("innodb") |
| 140 | + |
| 141 | + migrationContext.PanicOnWarnings = true |
| 142 | + |
| 143 | + migrationContext.OriginalTableColumns = sql.NewColumnList([]string{"id", "email"}) |
| 144 | + migrationContext.SharedColumns = sql.NewColumnList([]string{"id", "email"}) |
| 145 | + migrationContext.MappedSharedColumns = sql.NewColumnList([]string{"id", "email"}) |
| 146 | + migrationContext.UniqueKey = &sql.UniqueKey{ |
| 147 | + Name: "PRIMARY", |
| 148 | + NameInGhostTable: "PRIMARY", |
| 149 | + Columns: *sql.NewColumnList([]string{"id"}), |
| 150 | + } |
| 151 | + |
| 152 | + applier := NewApplier(migrationContext) |
| 153 | + suite.Require().NoError(applier.prepareQueries()) |
| 154 | + defer applier.Teardown() |
| 155 | + |
| 156 | + err = applier.InitDBConnections() |
| 157 | + suite.Require().NoError(err) |
| 158 | + |
| 159 | + // Setup: Insert initial rows into ghost table |
| 160 | + _, err = suite.db.ExecContext(ctx, fmt.Sprintf("INSERT INTO %s (id, email) VALUES (1, 'alice@example.com'), (2, 'bob@example.com');", getTestGhostTableName())) |
| 161 | + suite.Require().NoError(err) |
| 162 | + |
| 163 | + // Simulate binlog event: Normal UPDATE that only changes email (not PRIMARY KEY) |
| 164 | + // This should use UPDATE query, not DELETE+INSERT |
| 165 | + dmlEvents := []*binlog.BinlogDMLEvent{ |
| 166 | + { |
| 167 | + DatabaseName: testMysqlDatabase, |
| 168 | + TableName: testMysqlTableName, |
| 169 | + DML: binlog.UpdateDML, |
| 170 | + NewColumnValues: sql.ToColumnValues([]interface{}{2, "robert@example.com"}), // update email only |
| 171 | + WhereColumnValues: sql.ToColumnValues([]interface{}{2, "bob@example.com"}), |
| 172 | + }, |
| 173 | + } |
| 174 | + |
| 175 | + // Verify this generates a single UPDATE query (not DELETE+INSERT) |
| 176 | + buildResults := applier.buildDMLEventQuery(dmlEvents[0]) |
| 177 | + suite.Require().Len(buildResults, 1, "Normal UPDATE should generate single UPDATE query") |
| 178 | + |
| 179 | + // Apply the event - should succeed |
| 180 | + err = applier.ApplyDMLEventQueries(dmlEvents) |
| 181 | + suite.Require().NoError(err) |
| 182 | + |
| 183 | + // Verify the update was applied correctly |
| 184 | + rows, err := suite.db.Query("SELECT id, email FROM " + getTestGhostTableName() + " WHERE id = 2") |
| 185 | + suite.Require().NoError(err) |
| 186 | + defer rows.Close() |
| 187 | + |
| 188 | + var id int |
| 189 | + var email string |
| 190 | + suite.Require().True(rows.Next(), "Should find updated row") |
| 191 | + err = rows.Scan(&id, &email) |
| 192 | + suite.Require().NoError(err) |
| 193 | + suite.Require().Equal(2, id) |
| 194 | + suite.Require().Equal("robert@example.com", email) |
| 195 | + suite.Require().False(rows.Next(), "Should only have one row") |
| 196 | + suite.Require().NoError(rows.Err()) |
| 197 | +} |
| 198 | + |
| 199 | +func TestDeleteInsert(t *testing.T) { |
| 200 | + suite.Run(t, new(DeleteInsertTestSuite)) |
| 201 | +} |
0 commit comments