Tony CHEMIT pushed to branch develop-7.x at ultreiaio / ird-observe Commits: 556f5d2a by Tony CHEMIT at 2018-09-19T14:46:06Z remove EntityMap class - - - - - 1b0f5e65 by Tony CHEMIT at 2018-09-20T15:33:43Z Use topia-extension usage support to compute usages (see #1066) - - - - - f193d8a5 by Tony CHEMIT at 2018-09-20T15:35:33Z use new topia metadata model feature to generate clean sql statements (See #1065) - - - - - 15 changed files: - − persistence/src/main/java/fr/ird/observe/entities/EntityMap.java - persistence/src/main/java/fr/ird/observe/persistence/ObserveTopiaApplicationContext.java - pom.xml - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/legacy/UnidirectionalReferentialSynchronizeLocalServiceLocal.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/ng/ReferentialSynchronizeSqlsRequestBuilder.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/DeleteSqlStatementGenerator.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/DesactivateSqlStatementGenerator.java → services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/DisableSqlStatementGenerator.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/InsertSqlStatementGenerator.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/InsertSqlWithCascadeStatementGenerator.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/ReplaceSqlStatementGenerator.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/UpdateSqlStatementGenerator.java - services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/UpdateSqlWithCascadeStatementGenerator.java - services-local/src/main/java/fr/ird/observe/services/local/service/referential/ReferentialServiceLocal.java - services/pom.xml - services/src/main/java/fr/ird/observe/services/service/actions/synchro/referential/ng/ReferentialSynchronizeSqlsRequest.java Changes: ===================================== persistence/src/main/java/fr/ird/observe/entities/EntityMap.java deleted ===================================== @@ -1,45 +0,0 @@ -/* - * #%L - * ObServe :: Persistence - * %% - * Copyright (C) 2008 - 2018 IRD, Code Lutin, Ultreia.io - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.entities; - -import org.nuiton.topia.persistence.TopiaEntity; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * A Dictionary of entities - * - * @author Tony Chemit - dev@tchemit.fr - * @since 1.4 - */ -public class EntityMap extends HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> { - private static final long serialVersionUID = 1L; - - public EntityMap() { - } - - public EntityMap(Map<? extends Class<? extends TopiaEntity>, ? extends List<? extends TopiaEntity>> m) { - super(m); - } -} ===================================== persistence/src/main/java/fr/ird/observe/persistence/ObserveTopiaApplicationContext.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.persistence; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -24,19 +24,22 @@ package fr.ird.observe.persistence; import com.google.common.collect.ImmutableSet; import fr.ird.observe.entities.referentiel.ObserveReferentialEntity; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; +import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaException; import org.nuiton.topia.persistence.internal.support.TopiaMetadataModelSupportImpl; +import org.nuiton.topia.persistence.internal.support.TopiaUsageSupportImpl; import org.nuiton.topia.persistence.jdbc.JdbcHelper; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; import org.nuiton.topia.persistence.script.SqlScriptReader; import org.nuiton.topia.persistence.script.TopiaSqlScript; import org.nuiton.topia.persistence.support.TopiaMetadataModelSupport; +import org.nuiton.topia.persistence.support.TopiaUsageSupport; import org.nuiton.topia.service.migration.TopiaMigrationService; import org.nuiton.topia.service.script.TopiaSqlScriptGeneratorService; import org.nuiton.topia.service.script.table.TopiaSqlTable; @@ -45,13 +48,16 @@ import org.nuiton.topia.service.script.table.TopiaSqlTablesFactory; import java.util.EnumSet; import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; -public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicationContext implements TopiaMetadataModelSupport { +public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicationContext { static final String MIGRATION_SERVICE_NAME = "migration"; static final String SQL_SCRIPT_GENERATOR_BATCH_SERVICE_NAME = "sqlScriptGenerator"; @@ -65,6 +71,7 @@ public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicat protected final String authenticationToken; private final TopiaMetadataModelSupport topiaMetadataModelSupport; private final TopiaSqlTablesFactory topiaSqlTablesFactory; + private final TopiaUsageSupport topiaUsageSupport; /** * Mise à {@code true} quand au moins une connection a été effectuée. */ @@ -78,6 +85,7 @@ public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicat this.authenticationToken = UUID.randomUUID().toString(); this.topiaMetadataModelSupport = new TopiaMetadataModelSupportImpl("fr.ird.observe.persistence", "Observe"); this.topiaSqlTablesFactory = new TopiaSqlTablesFactory(getMetadataModel(), this); + this.topiaUsageSupport = new TopiaUsageSupportImpl(topiaMetadataModelSupport, this); } @Override @@ -108,6 +116,22 @@ public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicat return getServices(TopiaSqlScriptGeneratorService.class).get(SQL_SCRIPT_GENERATOR_BATCH_SERVICE_NAME); } + public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findReverseCompositions(ObserveTopiaPersistenceContext topiaPersistenceContext, TopiaEntity entity, Predicate<Class<? extends TopiaEntity>> entityTypeFilter) { + return topiaUsageSupport.findReverseCompositions(topiaPersistenceContext, entity, entityTypeFilter); + } + + public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findReverseAssociations(ObserveTopiaPersistenceContext topiaPersistenceContext, TopiaEntity entity, Predicate<Class<? extends TopiaEntity>> entityTypeFilter) { + return topiaUsageSupport.findReverseAssociations(topiaPersistenceContext, entity, entityTypeFilter); + } + + public Map<Class<? extends TopiaEntity>, Long> countReverseCompositions(ObserveTopiaPersistenceContext topiaPersistenceContext, TopiaEntity entity, Predicate<Class<? extends TopiaEntity>> entityTypeFilter) { + return topiaUsageSupport.countReverseCompositions(topiaPersistenceContext, entity, entityTypeFilter); + } + + public Map<Class<? extends TopiaEntity>, Long> countReverseAssociations(ObserveTopiaPersistenceContext topiaPersistenceContext, TopiaEntity entity, Predicate<Class<? extends TopiaEntity>> entityTypeFilter) { + return topiaUsageSupport.countReverseAssociations(topiaPersistenceContext, entity, entityTypeFilter); + } + @Override public void createSchema() { try { @@ -206,7 +230,6 @@ public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicat return authenticationToken; } - @Override public TopiaMetadataModel getMetadataModel() { return topiaMetadataModelSupport.getMetadataModel(); } @@ -269,7 +292,7 @@ public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicat basketTable.getFromClause(), basketTable.getWhereClauseAlias(), ImmutableSet.of(" INNER JOIN observe_longline.set set ON set.topiaId = activity.set", - " INNER JOIN observe_longline.basket basket ON basket.set = set.topiaId" + " INNER JOIN observe_longline.basket basket ON basket.set = set.topiaId" ), null); @@ -285,8 +308,8 @@ public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicat branchlineTable.getFromClause(), branchlineTable.getWhereClauseAlias(), ImmutableSet.of(" INNER JOIN observe_longline.set set ON set.topiaId = activity.set", - " INNER JOIN observe_longline.basket basket ON basket.set = set.topiaId", - " INNER JOIN observe_longline.branchline branchline ON branchline.basket = basket.topiaId" + " INNER JOIN observe_longline.basket basket ON basket.set = set.topiaId", + " INNER JOIN observe_longline.branchline branchline ON branchline.basket = basket.topiaId" ), null); @@ -312,6 +335,7 @@ public class ObserveTopiaApplicationContext extends AbstractObserveTopiaApplicat return referentialTables = topiaSqlTablesFactory.newReplicateEntityTables(new TripReplicateTablesPredicate(), entityEnum); } + private static class TripReplicateTablesPredicate implements TopiaSqlTablesFactory.TopiaSqlTablesPredicate { protected final Set<String> sections = ImmutableSet.of( ===================================== pom.xml ===================================== @@ -162,7 +162,7 @@ <lib.version.h2>1.4.196</lib.version.h2> <!--<lib.version.nuiton.topia>3.6-SNAPSHOT</lib.version.nuiton.topia>--> <!--<lib.version.java4all.eugene>3.0-alpha-21</lib.version.java4all.eugene>--> - <!--<lib.version.java4all.topia>1.1.8-SNAPSHOT</lib.version.java4all.topia>--> + <lib.version.java4all.topia>1.1.8-SNAPSHOT</lib.version.java4all.topia> <!-- license header configuration --> <license.licenseName>gpl_v3</license.licenseName> <license.organizationName>IRD, Code Lutin, Ultreia.io</license.organizationName> ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/legacy/UnidirectionalReferentialSynchronizeLocalServiceLocal.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.legacy * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -44,8 +44,6 @@ import fr.ird.observe.services.service.actions.synchro.referential.legacy.Unidir import fr.ird.observe.spi.DbModelHelper; import fr.ird.observe.spi.context.ReferentialDtoEntityContext; import fr.ird.observe.spi.context.ReferentialReferenceEntityContext; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.nuiton.topia.persistence.TopiaDao; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; @@ -65,9 +63,6 @@ import java.util.Set; */ public class UnidirectionalReferentialSynchronizeLocalServiceLocal extends ObserveServiceLocal implements UnidirectionalReferentialSynchronizeLocalService { - /** Logger. */ - private static final Logger log = LogManager.getLogger(UnidirectionalReferentialSynchronizeLocalServiceLocal.class); - private LastUpdateDateService lastUpdateDateService; @Override @@ -79,9 +74,6 @@ public class UnidirectionalReferentialSynchronizeLocalServiceLocal extends Obser @Override public <D extends ReferentialDto> ImmutableSet<String> filterIdsUsedInLocalSource(Class<D> dtoType, ImmutableSet<String> ids) { - if (log.isTraceEnabled()) { - log.trace("filterIdsUsedInLocalSource(" + dtoType + ", " + ids + ")"); - } Class<? extends ObserveReferentialEntity> entityType = DbModelHelper.fromReferentialDto(dtoType).toEntityType(); Set<String> result = new LinkedHashSet<>(); for (String id : ids) { @@ -107,10 +99,6 @@ public class UnidirectionalReferentialSynchronizeLocalServiceLocal extends Obser @Override public <D extends ReferentialDto> ImmutableSet<String> generateSqlRequests(UnidirectionalReferentialSynchronizeRequest<D> request) { - if (log.isTraceEnabled()) { - log.trace("generateSqlRequests(" + request + ")"); - } - Set<String> result = new LinkedHashSet<>(); Class<D> dtoType = request.getReferentialName(); @@ -122,7 +110,7 @@ public class UnidirectionalReferentialSynchronizeLocalServiceLocal extends Obser TopiaMetadataEntity metadataEntity = metadataModel.getEntity(referentielName); if (request.withReferentialToAdd()) { - InsertSqlStatementGenerator<D> sqlStatementGenerator = new InsertSqlStatementGenerator<>(metadataEntity, dtoType); + InsertSqlStatementGenerator<D> sqlStatementGenerator = new InsertSqlStatementGenerator<>(metadataModel, metadataEntity, dtoType); ImmutableSet<D> referentialToAdd = request.getReferentialToAdd(); if (ObjectMaterialDto.class.equals(dtoType)) { @@ -139,55 +127,40 @@ public class UnidirectionalReferentialSynchronizeLocalServiceLocal extends Obser if (request.withReferentialToUpdate()) { - UpdateSqlStatementGenerator<D> sqlStatementGenerator = new UpdateSqlStatementGenerator<>(metadataEntity, dtoType); + UpdateSqlStatementGenerator<D> sqlStatementGenerator = new UpdateSqlStatementGenerator<>(metadataModel, metadataEntity, dtoType); for (D referentialDto : request.getReferentialToUpdate()) { ImmutableList<String> sql = sqlStatementGenerator.generateSql(referentialDto); result.addAll(sql); } - } - if (request.withReferentialToReplace()) { - ReplaceSqlStatementGenerator sqlStatementGenerator = new ReplaceSqlStatementGenerator(metadataModel, referentielName); + ReplaceSqlStatementGenerator sqlStatementGenerator = new ReplaceSqlStatementGenerator(metadataModel, metadataEntity); for (Map.Entry<String, String> entry : request.getReferentialToReplace().entrySet()) { ImmutableList<String> sql = sqlStatementGenerator.generateSqls(entry.getKey(), entry.getValue()); result.addAll(sql); } - } if (request.withReferentialToRemove()) { - DeleteSqlStatementGenerator sqlStatementGenerator = new DeleteSqlStatementGenerator(metadataEntity); + DeleteSqlStatementGenerator sqlStatementGenerator = new DeleteSqlStatementGenerator(metadataModel, metadataEntity); for (String id : request.getReferentialToRemove()) { List<String> sql = sqlStatementGenerator.generateSql(id); result.addAll(sql); } - } - - return ImmutableSet.copyOf(result); - } @Override public void applySqlRequests(ImmutableSet<String> sqlRequests) { - - if (log.isTraceEnabled()) { - log.trace("applySqlRequests(" + sqlRequests + ")"); - } - TopiaSqlWork applySqlWork = new ApplySqlRequestWork(sqlRequests); getTopiaPersistenceContext().getSqlSupport().doSqlWork(applySqlWork); - } @Override public void updateLastUpdateDates() { - lastUpdateDateService.updateReferentialLastUpdateDates(); - } private <E extends ObserveReferentialEntity> int countUsage0(Class<E> entityType, String id) { ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/ng/ReferentialSynchronizeSqlsRequestBuilder.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.ng; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -31,7 +31,7 @@ import fr.ird.observe.dto.referential.ReferentialLocale; import fr.ird.observe.entities.referentiel.ObserveReferentialEntity; import fr.ird.observe.persistence.ObserveEntityEnum; import fr.ird.observe.services.local.service.actions.synchro.referential.sql.DeleteSqlStatementGenerator; -import fr.ird.observe.services.local.service.actions.synchro.referential.sql.DesactivateSqlStatementGenerator; +import fr.ird.observe.services.local.service.actions.synchro.referential.sql.DisableSqlStatementGenerator; import fr.ird.observe.services.local.service.actions.synchro.referential.sql.InsertSqlStatementGenerator; import fr.ird.observe.services.local.service.actions.synchro.referential.sql.InsertSqlWithCascadeStatementGenerator; import fr.ird.observe.services.local.service.actions.synchro.referential.sql.ReplaceSqlStatementGenerator; @@ -153,7 +153,7 @@ public class ReferentialSynchronizeSqlsRequestBuilder { List<E> insertEntities = loadEntities(entityType, tasks); if (metadata.withEntities()) { - InsertSqlWithCascadeStatementGenerator<D> insertGenerator = new InsertSqlWithCascadeStatementGenerator<D>(metadata, dtoType, request.getIdsOnlyExistingOnThisSide()) { + InsertSqlWithCascadeStatementGenerator<D> insertGenerator = new InsertSqlWithCascadeStatementGenerator<D>(metadataModel, metadata, dtoType, request.getIdsOnlyExistingOnThisSide()) { @Override protected <DD extends ReferentialDto> ImmutableList<String> insertMissingReferential(Class<DD> referentialType, String id) { @@ -166,9 +166,7 @@ public class ReferentialSynchronizeSqlsRequestBuilder { D referential = binder.toDto(referentialLocale, entity); ImmutableList<String> sqls = insertGenerator.generateSql(referential); - if (log.isInfoEnabled()) { - log.info("Insert referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); - } + log.info("Insert referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); for (String sql : sqls) { resultBuilder.addInsertStatement(sql); } @@ -176,14 +174,12 @@ public class ReferentialSynchronizeSqlsRequestBuilder { } else { - InsertSqlStatementGenerator<D> insertGenerator = new InsertSqlStatementGenerator<>(metadata, dtoType); + InsertSqlStatementGenerator<D> insertGenerator = new InsertSqlStatementGenerator<>(metadataModel, metadata, dtoType); for (E entity : insertEntities) { D referential = binder.toDto(referentialLocale, entity); ImmutableList<String> sqls = insertGenerator.generateSql(referential); - if (log.isInfoEnabled()) { - log.info("Insert referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); - } + log.info("Insert referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); for (String sql : sqls) { resultBuilder.addInsertStatement(sql); } @@ -201,7 +197,7 @@ public class ReferentialSynchronizeSqlsRequestBuilder { if (metadata.withEntities()) { - UpdateSqlWithCascadeStatementGenerator<D> updateGenerator = new UpdateSqlWithCascadeStatementGenerator<D>(metadata, dtoType, request.getIdsOnlyExistingOnThisSide()) { + UpdateSqlWithCascadeStatementGenerator<D> updateGenerator = new UpdateSqlWithCascadeStatementGenerator<D>(metadataModel, metadata, dtoType, request.getIdsOnlyExistingOnThisSide()) { @Override protected <DD extends ReferentialDto> ImmutableList<String> insertMissingReferential(Class<DD> referentialType, String id) { @@ -212,9 +208,7 @@ public class ReferentialSynchronizeSqlsRequestBuilder { D referential = binder.toDto(referentialLocale, entity); ImmutableList<String> sqls = updateGenerator.generateSql(referential); - if (log.isInfoEnabled()) { - log.info("Update referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); - } + log.info("Update referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); for (String sql : sqls) { resultBuilder.addUpdateStatement(sql); } @@ -222,14 +216,12 @@ public class ReferentialSynchronizeSqlsRequestBuilder { } else { - UpdateSqlStatementGenerator<D> updateGenerator = new UpdateSqlStatementGenerator<>(metadata, dtoType); + UpdateSqlStatementGenerator<D> updateGenerator = new UpdateSqlStatementGenerator<>(metadataModel, metadata, dtoType); for (E entity : updateEntities) { D referential = binder.toDto(referentialLocale, entity); ImmutableList<String> sqls = updateGenerator.generateSql(referential); - if (log.isInfoEnabled()) { - log.info("Update referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); - } + log.info("Update referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); for (String sql : sqls) { resultBuilder.addUpdateStatement(sql); } @@ -244,15 +236,13 @@ public class ReferentialSynchronizeSqlsRequestBuilder { TopiaMetadataEntity metadata = metadataModel.getEntity(referentialName); Class<E> entityType = binder.getEntityType(); - UpdateSqlStatementGenerator<D> updateGenerator = new UpdateSqlStatementGenerator<>(metadata, binder.getDtoType()); + UpdateSqlStatementGenerator<D> updateGenerator = new UpdateSqlStatementGenerator<>(metadataModel, metadata, binder.getDtoType()); List<E> updateEntities = loadEntities(entityType, tasks); for (E entity : updateEntities) { D referential = binder.toDto(referentialLocale, entity); ImmutableList<String> sqls = updateGenerator.generateSql(referential); - if (log.isInfoEnabled()) { - log.info("Revert referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); - } + log.info("Revert referential: " + referenceType.getName() + " / " + referential.getId() + " -- " + sqls); for (String sql : sqls) { resultBuilder.addUpdateStatement(sql); } @@ -264,8 +254,8 @@ public class ReferentialSynchronizeSqlsRequestBuilder { TopiaMetadataEntity metadata = metadataModel.getEntity(referentialName); - ReplaceSqlStatementGenerator replaceGenerator = new ReplaceSqlStatementGenerator(metadataModel, referentialName); - DeleteSqlStatementGenerator deleteGenerator = new DeleteSqlStatementGenerator(metadata); + ReplaceSqlStatementGenerator replaceGenerator = new ReplaceSqlStatementGenerator(metadataModel, metadata); + DeleteSqlStatementGenerator deleteGenerator = new DeleteSqlStatementGenerator(metadataModel, metadata); for (ReferentialSynchronizeTask<R> task : tasks) { @@ -291,8 +281,8 @@ public class ReferentialSynchronizeSqlsRequestBuilder { TopiaMetadataEntity metadata = metadataModel.getEntity(referentialName); - ReplaceSqlStatementGenerator replaceGenerator = new ReplaceSqlStatementGenerator(metadataModel, referentialName); - DesactivateSqlStatementGenerator desactivateGenerator = new DesactivateSqlStatementGenerator(metadata); + ReplaceSqlStatementGenerator replaceGenerator = new ReplaceSqlStatementGenerator(metadataModel, metadata); + DisableSqlStatementGenerator desactivateGenerator = new DisableSqlStatementGenerator(metadata); for (ReferentialSynchronizeTask<R> task : tasks) { String referentialId = task.getReferentialId(); @@ -305,9 +295,7 @@ public class ReferentialSynchronizeSqlsRequestBuilder { } String sql = desactivateGenerator.generateSql(referentialId); - if (log.isInfoEnabled()) { - log.info("Desactivate referential: " + type.getName() + " / " + referentialId + " -- " + sql); - } + log.info("Desactivate referential: " + type.getName() + " / " + referentialId + " -- " + sql); resultBuilder.addDesactivateStatement(sql); } @@ -320,7 +308,7 @@ public class ReferentialSynchronizeSqlsRequestBuilder { String referentialName = ObserveEntityEnum.valueOf(entityType).name(); TopiaMetadataEntity metadata = metadataModel.getEntity(referentialName); - InsertSqlStatementGenerator<D> insertGenerator = new InsertSqlStatementGenerator<>(metadata, dtoType); + InsertSqlStatementGenerator<D> insertGenerator = new InsertSqlStatementGenerator<>(metadataModel, metadata, dtoType); D referential = service.loadEntityToReferentialDto(binder, id); return insertGenerator.generateSql(referential); ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/DeleteSqlStatementGenerator.java ===================================== @@ -23,16 +23,14 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; */ import com.google.common.collect.ImmutableList; -import fr.ird.observe.services.local.service.actions.synchro.referential.sql.UpdateSqlStatementGenerator.ManyToManyAssociationStruct; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.nuiton.topia.persistence.metadata.TopiaMetadataAssociation; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; +import org.nuiton.topia.service.script.TopiaSqlStatements; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; - -import static fr.ird.observe.services.local.service.actions.synchro.referential.sql.UpdateSqlStatementGenerator.MANY_TO_MANY_ASSOCIATION_DELETE_STATEMENT; +import java.util.Objects; +import java.util.Set; /** * Pour générer une requète sql de suppression à partir d'un référentiel donné. @@ -43,56 +41,23 @@ import static fr.ird.observe.services.local.service.actions.synchro.referential. */ public class DeleteSqlStatementGenerator { - /** Logger. */ - private static final Logger log = LogManager.getLogger(DeleteSqlStatementGenerator.class); - - private static final String DELETE_STATEMENT = "DELETE FROM %s.%s WHERE topiaId = '%s';\n"; - private static final String DELETE_ASSOCIATION_STATEMENT = "DELETE FROM %s.%s WHERE %s = '%s';\n"; - - private final String schemaName; - private final String tableName; - private final LinkedHashSet<ManyToManyAssociationStruct> manyToManyAssociations; + private final Set<TopiaMetadataAssociation> associations; + private final TopiaMetadataEntity metadataEntity; - public DeleteSqlStatementGenerator(TopiaMetadataEntity metadataEntity) { - this.schemaName = metadataEntity.getDbSchemaName(); - this.tableName = metadataEntity.getDbTableName(); - Map<String, String> manyToManyAssociationsMap = metadataEntity.getManyToManyAssociations(); - this.manyToManyAssociations = new LinkedHashSet<>(); - for (Map.Entry<String, String> entry : manyToManyAssociationsMap.entrySet()) { - String propertyName = entry.getKey(); - String dbColumnName = metadataEntity.getDbColumnName(propertyName); - String tableName = metadataEntity.getBdManyToManyAssociationTableName(propertyName); - ManyToManyAssociationStruct manyToManyAssociation = new ManyToManyAssociationStruct(propertyName, dbColumnName, tableName); - manyToManyAssociations.add(manyToManyAssociation); - } + public DeleteSqlStatementGenerator(TopiaMetadataModel topiaMetadataModel, TopiaMetadataEntity metadataEntity) { + this.metadataEntity = Objects.requireNonNull(metadataEntity); + this.associations = topiaMetadataModel.getReverseAssociations(metadataEntity); } public List<String> generateSql(String id) { ImmutableList.Builder<String> result = ImmutableList.builder(); - String sql = String.format(DELETE_STATEMENT, schemaName, tableName, id); - if (log.isDebugEnabled()) { - log.debug("sql: " + sql); - } + String sql = TopiaSqlStatements.generateDeleteStatement(metadataEntity, id); result.add(sql); - for (ManyToManyAssociationStruct manyToManyAssociation : manyToManyAssociations) { - generateManyToManyAssociationSql(id, manyToManyAssociation, result); + for (TopiaMetadataAssociation association : associations) { + String sql2 = TopiaSqlStatements.generateAssociationDeleteStatement(association, id); + result.add(TopiaSqlStatements.boxAssociationStatement(sql2)); } return result.build(); } - private void generateManyToManyAssociationSql(String referentialDtoId, ManyToManyAssociationStruct manyToManyAssociation, ImmutableList.Builder<String> result) { - - String manyToManyAssociationTableName = manyToManyAssociation.tableName; - - // On commence toujours par supprimer toutes les anciennes associations, elles seront ré-ajoutées juste après - String deleteSql = String.format(MANY_TO_MANY_ASSOCIATION_DELETE_STATEMENT, - schemaName, - manyToManyAssociationTableName, - tableName, - referentialDtoId); - result.add(deleteSql); - if (log.isDebugEnabled()) { - log.debug("sql: " + deleteSql); - } - } } ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/DesactivateSqlStatementGenerator.java → services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/DisableSqlStatementGenerator.java ===================================== @@ -10,21 +10,22 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; +import org.nuiton.topia.service.script.TopiaSqlStatements; + +import java.util.Objects; /** * Pour générer une requète sql de désactivation d'un référentiel donné. @@ -33,35 +34,16 @@ import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; * @author Tony Chemit - dev@tchemit.fr * @since 5.0 */ -public class DesactivateSqlStatementGenerator { +public class DisableSqlStatementGenerator { - /** Logger. */ - private static final Logger log = LogManager.getLogger(DesactivateSqlStatementGenerator.class); + private final TopiaMetadataEntity metadataEntity; - private static final String UPDATE_STATEMENT = "UPDATE %s.%s SET enabled = false, topiaVersion = topiaVersion + 1 WHERE topiaId ='%s';\n"; - - private final String schemaName; - private final String tableName; - - public DesactivateSqlStatementGenerator(TopiaMetadataEntity metadataEntity) { - this.schemaName = metadataEntity.getDbSchemaName(); - this.tableName = metadataEntity.getDbTableName(); + public DisableSqlStatementGenerator(TopiaMetadataEntity metadataEntity) { + this.metadataEntity = Objects.requireNonNull(metadataEntity); } public String generateSql(String sourceId) { - - StringBuilder result = new StringBuilder(); - - String sql = String.format(UPDATE_STATEMENT, schemaName, tableName, sourceId); - result.append(sql); - - if (log.isDebugEnabled()) { - log.debug("sql: " + sql); - } - - return result.toString(); - + return TopiaSqlStatements.generateUpdateStatement(metadataEntity, sourceId, "enabled = false, topiaVersion = topiaVersion + 1"); } - } ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/InsertSqlStatementGenerator.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -25,13 +25,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; import com.google.common.collect.ImmutableList; import fr.ird.observe.dto.reference.ReferentialDtoReference; import fr.ird.observe.dto.referential.ReferentialDto; -import fr.ird.observe.persistence.ObserveEntityEnum; -import fr.ird.observe.spi.DbModelHelper; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataAssociation; +import org.nuiton.topia.persistence.metadata.TopiaMetadataComposition; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; +import org.nuiton.topia.service.script.TopiaSqlStatements; import org.nuiton.util.beans.Binder; import org.nuiton.util.beans.BinderFactory; @@ -42,6 +41,7 @@ import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -53,49 +53,31 @@ import java.util.Set; */ public class InsertSqlStatementGenerator<D extends ReferentialDto> { - /** Logger. */ - private static final Logger log = LogManager.getLogger(InsertSqlStatementGenerator.class); - - private static final String INSERT_STATEMENT = "INSERT INTO %s.%s(%s) VALUES (%s);\n"; - // We use a special prefix because those requests must be applied after all simple insert requests - public static final String MANY_TO_MANY_ASSOCIATION_INSERT_STATEMENT = "$$_INSERT INTO %s.%s(%s, %s) VALUES ('%s', '%s');\n"; - + private final TopiaMetadataEntity metadataEntity; + private final Set<TopiaMetadataComposition> compositions; + private final Set<TopiaMetadataAssociation> associations; private final Set<String> columnNames; - private final String schemaName; - private final String tableName; private final Binder<D, D> binder; private final String[] simplePropertyNames; - private final String[] manyToOneAssociationNames; - private final Set<ManyToManyAssociationStruct> manyToManyAssociations; + private final Set<String> primitiveBooleanPropertyNames; private final Set<String> primitiveIntegerPropertyNames; private final Set<String> primitiveLongPropertyNames; private final Set<String> primitiveFloatPropertyNames; - public InsertSqlStatementGenerator(TopiaMetadataEntity metadataEntity, Class<D> dtoType) { - this.schemaName = metadataEntity.getDbSchemaName(); - this.tableName = metadataEntity.getDbTableName(); + public InsertSqlStatementGenerator(TopiaMetadataModel topiaMetadataModel, TopiaMetadataEntity metadataEntity, Class<D> dtoType) { + this.metadataEntity = Objects.requireNonNull(metadataEntity); + this.compositions = topiaMetadataModel.getCompositions(this.metadataEntity); + this.associations = topiaMetadataModel.getAssociations(this.metadataEntity); + Set<String> propertyNamesSet = metadataEntity.getProperties().keySet(); this.simplePropertyNames = propertyNamesSet.toArray(new String[0]); this.primitiveBooleanPropertyNames = metadataEntity.getPrimitivePropertyNames("boolean"); this.primitiveIntegerPropertyNames = metadataEntity.getPrimitivePropertyNames("int"); this.primitiveLongPropertyNames = metadataEntity.getPrimitivePropertyNames("long"); this.primitiveFloatPropertyNames = metadataEntity.getPrimitivePropertyNames("float"); - Set<String> manyToOneAssociationNamesSet = metadataEntity.getManyToOneAssociations().keySet(); - this.manyToOneAssociationNames = manyToOneAssociationNamesSet.toArray(new String[0]); - - Map<String, String> manyToManyAssociationsMap = metadataEntity.getManyToManyAssociations(); - this.manyToManyAssociations = new LinkedHashSet<>(); - for (Map.Entry<String, String> entry : manyToManyAssociationsMap.entrySet()) { - String propertyName = entry.getKey(); - String dbColumnName = metadataEntity.getDbColumnName(propertyName); - String tableName = metadataEntity.getBdManyToManyAssociationTableName(propertyName); - String typeName = entry.getValue(); - ObserveEntityEnum entityEnum = ObserveEntityEnum.valueOf(typeName); - Class<? extends ReferentialDto> referentialype = DbModelHelper.fromReferentialEntity(entityEnum).toDtoType(); - ManyToManyAssociationStruct manyToManyAssociation = new ManyToManyAssociationStruct(propertyName, dbColumnName, tableName, referentialype); - manyToManyAssociations.add(manyToManyAssociation); - } + + String[] manyToOneAssociationNames = compositions.stream().map(TopiaMetadataComposition::getTargetDbName).toArray(String[]::new); this.columnNames = computeColumnNames(metadataEntity, simplePropertyNames, manyToOneAssociationNames); this.binder = BinderFactory.newBinder(dtoType); } @@ -151,76 +133,46 @@ public class InsertSqlStatementGenerator<D extends ReferentialDto> { addOtherTypeParameter(parameterValue, parameters); } - Map<String, Object> manyToOneParameters = binder.obtainProperties(referentialDto, true, true, manyToOneAssociationNames); - for (String manyToOneAssociationName : manyToOneAssociationNames) { - Object parameterValue = manyToOneParameters.get(manyToOneAssociationName); - if (parameterValue == null) { + for (TopiaMetadataComposition composition : compositions) { + Object compositionValue = binder.obtainSourceProperty(referentialDto, composition.getTargetPropertyName()); + if (compositionValue == null) { addNullParameter(parameters); continue; } - if (parameterValue instanceof ReferentialDto) { - addReferentialDtoParameter((ReferentialDto) parameterValue, parameters, result); + if (compositionValue instanceof ReferentialDto) { + addReferentialDtoParameter((ReferentialDto) compositionValue, parameters, result); continue; } - if (parameterValue instanceof ReferentialDtoReference) { - addReferentialReferenceParameter((ReferentialDtoReference) parameterValue, parameters, result); + if (compositionValue instanceof ReferentialDtoReference) { + addReferentialReferenceParameter((ReferentialDtoReference) compositionValue, parameters, result); } } + String insertSql = TopiaSqlStatements.generateInsertStatement(metadataEntity, + String.join(",", columnNames), + String.join(",", parameters)); + result.add(insertSql); - result.add(String.format(INSERT_STATEMENT, - schemaName, - tableName, - String.join(",", columnNames), - String.join(",", parameters))); + String id = referentialDto.getId(); + for (TopiaMetadataAssociation association : associations) { - if (log.isDebugEnabled()) { - log.debug("sql: " + result); - } - for (ManyToManyAssociationStruct manyToManyAssociation : manyToManyAssociations) { - generateNmAssociationSql(referentialDto, manyToManyAssociation, result); + Collection<ReferentialDtoReference<?, ?>> associationValues = binder.obtainSourceProperty(referentialDto, association.getTargetPropertyName()); + for (ReferentialDtoReference<?, ?> associationValue : associationValues) { + String insertAssocationSql = TopiaSqlStatements.generateAssociationInsertStatement(association, id, associationValue.getId()); + result.add(TopiaSqlStatements.boxAssociationStatement(insertAssocationSql)); + } } - return result.build(); } - private void generateNmAssociationSql(D referentialDto, ManyToManyAssociationStruct manyToManyAssociationStruct, ImmutableList.Builder<String> result) { - - Collection<ReferentialDtoReference<?, ?>> manyToManyAssociationValues = binder.obtainSourceProperty(referentialDto, manyToManyAssociationStruct.propertyName); - if (CollectionUtils.isNotEmpty(manyToManyAssociationValues)) { - - String nmAssociationTableName = manyToManyAssociationStruct.tableName; - String nmAssociationDbColumnName = manyToManyAssociationStruct.dbColumnName; - String referentialDtoId = referentialDto.getId(); - - for (ReferentialDtoReference<?, ?> nmAssociationValue : manyToManyAssociationValues) { - - addMnAssociation(nmAssociationTableName, nmAssociationDbColumnName, referentialDtoId, manyToManyAssociationStruct.type, nmAssociationValue.getId(), result); - - } - } - } - - <DD extends ReferentialDto> void addMnAssociation(String nmAssociationTableName, - String nmAssociationDbColumnName, - String referentialDtoId, - Class<DD> associationType, - String associationId, - ImmutableList.Builder<String> builder) { - - String sql = String.format(MANY_TO_MANY_ASSOCIATION_INSERT_STATEMENT, - schemaName, - nmAssociationTableName, - this.tableName, - nmAssociationDbColumnName, - referentialDtoId, - associationId); - if (log.isDebugEnabled()) { - log.debug("sql: " + sql); - } - builder.add(sql); + <DD extends ReferentialDto, RR extends ReferentialDtoReference<DD, RR>> void addAssociation(TopiaMetadataAssociation association, + String sourceId, + RR associationValue, + ImmutableList.Builder<String> builder) { + String insertAssocationSql = TopiaSqlStatements.generateAssociationInsertStatement(association, sourceId, associationValue.getId()); + builder.add(TopiaSqlStatements.boxAssociationStatement(insertAssocationSql)); } private Set<String> computeColumnNames(TopiaMetadataEntity metadataEntity, @@ -288,32 +240,4 @@ public class InsertSqlStatementGenerator<D extends ReferentialDto> { addStringParameter(parameter.getId(), parameters); } - /** - * Pour décrire une association nm. - */ - private static class ManyToManyAssociationStruct { - - /** - * Le nom de la propriété dans l'objet. - */ - private final String propertyName; - /** - * Le nom de la colonne de l'association dans la table d'association. - */ - private final String dbColumnName; - /** - * Le nom de la table d'association. - */ - private final String tableName; - - private final Class<? extends ReferentialDto> type; - - private ManyToManyAssociationStruct(String propertyName, String dbColumnName, String tableName, Class<? extends ReferentialDto> type) { - this.propertyName = propertyName; - this.dbColumnName = dbColumnName; - this.tableName = tableName; - this.type = type; - } - - } } ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/InsertSqlWithCascadeStatementGenerator.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -26,7 +26,9 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import fr.ird.observe.dto.reference.ReferentialDtoReference; import fr.ird.observe.dto.referential.ReferentialDto; +import org.nuiton.topia.persistence.metadata.TopiaMetadataAssociation; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; import java.util.List; @@ -43,16 +45,19 @@ public abstract class InsertSqlWithCascadeStatementGenerator<D extends Referenti private final InsertSqlStatementGenerator<D> delegateGenerator; private final Multimap<Class<? extends ReferentialDtoReference>, String> idsOnlyExistingOnThisSide; - protected InsertSqlWithCascadeStatementGenerator(TopiaMetadataEntity metadataEntity, + protected InsertSqlWithCascadeStatementGenerator(TopiaMetadataModel topiaMetadataModel, TopiaMetadataEntity metadataEntity, Class<D> dtoType, Multimap<Class<? extends ReferentialDtoReference>, String> idsOnlyExistingOnThisSide) { this.idsOnlyExistingOnThisSide = idsOnlyExistingOnThisSide; - this.delegateGenerator = new InsertSqlStatementGenerator<D>(metadataEntity, dtoType) { + this.delegateGenerator = new InsertSqlStatementGenerator<D>(topiaMetadataModel, metadataEntity, dtoType) { @Override - protected <DD extends ReferentialDto> void addMnAssociation(String nmAssociationTableName, String nmAssociationDbColumnName, String referentialDtoId, Class<DD> associationType, String associationId, ImmutableList.Builder<String> builder) { - super.addMnAssociation(nmAssociationTableName, nmAssociationDbColumnName, referentialDtoId, associationType, associationId, builder); - addMissingReferentialIfNecessary(associationType, associationId, builder); + <DD extends ReferentialDto, RR extends ReferentialDtoReference<DD, RR>> void addAssociation(TopiaMetadataAssociation association, + String sourceId, + RR associationValue, + ImmutableList.Builder<String> builder) { + super.addAssociation(association, sourceId, associationValue, builder); + addMissingReferentialIfNecessary(associationValue.getDtoType(), associationValue.getId(), builder); } @Override ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/ReplaceSqlStatementGenerator.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -23,17 +23,25 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; */ import com.google.common.collect.ImmutableList; +import fr.ird.observe.entities.referentiel.ObserveReferentialEntity; +import fr.ird.observe.persistence.ObserveEntityEnum; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataAssociation; +import org.nuiton.topia.persistence.metadata.TopiaMetadataComposition; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; +import org.nuiton.topia.service.script.TopiaSqlStatements; -import java.util.LinkedHashSet; +import java.util.Objects; import java.util.Set; -import java.util.stream.Collectors; /** * Pour générer une requète sql de remplacement à partir d'un référentiel donné. + * <p> + * À noter que l'on ne traite pas ici les remplacements d'association sur des types référentiel. + * <p> * Created on 04/07/16. * * @author Tony Chemit - dev@tchemit.fr @@ -44,118 +52,36 @@ public class ReplaceSqlStatementGenerator { /** Logger. */ private static final Logger log = LogManager.getLogger(ReplaceSqlStatementGenerator.class); - private static final String MANY_TO_ONE_ASSOCIATION_UPDATE_STATEMENT = "UPDATE %s.%s SET %s = '%s', topiaVersion = topiaVersion + 1 WHERE %s = '%s';\n"; - private static final String MANY_TO_MANY_ASSOCIATION_UPDATE_STATEMENT = "UPDATE %s.%s SET %s = '%s' WHERE %s = '%s';\n"; - /** * Informations pour remplacer dans une relation many-to-one. */ - private final Set<ReplacementStruct> manyToOneAssociationReplacements; + private final Set<TopiaMetadataComposition> compositions; /** * Informations pour remplacer dans une relation many-to-many. */ - private final Set<ReplacementStruct> manyToManyAssociationReplacements; + private final Set<TopiaMetadataAssociation> associations; - public ReplaceSqlStatementGenerator(TopiaMetadataModel topiaMetadataModel, String referentialName) { - this.manyToOneAssociationReplacements = computeManyToOneAssociationReplacements(referentialName, topiaMetadataModel); - this.manyToManyAssociationReplacements = computeManyToManyAssociationReplacements(referentialName, topiaMetadataModel); + public ReplaceSqlStatementGenerator(TopiaMetadataModel topiaMetadataModel, TopiaMetadataEntity metadataEntity) { + this.compositions = Objects.requireNonNull(topiaMetadataModel).getReverseCompositions(Objects.requireNonNull(metadataEntity)); + this.associations = topiaMetadataModel.getReverseAssociations(metadataEntity); } public ImmutableList<String> generateSqls(String sourceId, String replacementId) { - ImmutableList.Builder<String> builder = ImmutableList.builder(); - - for (ReplacementStruct replacementStruct : manyToOneAssociationReplacements) { - - String sql = generateSqlStatement(MANY_TO_ONE_ASSOCIATION_UPDATE_STATEMENT, sourceId, replacementId, replacementStruct); + for (TopiaMetadataComposition replacementStruct : compositions) { + String sql = TopiaSqlStatements.generateCompositionUpdateStatement(replacementStruct, sourceId, replacementId); builder.add(sql); - } - - for (ReplacementStruct replacementStruct : manyToManyAssociationReplacements) { - - String sql = generateSqlStatement(MANY_TO_MANY_ASSOCIATION_UPDATE_STATEMENT, sourceId, replacementId, replacementStruct); + for (TopiaMetadataAssociation replacementStruct : associations) { + Class<? extends TopiaEntity> entityType = ObserveEntityEnum.valueOf(replacementStruct.getOwner().getType()).getContract(); + if (ObserveReferentialEntity.class.isAssignableFrom(entityType)) { + // do not update referentials associations (see https://gitlab.com/ultreiaio/ird-observe/issues/1065) + continue; + } + String sql = TopiaSqlStatements.generateAssociationUpdateStatement(replacementStruct, sourceId, replacementId); builder.add(sql); } - return builder.build(); - - } - - private Set<ReplacementStruct> computeManyToOneAssociationReplacements(String referentialName, TopiaMetadataModel topiaMetadataModel) { - - Set<ReplacementStruct> result = new LinkedHashSet<>(); - - for (TopiaMetadataEntity metadataEntity : topiaMetadataModel) { - - result.addAll(metadataEntity.getManyToOneAssociations().entrySet().stream() - .filter(entry -> entry.getValue().equals(referentialName)) - .map(entry -> new ReplacementStruct(metadataEntity.getDbSchemaName(), - metadataEntity.getDbTableName(), - metadataEntity.getDbColumnName(entry.getKey()))) - .collect(Collectors.toList())); - - } - - return result; - - } - - private Set<ReplacementStruct> computeManyToManyAssociationReplacements(String referentialName, TopiaMetadataModel topiaMetadataModel) { - - Set<ReplacementStruct> result = new LinkedHashSet<>(); - - for (TopiaMetadataEntity metadataEntity : topiaMetadataModel) { - - result.addAll(metadataEntity.getManyToManyAssociations().entrySet().stream() - .filter(entry -> entry.getValue().equals(referentialName)) - .map(entry -> new ReplacementStruct(metadataEntity.getDbSchemaName(), - metadataEntity.getBdManyToManyAssociationTableName(entry.getKey()), - metadataEntity.getDbColumnName(entry.getKey()))) - .collect(Collectors.toList())); - - } - - return result; - - } - - private String generateSqlStatement(String sqlPattern, String sourceId, String replacementId, ReplacementStruct replacementStruct) { - - String sql = String.format(sqlPattern, - replacementStruct.schemaName, - replacementStruct.tableName, - replacementStruct.columnName, - replacementId, - replacementStruct.columnName, - sourceId); - if (log.isDebugEnabled()) { - log.debug("sql: " + sql); - } - return sql; - - } - - private static class ReplacementStruct { - - private final String schemaName; - private final String tableName; - private final String columnName; - - private ReplacementStruct(String schemaName, String tableName, String columnName) { - this.schemaName = schemaName; - this.tableName = tableName; - this.columnName = columnName; - } - - @Override - public String toString() { - return "ReplacementStruct{" + - "schemaName='" + schemaName + '\'' + - ", tableName='" + tableName + '\'' + - ", columnName='" + columnName + '\'' + - '}'; - } } } ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/UpdateSqlStatementGenerator.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -25,24 +25,23 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; import com.google.common.collect.ImmutableList; import fr.ird.observe.dto.reference.ReferentialDtoReference; import fr.ird.observe.dto.referential.ReferentialDto; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataAssociation; +import org.nuiton.topia.persistence.metadata.TopiaMetadataComposition; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; +import org.nuiton.topia.service.script.TopiaSqlStatements; import org.nuiton.util.beans.Binder; import org.nuiton.util.beans.BinderFactory; import java.sql.Timestamp; import java.util.Collection; import java.util.Date; -import java.util.LinkedHashSet; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; -import static fr.ird.observe.services.local.service.actions.synchro.referential.sql.InsertSqlStatementGenerator.MANY_TO_MANY_ASSOCIATION_INSERT_STATEMENT; - /** * Pour générer une requète sql de mise à jour à partir d'un référentiel donné. * <p> @@ -52,49 +51,32 @@ import static fr.ird.observe.services.local.service.actions.synchro.referential. */ public class UpdateSqlStatementGenerator<D extends ReferentialDto> { - /** Logger. */ - private static final Logger log = LogManager.getLogger(UpdateSqlStatementGenerator.class); - - private static final String UPDATE_STATEMENT = "UPDATE %s.%s SET %s WHERE topiaId ='%s';\n"; - // We use a special prefix because those requests must be applied before all simple insert requests - static final String MANY_TO_MANY_ASSOCIATION_DELETE_STATEMENT = "$$_DELETE FROM %s.%s WHERE %s = '%s';\n"; - private final Map<String, String> columnNames; - private final String schemaName; - private final String tableName; private final Binder<D, D> binder; private final String[] simplePropertyNames; - private final String[] manyToOneAssociationNames; - private final Set<ManyToManyAssociationStruct> manyToManyAssociations; + private final TopiaMetadataEntity metadataEntity; + private final Set<TopiaMetadataComposition> compositions; + private final Set<TopiaMetadataAssociation> associations; private final Set<String> primitiveBooleanPropertyNames; private final Set<String> primitiveIntegerPropertyNames; private final Set<String> primitiveLongPropertyNames; private final Set<String> primitiveFloatPropertyNames; - public UpdateSqlStatementGenerator(TopiaMetadataEntity metadataEntity, Class<D> dtoType) { - this.schemaName = metadataEntity.getDbSchemaName(); - this.tableName = metadataEntity.getDbTableName(); + public UpdateSqlStatementGenerator(TopiaMetadataModel topiaMetadataModel, TopiaMetadataEntity metadataEntity, Class<D> dtoType) { + this.metadataEntity = Objects.requireNonNull(metadataEntity); + this.compositions = topiaMetadataModel.getCompositions(metadataEntity); + this.associations = topiaMetadataModel.getAssociations(metadataEntity); - Set<String> simplePropertyNamesSet = metadataEntity.getProperties().keySet(); + Set<String> simplePropertyNamesSet = this.metadataEntity.getProperties().keySet(); this.simplePropertyNames = simplePropertyNamesSet.toArray(new String[0]); - this.primitiveBooleanPropertyNames = metadataEntity.getPrimitivePropertyNames("boolean"); - this.primitiveIntegerPropertyNames = metadataEntity.getPrimitivePropertyNames("int"); - this.primitiveLongPropertyNames = metadataEntity.getPrimitivePropertyNames("long"); - this.primitiveFloatPropertyNames = metadataEntity.getPrimitivePropertyNames("float"); - - Set<String> manyToOneAssociationNamesSet = metadataEntity.getManyToOneAssociations().keySet(); - this.manyToOneAssociationNames = manyToOneAssociationNamesSet.toArray(new String[0]); - - Map<String, String> manyToManyAssociationsMap = metadataEntity.getManyToManyAssociations(); - this.manyToManyAssociations = new LinkedHashSet<>(); - for (Map.Entry<String, String> entry : manyToManyAssociationsMap.entrySet()) { - String propertyName = entry.getKey(); - String dbColumnName = metadataEntity.getDbColumnName(propertyName); - String tableName = metadataEntity.getBdManyToManyAssociationTableName(propertyName); - ManyToManyAssociationStruct manyToManyAssociation = new ManyToManyAssociationStruct(propertyName, dbColumnName, tableName); - manyToManyAssociations.add(manyToManyAssociation); - } - this.columnNames = computeColumnNames(metadataEntity, simplePropertyNames, manyToOneAssociationNames); + this.primitiveBooleanPropertyNames = this.metadataEntity.getPrimitivePropertyNames("boolean"); + this.primitiveIntegerPropertyNames = this.metadataEntity.getPrimitivePropertyNames("int"); + this.primitiveLongPropertyNames = this.metadataEntity.getPrimitivePropertyNames("long"); + this.primitiveFloatPropertyNames = this.metadataEntity.getPrimitivePropertyNames("float"); + + String[] manyToOneAssociationNames = compositions.stream().map(TopiaMetadataComposition::getTargetDbName).toArray(String[]::new); + + this.columnNames = computeColumnNames(this.metadataEntity, simplePropertyNames, manyToOneAssociationNames); this.binder = BinderFactory.newBinder(dtoType); } @@ -148,121 +130,54 @@ public class UpdateSqlStatementGenerator<D extends ReferentialDto> { addEnumParameter(columnName, (Enum) simplePropertyValue, parameters); continue; } - addOtherTypeParameter(columnName, simplePropertyValue, parameters); - } - } ImmutableList.Builder<String> result = ImmutableList.builder(); - if (manyToOneAssociationNames.length > 0) { - - Map<String, Object> manyToOneAssociations = binder.obtainProperties(referentialDto, true, manyToOneAssociationNames); - for (Map.Entry<String, Object> entry : manyToOneAssociations.entrySet()) { - - String manyToOneAssociationName = entry.getKey(); - String columnName = columnNames.get(manyToOneAssociationName); - Object manyToOneAssociationValue = entry.getValue(); - - if (manyToOneAssociationValue == null) { - addNullParameter(columnName, parameters); - continue; - } - if (manyToOneAssociationValue instanceof ReferentialDto) { - addReferentialDtoParameter(columnName, (ReferentialDto) manyToOneAssociationValue, parameters, result); - continue; - } - if (manyToOneAssociationValue instanceof ReferentialDtoReference) { - addReferentialReferenceParameter(columnName, (ReferentialDtoReference) manyToOneAssociationValue, parameters, result); - } - + for (TopiaMetadataComposition composition : compositions) { + Object compositionValue = binder.obtainSourceProperty(referentialDto, composition.getTargetPropertyName()); + String columnName = composition.getTargetDbName(); + if (compositionValue == null) { + addNullParameter(columnName, parameters); + continue; + } + if (compositionValue instanceof ReferentialDto) { + addReferentialDtoParameter(columnName, (ReferentialDto) compositionValue, parameters, result); + continue; + } + if (compositionValue instanceof ReferentialDtoReference) { + addReferentialReferenceParameter(columnName, (ReferentialDtoReference) compositionValue, parameters, result); } - - } - - - String sql = String.format(UPDATE_STATEMENT, - schemaName, - tableName, - parameters.substring(2), - referentialDto.getId()); - result.add(sql); - if (log.isDebugEnabled()) { - log.debug("sql: " + sql); - } - - for (ManyToManyAssociationStruct manyToManyAssociation : manyToManyAssociations) { - generateManyToManyAssociationSql(referentialDto, manyToManyAssociation, result); - } - - return result.build(); - - } - - private void generateManyToManyAssociationSql(D referentialDto, ManyToManyAssociationStruct manyToManyAssociation, ImmutableList.Builder<String> result) { - - String referentialDtoId = referentialDto.getId(); - String manyToManyAssociationTableName = manyToManyAssociation.tableName; - - // On commence toujours par supprimer toutes les anciennes associations, elles seront ré-ajoutées juste après - String deleteSql = String.format(MANY_TO_MANY_ASSOCIATION_DELETE_STATEMENT, - schemaName, - manyToManyAssociationTableName, - tableName, - referentialDtoId); - result.add(deleteSql); - if (log.isDebugEnabled()) { - log.debug("sql: " + deleteSql); } - Collection<ReferentialDtoReference<?, ?>> manyToManyAssociationValues = binder.obtainSourceProperty(referentialDto, manyToManyAssociation.propertyName); - if (CollectionUtils.isNotEmpty(manyToManyAssociationValues)) { - - - String manyToManyAssociationDbColumnName = manyToManyAssociation.dbColumnName; + String updateSql = TopiaSqlStatements.generateUpdateStatement(metadataEntity, parameters.substring(2), referentialDto.getId()); + result.add(updateSql); + String id = referentialDto.getId(); + for (TopiaMetadataAssociation association : associations) { + // On commence toujours par supprimer toutes les anciennes associations, elles seront ré-ajoutées juste après + String deleteSql = TopiaSqlStatements.generateAssociationDeleteStatement(association, id); + result.add(TopiaSqlStatements.boxAssociationStatement(deleteSql)); - for (ReferentialDtoReference<?, ?> manyToManyAssociationValue : manyToManyAssociationValues) { - - addMnAssociation( - manyToManyAssociationTableName, - manyToManyAssociationDbColumnName, - referentialDtoId, - manyToManyAssociationValue.getDtoType(), - manyToManyAssociationValue.getId(), - result - ); + Collection<ReferentialDtoReference<?, ?>> associationValues = binder.obtainSourceProperty(referentialDto, association.getTargetPropertyName()); + for (ReferentialDtoReference associationValue : associationValues) { + addAssociation(association, id, associationValue, result); } } - + return result.build(); } - protected <DD extends ReferentialDto> void addMnAssociation(String nmAssociationTableName, - String nmAssociationDbColumnName, - String referentialDtoId, - Class<DD> associationType, - String associationId, - ImmutableList.Builder<String> builder) { - - String sql = String.format(MANY_TO_MANY_ASSOCIATION_INSERT_STATEMENT, - schemaName, - nmAssociationTableName, - this.tableName, - nmAssociationDbColumnName, - referentialDtoId, - associationId); - if (log.isDebugEnabled()) { - log.debug("sql: " + sql); - } - builder.add(sql); - + <DD extends ReferentialDto, RR extends ReferentialDtoReference<DD, RR>> void addAssociation(TopiaMetadataAssociation association, + String sourceId, + RR associationValue, + ImmutableList.Builder<String> builder) { + String insertSql = TopiaSqlStatements.generateAssociationInsertStatement(association, sourceId, associationValue.getId()); + builder.add(TopiaSqlStatements.boxAssociationStatement(insertSql)); } - private Map<String, String> computeColumnNames(TopiaMetadataEntity metadataEntity, - String[] simplePropertyNames, - String[] compositionPropertyNames) { + private Map<String, String> computeColumnNames(TopiaMetadataEntity metadataEntity, String[] simplePropertyNames, String[] compositionPropertyNames) { Map<String, String> columnNames = new TreeMap<>(); for (String propertyName : simplePropertyNames) { @@ -326,29 +241,4 @@ public class UpdateSqlStatementGenerator<D extends ReferentialDto> { addParameter0(columnName, "" + (parameter == null ? 0f : parameter), parameters); } - /** - * Pour décrire une association nm. - */ - static class ManyToManyAssociationStruct { - - /** - * Le nom de la propriété dans l'objet. - */ - private final String propertyName; - /** - * Le nom de la colonne de l'association dans la table d'association. - */ - private final String dbColumnName; - /** - * Le nom de la table d'association. - */ - final String tableName; - - ManyToManyAssociationStruct(String propertyName, String dbColumnName, String tableName) { - this.propertyName = propertyName; - this.dbColumnName = dbColumnName; - this.tableName = tableName; - } - - } } ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/actions/synchro/referential/sql/UpdateSqlWithCascadeStatementGenerator.java ===================================== @@ -10,12 +10,12 @@ package fr.ird.observe.services.local.service.actions.synchro.referential.sql; * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. @@ -26,7 +26,9 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import fr.ird.observe.dto.reference.ReferentialDtoReference; import fr.ird.observe.dto.referential.ReferentialDto; +import org.nuiton.topia.persistence.metadata.TopiaMetadataAssociation; import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; /** * Pour générer une requète sql d'ajout à partir d'un référentiel donné et aussi tous les inserts manquants. @@ -41,17 +43,20 @@ public abstract class UpdateSqlWithCascadeStatementGenerator<D extends Referenti private final UpdateSqlStatementGenerator<D> delegateGenerator; private final Multimap<Class<? extends ReferentialDtoReference>, String> idsOnlyExistingOnThisSide; - protected UpdateSqlWithCascadeStatementGenerator(TopiaMetadataEntity metadataEntity, + protected UpdateSqlWithCascadeStatementGenerator(TopiaMetadataModel topiaMetadataModel, + TopiaMetadataEntity metadataEntity, Class<D> dtoType, Multimap<Class<? extends ReferentialDtoReference>, String> idsOnlyExistingOnThisSide) { this.idsOnlyExistingOnThisSide = idsOnlyExistingOnThisSide; - this.delegateGenerator = new UpdateSqlStatementGenerator<D>(metadataEntity, dtoType) { + this.delegateGenerator = new UpdateSqlStatementGenerator<D>(topiaMetadataModel, metadataEntity, dtoType) { - @Override - protected <DD extends ReferentialDto> void addMnAssociation(String nmAssociationTableName, String nmAssociationDbColumnName, String referentialDtoId, Class<DD> associationType, String associationId, ImmutableList.Builder<String> result) { - super.addMnAssociation(nmAssociationTableName, nmAssociationDbColumnName, referentialDtoId, associationType, associationId, result); - addMissingReferentialIfNecessary(associationType, associationId, result); + <DD extends ReferentialDto, RR extends ReferentialDtoReference<DD, RR>> void addAssociation(TopiaMetadataAssociation association, + String sourceId, + RR associationValue, + ImmutableList.Builder<String> builder) { + super.addAssociation(association, sourceId, associationValue, builder); + addMissingReferentialIfNecessary(associationValue.getDtoType(), associationValue.getId(), builder); } @Override ===================================== services-local/src/main/java/fr/ird/observe/services/local/service/referential/ReferentialServiceLocal.java ===================================== @@ -28,6 +28,7 @@ import fr.ird.observe.binder.data.DataEntityReferenceBinderSupport; import fr.ird.observe.binder.referential.ReferentialEntityDtoBinderSupport; import fr.ird.observe.binder.referential.ReferentialEntityReferenceBinderSupport; import fr.ird.observe.dto.IdDto; +import fr.ird.observe.dto.IdHelper; import fr.ird.observe.dto.data.DataDto; import fr.ird.observe.dto.form.Form; import fr.ird.observe.dto.form.FormDefinition; @@ -42,7 +43,6 @@ import fr.ird.observe.dto.referential.SpeciesDto; import fr.ird.observe.dto.referential.SpeciesGroupDto; import fr.ird.observe.dto.referential.seine.ObservedSystemReference; import fr.ird.observe.dto.result.SaveResultDto; -import fr.ird.observe.entities.EntityMap; import fr.ird.observe.entities.ObserveDataEntity; import fr.ird.observe.entities.longline.TripLongline; import fr.ird.observe.entities.referentiel.ObserveReferentialEntity; @@ -75,6 +75,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.nuiton.topia.persistence.TopiaDao; import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.metadata.TopiaMetadataEntity; import org.nuiton.topia.persistence.metadata.TopiaMetadataModel; import org.nuiton.topia.persistence.script.SqlScriptConsumer; import org.nuiton.topia.persistence.script.TopiaSqlScript; @@ -86,6 +87,7 @@ import java.util.Collections; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -205,8 +207,8 @@ public class ReferentialServiceLocal extends ObserveServiceLocal implements Refe ObserveEntityEnum entityEnum = ObserveEntityEnum.valueOf(entityType); TopiaMetadataModel metadataModel = serviceContext.getTopiaApplicationContext().getMetadataModel(); - - ReplaceSqlStatementGenerator generator = new ReplaceSqlStatementGenerator(metadataModel, entityEnum.name()); + TopiaMetadataEntity metadataEntity = Objects.requireNonNull(metadataModel.getEntity(entityEnum.name())); + ReplaceSqlStatementGenerator generator = new ReplaceSqlStatementGenerator(metadataModel, metadataEntity); ImmutableList<String> sql = generator.generateSqls(idToReplace, replaceId); @@ -218,16 +220,22 @@ public class ReferentialServiceLocal extends ObserveServiceLocal implements Refe public <D extends ReferentialDto> ImmutableSetDtoMap<DtoReference> findAllUsages(D bean) { ReferentialDtoEntityContext<D, ?, ?> spi = DbModelHelper.fromReferentialDto(bean); - Class<ObserveReferentialEntity> entityType = spi.toEntityType(); - ObserveReferentialEntity entity = loadEntity(spi.toDtoType(), bean.getId()); - TopiaDao<ObserveReferentialEntity> dao = getTopiaPersistenceContext().getDao(entityType); - EntityMap allUsages = new EntityMap(dao.findAllUsages(entity)); + Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> compositions = serviceContext.getTopiaApplicationContext().findReverseCompositions(getTopiaPersistenceContext(), entity, e -> true); + Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> associations = serviceContext.getTopiaApplicationContext().findReverseAssociations(getTopiaPersistenceContext(), entity, IdHelper::isData); ImmutableSetDtoMap.Builder<DtoReference> result = ImmutableSetDtoMap.builder(); - for (Class<? extends TopiaEntity> type : allUsages.keySet()) { - List<? extends TopiaEntity> entities = allUsages.get(type); + + buildUsageResult(compositions, result); + buildUsageResult(associations, result); + return result.build(); + } + + private void buildUsageResult(Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> compositions, ImmutableSetDtoMap.Builder<DtoReference> result) { + for (Map.Entry<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> entry : compositions.entrySet()) { + Class<? extends TopiaEntity> type = entry.getKey(); + List<? extends TopiaEntity> entities = entry.getValue(); if (ObserveReferentialEntity.class.isAssignableFrom(type)) { //noinspection unchecked addAllReferentialUsage(DbModelHelper.fromReferentialEntity((Class) type), (List) entities, result); @@ -236,7 +244,6 @@ public class ReferentialServiceLocal extends ObserveServiceLocal implements Refe adddAllDataUsage(DbModelHelper.fromDataEntity((Class) type), (List) entities, result); } } - return result.build(); } private <D extends ReferentialDto, R extends ReferentialDtoReference<D, R>, E extends ObserveReferentialEntity> ReferentialDtoReferenceSet<R> getReferenceSet0(ReferentialReferenceEntityContext<D, R, E> spi, Date lastUpdateDate) { ===================================== services/pom.xml ===================================== @@ -153,6 +153,10 @@ <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> + <dependency> + <groupId>io.ultreia.java4all.topia</groupId> + <artifactId>service-script</artifactId> + </dependency> </dependencies> ===================================== services/src/main/java/fr/ird/observe/services/service/actions/synchro/referential/ng/ReferentialSynchronizeSqlsRequest.java ===================================== @@ -25,6 +25,7 @@ package fr.ird.observe.services.service.actions.synchro.referential.ng; import fr.ird.observe.dto.ObserveDto; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.nuiton.topia.service.script.TopiaSqlStatements; /** * Created on 08/08/16. @@ -34,7 +35,6 @@ import org.apache.logging.log4j.Logger; */ public class ReferentialSynchronizeSqlsRequest implements ObserveDto { - /** Logger. */ private static final Logger log = LogManager.getLogger(ReferentialSynchronizeSqlsRequest.class); private final byte[] insertAssociationSqlCode; @@ -105,11 +105,9 @@ public class ReferentialSynchronizeSqlsRequest implements ObserveDto { } public Builder addInsertStatement(String sql) { - if (log.isInfoEnabled()) { - log.info("Add add sql: " + sql); - } - if (sql.startsWith("$$_INSERT")) { - addAssociationTasksBuilder.append(sql.substring(3)); + log.info("Add add sql: " + sql); + if (sql.startsWith(TopiaSqlStatements.ASSOCIATION_STATEMENT_PREFIX)) { + addAssociationTasksBuilder.append(TopiaSqlStatements.unboxAssociationStatement(sql)); } else { addTasksBuilder.append(sql); } @@ -117,20 +115,15 @@ public class ReferentialSynchronizeSqlsRequest implements ObserveDto { } public Builder addUpdateStatement(String sql) { - if (log.isInfoEnabled()) { - log.info("Add update sql: " + sql); - } + log.info("Add update sql: " + sql); updateTasksBuilder.append(sql); return this; } public Builder addDeleteStatement(String sql) { - - if (log.isInfoEnabled()) { - log.info("Add delete sql: " + sql); - } - if (sql.startsWith("$$_DELETE")) { - deleteAssociationTasksBuilder.append(sql.substring(3)); + log.info("Add delete sql: " + sql); + if (sql.startsWith(TopiaSqlStatements.ASSOCIATION_STATEMENT_PREFIX)) { + deleteAssociationTasksBuilder.append(TopiaSqlStatements.unboxAssociationStatement(sql)); } else { deleteTasksBuilder.append(sql); } @@ -138,10 +131,7 @@ public class ReferentialSynchronizeSqlsRequest implements ObserveDto { } public Builder addDesactivateStatement(String sql) { - - if (log.isInfoEnabled()) { - log.info("Add desactivate sql: " + sql); - } + log.info("Add desactivate sql: " + sql); desactivateTasksBuilder.append(sql); return this; } View it on GitLab: https://gitlab.com/ultreiaio/ird-observe/compare/bc64ef42537b8b9768425ba88be... -- View it on GitLab: https://gitlab.com/ultreiaio/ird-observe/compare/bc64ef42537b8b9768425ba88be... You're receiving this email because of your account on gitlab.com.