package db.migration; import static org.assertj.core.api.Assertions.assertThat; import java.sql.Connection; import javax.sql.DataSource; import org.flywaydb.core.api.configuration.Configuration; import org.flywaydb.core.api.migration.Context; import org.junit.jupiter.api.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; class V125ParkingLotRegistrationSnapshotTests { @Test void backfillsLegacyMerchantJsonWithoutUsingAnotherMerchantsGlobalLot() throws Exception { DataSource dataSource = new DriverManagerDataSource( "jdbc:h2:mem:parking-lot-snapshot-" + System.nanoTime() + ";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", "sa", ""); JdbcTemplate jdbc = new JdbcTemplate(dataSource); createSchema(jdbc); insertFixture(jdbc); try (Connection connection = dataSource.getConnection()) { V125__parking_lot_registration_snapshot migration = new V125__parking_lot_registration_snapshot(); Context context = new Context() { @Override public Configuration getConfiguration() { return null; } @Override public Connection getConnection() { return connection; } }; migration.migrate(context); migration.migrate(context); } assertThat(snapshot(jdbc, 100L)).containsExactly("P1停车场", "P1地址"); assertThat(snapshot(jdbc, 101L)).containsExactly("P2停车场", "P2地址"); assertThat(snapshot(jdbc, 102L)).containsExactly("数据库停车场", "数据库地址"); } private void createSchema(JdbcTemplate jdbc) { jdbc.execute(""" create table merchant ( id bigint primary key, usage_instructions text, deleted tinyint not null default 0 ) """); jdbc.execute(""" create table transport_parking_lot ( id bigint primary key, merchant_id bigint not null, parking_lot_name varchar(128), address varchar(255), deleted tinyint not null default 0 ) """); jdbc.execute(""" create table transport_parking_plate_registration ( id bigint primary key, merchant_id bigint not null, parking_lot_id bigint, card_id bigint ) """); } private void insertFixture(JdbcTemplate jdbc) { jdbc.update(""" insert into merchant(id, usage_instructions, deleted) values (99, '[{"id":1,"name":"P1停车场","address":"P1地址"},{"name":"P2停车场","address":"P2地址"}]', 0) """); jdbc.update("insert into merchant(id, usage_instructions, deleted) values (33, null, 0)"); jdbc.update("insert into transport_parking_lot values (1, 33, '其他商家停车场', '错误地址', 0)"); jdbc.update("insert into transport_parking_lot values (5, 99, '数据库停车场', '数据库地址', 0)"); jdbc.update("insert into transport_parking_plate_registration values (100, 99, 1, null)"); jdbc.update("insert into transport_parking_plate_registration values (101, 99, 2, null)"); jdbc.update("insert into transport_parking_plate_registration values (102, 99, 5, 88)"); } private String[] snapshot(JdbcTemplate jdbc, Long id) { return jdbc.queryForObject(""" select parking_lot_name_snapshot, parking_lot_address_snapshot from transport_parking_plate_registration where id = ? """, (row, rowNumber) -> new String[]{row.getString(1), row.getString(2)}, id); } }