public boolean before(DbLoadContext context, EventData currentData) {
// 初步构建sql
DbDialect dbDialect = dbDialectFactory.getDbDialect(context.getIdentity().getPipelineId(),
(DbMediaSource) context.getDataMediaSource());
SqlTemplate sqlTemplate = dbDialect.getSqlTemplate();
EventType type = currentData.getEventType();
String sql = null;
// 注意insert/update语句对应的字段数序都是将主键排在后面
if (type.isInsert()) {
if (CollectionUtils.isEmpty(currentData.getColumns())) { // 如果表为全主键,直接进行insert sql
sql = sqlTemplate.getInsertSql(currentData.getSchemaName(), currentData.getTableName(),
buildColumnNames(currentData.getKeys()),
buildColumnNames(currentData.getColumns()));
} else {
sql = sqlTemplate.getMergeSql(currentData.getSchemaName(), currentData.getTableName(),
buildColumnNames(currentData.getKeys()),
buildColumnNames(currentData.getColumns()), new String[] {});
}
} else if (type.isUpdate()) {
// String[] keyColumns = buildColumnNames(currentData.getKeys());
// String[] otherColumns = buildColumnNames(currentData.getUpdatedColumns());
// boolean existOldKeys = false;
// for (String key : keyColumns) {
// // 找一下otherColumns是否有主键,存在就代表有主键变更
// if (ArrayUtils.contains(otherColumns, key)) {
// existOldKeys = true;
// break;
// }
// }
boolean existOldKeys = !CollectionUtils.isEmpty(currentData.getOldKeys());
boolean rowMode = context.getPipeline().getParameters().getSyncMode().isRow();
String[] keyColumns = null;
String[] otherColumns = null;
if (existOldKeys) {
// 需要考虑主键变更的场景
// 构造sql如下:update table xxx set pk = newPK where pk = oldPk
keyColumns = buildColumnNames(currentData.getOldKeys());
otherColumns = buildColumnNames(currentData.getUpdatedColumns(), currentData.getKeys());
} else {
keyColumns = buildColumnNames(currentData.getKeys());
otherColumns = buildColumnNames(currentData.getUpdatedColumns());
}
if (rowMode && !existOldKeys) {// 如果是行记录,并且不存在主键变更,考虑merge sql
sql = sqlTemplate.getMergeSql(currentData.getSchemaName(), currentData.getTableName(), keyColumns,
otherColumns, new String[] {});
} else {// 否则进行update sql
sql = sqlTemplate.getUpdateSql(currentData.getSchemaName(), currentData.getTableName(), keyColumns,
otherColumns);
}
} else if (type.isDelete()) {
sql = sqlTemplate.getDeleteSql(currentData.getSchemaName(), currentData.getTableName(),
buildColumnNames(currentData.getKeys()));
}
currentData.setSql(sql);
return false;
}