Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(migrate): speed up resource migration and add transaction control #243

Merged
merged 3 commits into from
Sep 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@
import java.util.List;
import java.util.Objects;

import javax.sql.DataSource;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import com.oceanbase.odc.common.util.HashUtils;
import com.oceanbase.odc.common.util.MapperUtils;
Expand Down Expand Up @@ -119,17 +123,28 @@ public String checksum() {

@Override
public boolean doMigrate() {
for (ResourceMigrateMetaInfo migrateMeta : migrateMetas) {
ResourceManager manager = migrateMeta.getManager();
ResourceConfig config = migrateMeta.getConfig();
ResourceSpecMigrator migrator = new ResourceSpecMigrator(
new DataRecordRepository(config.getDataSource()),
new DefaultResourceMapperFactory(config, manager), config.getHandle());
ResourceSpec resourceSpec = findResourceSpec(manager, path);
resourceSpec.getTemplates().stream().flatMap(t -> t.getSpecs().stream())
.forEach(t -> fullFillFieldReference(manager, migrator, t.getValueFrom()));
migrator.migrate(resourceSpec);
}
DataSource dataSource = migrateMetas.stream().filter(Objects::nonNull).findFirst()
.orElseThrow(() -> new NullPointerException("DS not found")).getConfig().getDataSource();
TransactionTemplate txTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
txTemplate.execute(status -> {
try {
for (ResourceMigrateMetaInfo migrateMeta : migrateMetas) {
ResourceManager manager = migrateMeta.getManager();
ResourceConfig config = migrateMeta.getConfig();
ResourceSpecMigrator migrator = new ResourceSpecMigrator(
new DataRecordRepository(config.getDataSource()),
new DefaultResourceMapperFactory(config, manager), config.getHandle());
ResourceSpec resourceSpec = findResourceSpec(manager, path);
resourceSpec.getTemplates().stream().flatMap(t -> t.getSpecs().stream())
.forEach(t -> fullFillFieldReference(manager, migrator, t.getValueFrom()));
migrator.migrate(resourceSpec);
}
return true;
} catch (Exception e) {
status.setRollbackOnly();
throw e;
}
});
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,15 @@ public ResourceSpec migrate(@NonNull ResourceSpec resourceSpec) {
EntityMapper<ResourceSpec, List<DataRecord>> mapper = factory.generate(entity);
List<DataRecord> recordList = mapper.entityToModel(entity);
for (DataRecord record : recordList) {
List<DataRecord> savedRecords = repository.find(record);
if (CollectionUtils.isNotEmpty(savedRecords)) {
savedRecords.forEach(DataRecord::refresh);
}
if (CollectionUtils.isEmpty(savedRecords) || record.isAllowDuplicated()) {
DataRecord saved = repository.save(record);
if (log.isDebugEnabled()) {
log.debug("Resource is saved successfully, resource={}", saved);
if (record.isAllowDuplicated()) {
save(record);
} else {
List<DataRecord> savedRecords = repository.find(record);
if (CollectionUtils.isEmpty(savedRecords)) {
save(record);
} else {
savedRecords.forEach(DataRecord::refresh);
}
saved.refresh();
}
}
return entity;
Expand All @@ -95,4 +94,12 @@ public ResourceSpec refresh(@NonNull ResourceSpec resourceSpec) {
return entity;
}

private void save(DataRecord record) {
DataRecord saved = repository.save(record);
if (log.isDebugEnabled()) {
log.debug("Resource is saved successfully, resource={}", saved);
}
saved.refresh();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ public static DataRecord copyFrom(@NonNull ResultSet resultSet, @NonNull DataRec
return new DataRecord(record.getTableName(), record.isAllowDuplicated(), record.uniqueKeys, specs);
}

public static DataRecord copyFrom(@NonNull DataRecord record, @NonNull List<DataSpec> specs) {
return new DataRecord(record.getTableName(), record.isAllowDuplicated(), record.uniqueKeys, specs);
}

public Set<String> getKeys() {
return name2DataSpecs.keySet();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public DataSpec(@NonNull TableSpec entity, Object value) {
this.entity = entity;
}

static DataSpec copyFrom(@NonNull DataSpec spec, Object value) {
public static DataSpec copyFrom(@NonNull DataSpec spec, Object value) {
return new DataSpec(spec.entity, value);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@
package com.oceanbase.odc.core.migrate.resource.repository;

import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
Expand All @@ -27,6 +30,7 @@
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import com.oceanbase.odc.core.migrate.resource.model.DataRecord;
import com.oceanbase.odc.core.migrate.resource.model.DataSpec;
Expand Down Expand Up @@ -55,21 +59,16 @@ public DataRecord save(@NonNull DataRecord record) {
List<DataSpec> savedSpecs = record.getData().stream().filter(dataSpec -> !dataSpec.isIgnore())
.collect(Collectors.toList());
String insertSql = generateInsertSql(record.getTableName(), savedSpecs);
int affectRows = update(insertSql, savedSpecs);
if (log.isDebugEnabled()) {
log.debug("Record has been saved, affectRows={}", affectRows);
}
List<DataRecord> savedOne = find(record);
if (savedOne.isEmpty()) {
throw new IllegalStateException("Saved nothing, record " + record);
}
if (savedOne.size() == 1) {
return savedOne.get(0);
}
if (!record.isAllowDuplicated()) {
throw new IllegalStateException("Duplicated records are found, record " + record);
}
return savedOne.get(savedOne.size() - 1);
final Long id = insert(insertSql, savedSpecs);
List<DataSpec> specs = new LinkedList<>();
record.getData().forEach(src -> {
Object value = src.getValue();
if ("id".equals(src.getName())) {
value = id;
}
specs.add(DataSpec.copyFrom(src, value));
});
return DataRecord.copyFrom(record, specs);
}

public List<DataRecord> find(@NonNull DataRecord record) {
Expand All @@ -85,22 +84,44 @@ public boolean exists(@NonNull DataRecord record) {
return result.get(0) >= 1;
}

private int update(@NonNull String sql, List<DataSpec> dataSpecs) {
private Long insert(@NonNull String sql, List<DataSpec> dataSpecs) {
if (log.isDebugEnabled()) {
log.debug("Sql update, sql={}, params={}", sql,
dataSpecs == null ? null : dataSpecs.stream().map(DataSpec::getValue).collect(Collectors.toList()));
}
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate.update(connection -> {
PreparedStatement statement = connection.prepareStatement(sql);
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
int affectRows = jdbcTemplate.update(connection -> {
PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
if (dataSpecs == null) {
return statement;
}
for (int i = 0; i < dataSpecs.size(); i++) {
statement.setObject(i + 1, dataSpecs.get(i).getValue());
}
return statement;
});
}, keyHolder);
if (log.isDebugEnabled()) {
log.debug("Record has been saved, affectRows={}", affectRows);
}
if (affectRows != 1) {
throw new IllegalStateException("Saved nothing, record " + affectRows);
}
Map<String, Object> keyMap = keyHolder.getKeys();
if (keyMap == null) {
return null;
}
if (keyMap.size() == 1) {
return keyHolder.getKeyAs(Long.class);
}
if (keyMap.get("id") != null) {
return Long.valueOf(keyMap.get("id").toString());
} else if (keyMap.get("ID") != null) {
return Long.valueOf(keyMap.get("ID").toString());
} else if (keyMap.get("GENERATED_KEY") != null) {
return Long.valueOf(keyMap.get("GENERATED_KEY").toString());
}
return null;
}

private <T> List<T> query(@NonNull String sql, List<DataSpec> params, @NonNull RowMapper<T> mapper) {
Expand Down