diff --git a/src/main/java/org/avniproject/etl/repository/sync/CleanEnrolmentExitTableAction.java b/src/main/java/org/avniproject/etl/repository/sync/CleanEnrolmentExitTableAction.java index 69c89d3..b74ca31 100644 --- a/src/main/java/org/avniproject/etl/repository/sync/CleanEnrolmentExitTableAction.java +++ b/src/main/java/org/avniproject/etl/repository/sync/CleanEnrolmentExitTableAction.java @@ -11,6 +11,7 @@ import org.stringtemplate.v4.ST; import java.util.Date; +import java.util.Optional; import static org.avniproject.etl.repository.JdbcContextWrapper.runInOrgContext; @@ -28,13 +29,13 @@ public void perform(TableMetadata tableMetadata, Date lastSyncTime, Date dataSyn if (this.doesntSupport(tableMetadata)) { return; } - cleanInvalidExits(tableMetadata); + cleanInvalidExits(tableMetadata, currentSchemaMetadata); } - private void cleanInvalidExits(TableMetadata tableMetadata) { + private void cleanInvalidExits(TableMetadata tableMetadata, SchemaMetadata currentSchemaMetadata) { String schema = OrgIdentityContextHolder.getDbSchema(); String exitTableName = tableMetadata.getName(); - String primaryTableName = exitTableName.substring(0, exitTableName.length() - 5); + String primaryTableName = getPrimaryTableName(tableMetadata, currentSchemaMetadata); String sql = new ST(deleteInvalidExitsSqlTemplate) .add("schemaName", wrapInQuotes(schema)) .add("exitTableName", wrapInQuotes(exitTableName)) @@ -46,6 +47,18 @@ private void cleanInvalidExits(TableMetadata tableMetadata) { }, jdbcTemplate); } + + private String getPrimaryTableName(TableMetadata tableMetadata, SchemaMetadata currentSchemaMetadata) { + Optional primaryTableMetadata = currentSchemaMetadata.getAllProgramEnrolmentTables() + .stream().filter(tm -> tm.getProgramUuid() == tableMetadata.getProgramUuid() + && tm.getSubjectTypeUuid() == tableMetadata.getSubjectTypeUuid()).findAny(); + + if (primaryTableMetadata.isPresent()) { + return primaryTableMetadata.get().getName(); + } + throw new RuntimeException(String.format("Corresponding Primary table not found for cancel table: %s", tableMetadata.getName())); + } + private String wrapInQuotes(String parameter) { return parameter == null ? "null" : "\"" + parameter + "\""; }