diff options
author | Simon Brandhof <simon.brandhof@sonarsource.com> | 2015-07-05 21:45:32 +0200 |
---|---|---|
committer | Simon Brandhof <simon.brandhof@sonarsource.com> | 2015-07-06 09:22:50 +0200 |
commit | 305df737845a9f3c982735e28907ba6dbdf84623 (patch) | |
tree | ef0ab2c9d6ff3329c8d87439fbd1214cd5e786dd | |
parent | 32af292b745b7226bacc3f34d612437664af0ba3 (diff) | |
download | sonarqube-305df737845a9f3c982735e28907ba6dbdf84623.tar.gz sonarqube-305df737845a9f3c982735e28907ba6dbdf84623.zip |
Improve testability of Dao
139 files changed, 622 insertions, 1234 deletions
diff --git a/server/sonar-server-benchmarks/src/test/java/org/sonar/server/benchmark/SourceDbBenchmarkTest.java b/server/sonar-server-benchmarks/src/test/java/org/sonar/server/benchmark/SourceDbBenchmarkTest.java index 9fd6dceb0cc..64e9d9da589 100644 --- a/server/sonar-server-benchmarks/src/test/java/org/sonar/server/benchmark/SourceDbBenchmarkTest.java +++ b/server/sonar-server-benchmarks/src/test/java/org/sonar/server/benchmark/SourceDbBenchmarkTest.java @@ -20,7 +20,6 @@ package org.sonar.server.benchmark; import java.io.IOException; -import java.sql.Connection; import java.util.Arrays; import java.util.Timer; import java.util.concurrent.atomic.AtomicLong; @@ -30,11 +29,11 @@ import org.junit.Rule; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.sonar.api.utils.System2; import org.sonar.api.utils.internal.Uuids; import org.sonar.db.DbTester; import org.sonar.db.source.FileSourceDao; import org.sonar.db.source.FileSourceDto; -import org.sonar.server.db.DbClient; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.source.index.FileSourcesUpdaterHelper; import org.sonar.server.source.index.SourceLineResultSetIterator; @@ -50,7 +49,7 @@ public class SourceDbBenchmarkTest { public static final String PROJECT_UUID = Uuids.create(); @Rule - public DbTester dbTester = new DbTester(); + public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public Benchmark benchmark = new Benchmark(); @@ -63,8 +62,6 @@ public class SourceDbBenchmarkTest { private void scrollRows() throws Exception { LOGGER.info("Scroll table FILE_SOURCES"); - DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis()); - Connection connection = dbTester.openConnection(); AtomicLong counter = new AtomicLong(); ProgressTask progress = new ProgressTask(LOGGER, "source file", counter); Timer timer = new Timer("SourceDbScroll"); @@ -72,7 +69,7 @@ public class SourceDbBenchmarkTest { try { long start = System.currentTimeMillis(); - SourceLineResultSetIterator it = SourceLineResultSetIterator.create(dbClient, connection, 0L, null); + SourceLineResultSetIterator it = SourceLineResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L, null); while (it.hasNext()) { FileSourcesUpdaterHelper.Row row = it.next(); assertThat(row.getUpdateRequests().size()).isEqualTo(NUMBER_OF_LINES); @@ -86,7 +83,6 @@ public class SourceDbBenchmarkTest { benchmark.expectBetween("Throughput to scroll FILE_SOURCES", throughputPerSecond, 9, 13); } finally { - DbUtils.closeQuietly(connection); timer.cancel(); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/activity/ActivityService.java b/server/sonar-server/src/main/java/org/sonar/server/activity/ActivityService.java index 0aa9be22946..b44edeb98f7 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/activity/ActivityService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/activity/ActivityService.java @@ -19,15 +19,13 @@ */ package org.sonar.server.activity; -import org.sonar.api.server.ServerSide; import org.sonar.api.utils.KeyValueFormat; import org.sonar.api.utils.internal.Uuids; import org.sonar.db.activity.ActivityDto; import org.sonar.server.activity.index.ActivityIndexer; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.user.UserSession; -@ServerSide public class ActivityService { private final DbClient dbClient; diff --git a/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityIndexer.java b/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityIndexer.java index d2b791292ec..f5d651ad4f3 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityIndexer.java +++ b/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityIndexer.java @@ -19,14 +19,12 @@ */ package org.sonar.server.activity.index; +import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; import org.sonar.server.es.BaseIndexer; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.EsClient; -import java.sql.Connection; - /** * Add to Elasticsearch index {@link org.sonar.server.activity.index.ActivityIndexDefinition} the rows of * db table ACTIVITIES that are not indexed yet @@ -47,9 +45,8 @@ public class ActivityIndexer extends BaseIndexer { bulk.setLarge(lastUpdatedAt == 0L); DbSession dbSession = dbClient.openSession(false); - Connection dbConnection = dbSession.getConnection(); try { - ActivityResultSetIterator it = ActivityResultSetIterator.create(dbClient, dbConnection, lastUpdatedAt); + ActivityResultSetIterator it = ActivityResultSetIterator.create(dbClient, dbSession, lastUpdatedAt); bulk.start(); while (it.hasNext()) { bulk.add(it.next()); diff --git a/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityResultSetIterator.java b/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityResultSetIterator.java index afef3531195..66df9694ce5 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityResultSetIterator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/activity/index/ActivityResultSetIterator.java @@ -19,24 +19,23 @@ */ package org.sonar.server.activity.index; -import org.apache.commons.lang.StringUtils; -import org.elasticsearch.action.update.UpdateRequest; -import org.sonar.api.utils.KeyValueFormat; -import org.sonar.api.utils.text.JsonWriter; -import org.sonar.server.db.DbClient; -import org.sonar.db.ResultSetIterator; -import org.sonar.server.es.EsUtils; -import org.sonar.server.util.DateCollector; - import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; -import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; +import org.apache.commons.lang.StringUtils; +import org.elasticsearch.action.update.UpdateRequest; +import org.sonar.api.utils.KeyValueFormat; +import org.sonar.api.utils.text.JsonWriter; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.ResultSetIterator; +import org.sonar.server.es.EsUtils; +import org.sonar.server.util.DateCollector; /** * Scrolls over table ACTIVITIES and reads documents to populate @@ -64,10 +63,10 @@ class ActivityResultSetIterator extends ResultSetIterator<UpdateRequest> { super(stmt); } - static ActivityResultSetIterator create(DbClient dbClient, Connection connection, long afterDate) { + static ActivityResultSetIterator create(DbClient dbClient, DbSession session, long afterDate) { try { String sql = afterDate > 0L ? SQL_AFTER_DATE : SQL_ALL; - PreparedStatement stmt = dbClient.newScrollingSelectStatement(connection, sql); + PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql); if (afterDate > 0L) { stmt.setTimestamp(1, new Timestamp(afterDate)); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java b/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java index 6e51c44b994..63198953463 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/component/ComponentService.java @@ -42,7 +42,7 @@ import org.sonar.db.component.ComponentDto; import org.sonar.core.component.ComponentKeys; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.db.component.ResourceKeyUpdaterDao; import org.sonar.server.db.DbClient; import org.sonar.server.exceptions.BadRequestException; @@ -58,16 +58,16 @@ public class ComponentService { private final ResourceKeyUpdaterDao resourceKeyUpdaterDao; private final I18n i18n; - private final ResourceIndexerDao resourceIndexerDao; + private final ResourceIndexDao resourceIndexDao; private final UserSession userSession; private final System2 system2; - public ComponentService(DbClient dbClient, ResourceKeyUpdaterDao resourceKeyUpdaterDao, I18n i18n, ResourceIndexerDao resourceIndexerDao, + public ComponentService(DbClient dbClient, ResourceKeyUpdaterDao resourceKeyUpdaterDao, I18n i18n, ResourceIndexDao resourceIndexDao, UserSession userSession, System2 system2) { this.dbClient = dbClient; this.resourceKeyUpdaterDao = resourceKeyUpdaterDao; this.i18n = i18n; - this.resourceIndexerDao = resourceIndexerDao; + this.resourceIndexDao = resourceIndexDao; this.userSession = userSession; this.system2 = system2; } @@ -177,7 +177,7 @@ public class ComponentService { .setCreatedAt(new Date(system2.now())) ; dbClient.componentDao().insert(session, component); - resourceIndexerDao.indexResource(session, component.getId()); + resourceIndexDao.indexResource(session, component.getId()); session.commit(); return component.key(); diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/db/ComponentDao.java b/server/sonar-server/src/main/java/org/sonar/server/component/db/ComponentDao.java index b0aa30c56a2..8673e890fd8 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/component/db/ComponentDao.java +++ b/server/sonar-server/src/main/java/org/sonar/server/component/db/ComponentDao.java @@ -31,9 +31,7 @@ import javax.annotation.Nullable; import org.apache.ibatis.session.RowBounds; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; -import org.sonar.api.server.ServerSide; import org.sonar.db.Dao; -import org.sonar.db.DaoUtils; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; @@ -45,10 +43,6 @@ import org.sonar.server.exceptions.NotFoundException; import static com.google.common.collect.Maps.newHashMapWithExpectedSize; -/** - * @since 4.3 - */ -@ServerSide public class ComponentDao implements Dao { public ComponentDto selectById(long id, DbSession session) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/ReportQueue.java b/server/sonar-server/src/main/java/org/sonar/server/computation/ReportQueue.java index b644aa490bb..d009e11e105 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/ReportQueue.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/ReportQueue.java @@ -35,7 +35,7 @@ import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.process.ProcessProperties; import org.sonar.db.compute.AnalysisReportDao; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static org.sonar.db.compute.AnalysisReportDto.Status.PENDING; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/activity/ActivityManager.java b/server/sonar-server/src/main/java/org/sonar/server/computation/activity/ActivityManager.java index 3b73ce07bab..450a00ed4b6 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/activity/ActivityManager.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/activity/ActivityManager.java @@ -20,13 +20,13 @@ package org.sonar.server.computation.activity; import javax.annotation.CheckForNull; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.compute.AnalysisReportDto; +import org.sonar.server.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; +import org.sonar.db.component.ComponentDto; +import org.sonar.db.compute.AnalysisReportDto; import org.sonar.server.activity.Activity; import org.sonar.server.activity.ActivityService; -import org.sonar.server.db.DbClient; import static org.sonar.api.utils.DateUtils.formatDateTimeNullSafe; import static org.sonar.api.utils.DateUtils.longToDate; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/issue/BaseIssuesLoader.java b/server/sonar-server/src/main/java/org/sonar/server/computation/issue/BaseIssuesLoader.java index 3aea9995878..a16f57b2813 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/issue/BaseIssuesLoader.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/issue/BaseIssuesLoader.java @@ -35,7 +35,7 @@ import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.server.computation.batch.BatchReportReader; import org.sonar.server.computation.component.TreeRootHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static com.google.common.collect.FluentIterable.from; import static org.sonar.core.rule.RuleKeyFunctions.stringToRuleKey; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/issue/NewDebtAggregator.java b/server/sonar-server/src/main/java/org/sonar/server/computation/issue/NewDebtAggregator.java index 6f0fef0c988..b616f550890 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/issue/NewDebtAggregator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/issue/NewDebtAggregator.java @@ -36,7 +36,7 @@ import org.sonar.server.computation.metric.Metric; import org.sonar.server.computation.metric.MetricRepository; import org.sonar.server.computation.period.Period; import org.sonar.server.computation.period.PeriodsHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; public class NewDebtAggregator extends IssueVisitor { diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/issue/TrackerBaseInputFactory.java b/server/sonar-server/src/main/java/org/sonar/server/computation/issue/TrackerBaseInputFactory.java index d9b7438b240..621172bc039 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/issue/TrackerBaseInputFactory.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/issue/TrackerBaseInputFactory.java @@ -29,7 +29,7 @@ import org.sonar.core.issue.tracking.LineHashSequence; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.server.computation.component.Component; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; /** * Factory of {@link Input} of base data for issue tracking. Data are lazy-loaded. diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/measure/MeasureRepositoryImpl.java b/server/sonar-server/src/main/java/org/sonar/server/computation/measure/MeasureRepositoryImpl.java index 6bc789371e6..24e22c3e68c 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/measure/MeasureRepositoryImpl.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/measure/MeasureRepositoryImpl.java @@ -36,7 +36,7 @@ import org.sonar.server.computation.component.Component; import org.sonar.server.computation.debt.Characteristic; import org.sonar.server.computation.metric.Metric; import org.sonar.server.computation.metric.MetricRepository; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/ApplyPermissionsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/ApplyPermissionsStep.java index 8e69c81b619..c15eab8d19f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/ApplyPermissionsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/ApplyPermissionsStep.java @@ -26,7 +26,7 @@ import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.server.computation.component.DbIdsRepository; import org.sonar.server.computation.component.TreeRootHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.issue.index.IssueAuthorizationIndexer; /** diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/FeedDebtModelStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/FeedDebtModelStep.java index 602e45a1ae8..6b3ae0b4de4 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/FeedDebtModelStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/FeedDebtModelStep.java @@ -31,7 +31,7 @@ import org.sonar.db.DbSession; import org.sonar.db.debt.CharacteristicDto; import org.sonar.server.computation.debt.Characteristic; import org.sonar.server.computation.debt.MutableDebtModelHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static com.google.common.base.Predicates.not; import static com.google.common.collect.FluentIterable.from; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/FillMeasuresWithVariationsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/FillMeasuresWithVariationsStep.java index 8b9773b90b5..05c90a0451f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/FillMeasuresWithVariationsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/FillMeasuresWithVariationsStep.java @@ -44,7 +44,7 @@ import org.sonar.server.computation.metric.Metric; import org.sonar.server.computation.metric.MetricRepository; import org.sonar.server.computation.period.Period; import org.sonar.server.computation.period.PeriodsHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static org.sonar.server.computation.component.ComponentVisitor.Order.PRE_ORDER; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/IndexComponentsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/IndexComponentsStep.java index 90998d7a063..ba648fa1337 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/IndexComponentsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/IndexComponentsStep.java @@ -20,7 +20,7 @@ package org.sonar.server.computation.step; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.server.computation.component.DbIdsRepository; import org.sonar.server.computation.component.TreeRootHolder; @@ -29,19 +29,19 @@ import org.sonar.server.computation.component.TreeRootHolder; */ public class IndexComponentsStep implements ComputationStep { - private final ResourceIndexerDao resourceIndexerDao; + private final ResourceIndexDao resourceIndexDao; private final DbIdsRepository dbIdsRepository; private final TreeRootHolder treeRootHolder; - public IndexComponentsStep(ResourceIndexerDao resourceIndexerDao, DbIdsRepository dbIdsRepository, TreeRootHolder treeRootHolder) { - this.resourceIndexerDao = resourceIndexerDao; + public IndexComponentsStep(ResourceIndexDao resourceIndexDao, DbIdsRepository dbIdsRepository, TreeRootHolder treeRootHolder) { + this.resourceIndexDao = resourceIndexDao; this.dbIdsRepository = dbIdsRepository; this.treeRootHolder = treeRootHolder; } @Override public void execute() { - resourceIndexerDao.indexProject(dbIdsRepository.getComponentId(treeRootHolder.getRoot())); + resourceIndexDao.indexProject(dbIdsRepository.getComponentId(treeRootHolder.getRoot())); } @Override diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistEventsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistEventsStep.java index ce318a5866b..a171a541f8e 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistEventsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistEventsStep.java @@ -33,7 +33,7 @@ import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.event.Event; import org.sonar.server.computation.event.EventRepository; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static com.google.common.collect.Iterables.transform; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistFileSourcesStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistFileSourcesStep.java index 922f19a2a18..8ad3021e97f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistFileSourcesStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistFileSourcesStep.java @@ -45,7 +45,7 @@ import org.sonar.server.computation.source.HighlightingLineReader; import org.sonar.server.computation.source.LineReader; import org.sonar.server.computation.source.ScmLineReader; import org.sonar.server.computation.source.SymbolsLineReader; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.util.CloseableIterator; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistIssuesStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistIssuesStep.java index ff2688091b7..b9de241635f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistIssuesStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistIssuesStep.java @@ -33,7 +33,7 @@ import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.server.computation.issue.IssueCache; import org.sonar.server.computation.issue.RuleRepository; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.util.CloseableIterator; public class PersistIssuesStep implements ComputationStep { diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistMeasuresStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistMeasuresStep.java index 3fa2b54ec1b..263517c5349 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistMeasuresStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistMeasuresStep.java @@ -41,7 +41,7 @@ import org.sonar.server.computation.measure.MeasureRepository; import org.sonar.server.computation.measure.MeasureToMeasureDto; import org.sonar.server.computation.metric.Metric; import org.sonar.server.computation.metric.MetricRepository; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static com.google.common.collect.FluentIterable.from; import static org.sonar.server.computation.component.ComponentVisitor.Order.PRE_ORDER; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistNumberOfDaysSinceLastCommitStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistNumberOfDaysSinceLastCommitStep.java index 113de32a2a2..e7404d50684 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistNumberOfDaysSinceLastCommitStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistNumberOfDaysSinceLastCommitStep.java @@ -35,7 +35,7 @@ import org.sonar.server.computation.component.DbIdsRepository; import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.metric.MetricRepository; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.source.index.SourceLineIndex; import static com.google.common.base.Objects.firstNonNull; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistProjectLinksStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistProjectLinksStep.java index c97fcf6a275..0fabd53203b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistProjectLinksStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistProjectLinksStep.java @@ -38,7 +38,7 @@ import org.sonar.server.computation.batch.BatchReportReader; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor; import org.sonar.server.computation.component.TreeRootHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static com.google.common.collect.Sets.newHashSet; import static org.sonar.server.computation.component.ComponentVisitor.Order.PRE_ORDER; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistSnapshotsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistSnapshotsStep.java index 97d18113767..3190f5e45fd 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistSnapshotsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistSnapshotsStep.java @@ -32,7 +32,7 @@ import org.sonar.server.computation.component.DbIdsRepository; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.period.Period; import org.sonar.server.computation.period.PeriodsHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; /** * Persist snapshots diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistTestsStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistTestsStep.java index 436e5ac8e38..62119d32ad6 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistTestsStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistTestsStep.java @@ -48,7 +48,7 @@ import org.sonar.server.computation.batch.BatchReportReader; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor; import org.sonar.server.computation.component.TreeRootHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.source.db.FileSourceDb.Test.TestStatus; import org.sonar.server.util.CloseableIterator; diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PurgeDatastoresStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PurgeDatastoresStep.java index e8cf0019ce5..c32a2c77ed4 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/PurgeDatastoresStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/PurgeDatastoresStep.java @@ -28,7 +28,7 @@ import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DbIdsRepository; import org.sonar.server.computation.component.ProjectSettingsRepository; import org.sonar.server.computation.component.TreeRootHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; public class PurgeDatastoresStep implements ComputationStep { diff --git a/server/sonar-server/src/main/java/org/sonar/server/computation/step/SwitchSnapshotStep.java b/server/sonar-server/src/main/java/org/sonar/server/computation/step/SwitchSnapshotStep.java index 6e74b092366..2152a24ff9a 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/computation/step/SwitchSnapshotStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/computation/step/SwitchSnapshotStep.java @@ -28,7 +28,7 @@ import org.sonar.db.component.SnapshotDao; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DbIdsRepository; import org.sonar.server.computation.component.TreeRootHolder; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static org.sonar.db.component.SnapshotDao.isLast; diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/DbClient.java b/server/sonar-server/src/main/java/org/sonar/server/db/DbClient.java index b89b0aa6d67..ae9bab0f56c 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/DbClient.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/DbClient.java @@ -19,45 +19,10 @@ */ package org.sonar.server.db; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.IdentityHashMap; import java.util.Map; -import javax.annotation.Nullable; import org.sonar.db.Dao; import org.sonar.db.Database; -import org.sonar.db.DbSession; import org.sonar.db.MyBatis; -import org.sonar.db.activity.ActivityDao; -import org.sonar.db.component.ComponentLinkDao; -import org.sonar.db.component.ResourceDao; -import org.sonar.db.component.ResourceIndexerDao; -import org.sonar.db.component.SnapshotDao; -import org.sonar.db.compute.AnalysisReportDao; -import org.sonar.db.dashboard.DashboardDao; -import org.sonar.db.dashboard.WidgetDao; -import org.sonar.db.dashboard.WidgetPropertyDao; -import org.sonar.db.debt.CharacteristicDao; -import org.sonar.db.event.EventDao; -import org.sonar.db.issue.ActionPlanDao; -import org.sonar.db.issue.IssueChangeDao; -import org.sonar.db.issue.IssueDao; -import org.sonar.db.issue.IssueFilterDao; -import org.sonar.db.loadedtemplate.LoadedTemplateDao; -import org.sonar.db.measure.MeasureDao; -import org.sonar.db.permission.PermissionTemplateDao; -import org.sonar.db.property.PropertiesDao; -import org.sonar.db.purge.PurgeDao; -import org.sonar.db.qualitygate.QualityGateConditionDao; -import org.sonar.db.qualityprofile.QualityProfileDao; -import org.sonar.db.source.FileSourceDao; -import org.sonar.db.user.AuthorDao; -import org.sonar.db.user.AuthorizationDao; -import org.sonar.db.user.GroupMembershipDao; -import org.sonar.db.user.RoleDao; -import org.sonar.db.user.UserGroupDao; import org.sonar.server.component.db.ComponentDao; import org.sonar.server.measure.custom.persistence.CustomMeasureDao; import org.sonar.server.metric.persistence.MetricDao; @@ -66,271 +31,60 @@ import org.sonar.server.rule.db.RuleDao; import org.sonar.server.user.db.GroupDao; import org.sonar.server.user.db.UserDao; -public class DbClient { - - private final Database db; - private final MyBatis myBatis; - private final RuleDao ruleDao; - private final ActiveRuleDao activeRuleDao; - private final QualityProfileDao qualityProfileDao; - private final CharacteristicDao debtCharacteristicDao; - private final LoadedTemplateDao loadedTemplateDao; - private final PropertiesDao propertiesDao; - private final ComponentDao componentDao; - private final SnapshotDao snapshotDao; - private final ResourceDao resourceDao; - private final MeasureDao measureDao; - private final MetricDao metricDao; - private final ActivityDao activityDao; - private final AuthorizationDao authorizationDao; - private final UserDao userDao; - private final GroupDao groupDao; - private final UserGroupDao userGroupDao; - private final GroupMembershipDao groupMembershipDao; - private final RoleDao roleDao; - private final PermissionTemplateDao permissionTemplateDao; - private final IssueDao issueDao; - private final IssueFilterDao issueFilterDao; - private final IssueChangeDao issueChangeDao; - private final ActionPlanDao actionPlanDao; - private final AnalysisReportDao analysisReportDao; - private final DashboardDao dashboardDao; - private final WidgetDao widgetDao; - private final WidgetPropertyDao widgetPropertyDao; - private final FileSourceDao fileSourceDao; - private final AuthorDao authorDao; - private final ResourceIndexerDao componentIndexDao; - private final ComponentLinkDao componentLinkDao; - private final EventDao eventDao; - private final PurgeDao purgeDao; - private final CustomMeasureDao customMeasureDao; - private final QualityGateConditionDao gateConditionDao; - - public DbClient(Database db, MyBatis myBatis, Dao... daos) { - this.db = db; - this.myBatis = myBatis; - - Map<Class, Dao> map = new IdentityHashMap<>(); - for (Dao dao : daos) { - map.put(dao.getClass(), dao); - } - ruleDao = getDao(map, RuleDao.class); - activeRuleDao = getDao(map, ActiveRuleDao.class); - debtCharacteristicDao = getDao(map, CharacteristicDao.class); - qualityProfileDao = getDao(map, QualityProfileDao.class); - loadedTemplateDao = getDao(map, LoadedTemplateDao.class); - propertiesDao = getDao(map, PropertiesDao.class); - componentDao = getDao(map, ComponentDao.class); - snapshotDao = getDao(map, SnapshotDao.class); - resourceDao = getDao(map, ResourceDao.class); - measureDao = getDao(map, MeasureDao.class); - metricDao = getDao(map, MetricDao.class); - customMeasureDao = getDao(map, CustomMeasureDao.class); - activityDao = getDao(map, ActivityDao.class); - authorizationDao = getDao(map, AuthorizationDao.class); - userDao = getDao(map, UserDao.class); - groupDao = getDao(map, GroupDao.class); - userGroupDao = getDao(map, UserGroupDao.class); - groupMembershipDao = getDao(map, GroupMembershipDao.class); - roleDao = getDao(map, RoleDao.class); - permissionTemplateDao = getDao(map, PermissionTemplateDao.class); - issueDao = getDao(map, IssueDao.class); - issueFilterDao = getDao(map, IssueFilterDao.class); - issueChangeDao = getDao(map, IssueChangeDao.class); - actionPlanDao = getDao(map, ActionPlanDao.class); - analysisReportDao = getDao(map, AnalysisReportDao.class); - dashboardDao = getDao(map, DashboardDao.class); - widgetDao = getDao(map, WidgetDao.class); - widgetPropertyDao = getDao(map, WidgetPropertyDao.class); - fileSourceDao = getDao(map, FileSourceDao.class); - authorDao = getDao(map, AuthorDao.class); - componentIndexDao = getDao(map, ResourceIndexerDao.class); - componentLinkDao = getDao(map, ComponentLinkDao.class); - eventDao = getDao(map, EventDao.class); - purgeDao = getDao(map, PurgeDao.class); - gateConditionDao = getDao(map, QualityGateConditionDao.class); - } - - public Database database() { - return db; - } +/** + * Should be replaced by {@link org.sonar.db.DbClient}, but some DAOs + * still depend on other sonar-server classes. + */ +public class DbClient extends org.sonar.db.DbClient { - public DbSession openSession(boolean batch) { - return myBatis.openSession(batch); - } + private ActiveRuleDao activeRuleDao; + private ComponentDao componentDao; + private CustomMeasureDao customMeasureDao; + private GroupDao groupDao; + private MetricDao metricDao; + private RuleDao ruleDao; + private UserDao userDao; - public void closeSession(@Nullable DbSession session) { - MyBatis.closeQuietly(session); + public DbClient(Database database, MyBatis myBatis, Dao... daos) { + super(database, myBatis, daos); } - public RuleDao ruleDao() { - return ruleDao; + @Override + protected void doOnLoad(Map<Class, Dao> daoByClass) { + this.activeRuleDao = (ActiveRuleDao) daoByClass.get(ActiveRuleDao.class); + this.componentDao = (ComponentDao) daoByClass.get(ComponentDao.class); + this.customMeasureDao = (CustomMeasureDao) daoByClass.get(CustomMeasureDao.class); + this.groupDao = (GroupDao) daoByClass.get(GroupDao.class); + this.metricDao = (MetricDao) daoByClass.get(MetricDao.class); + this.ruleDao = (RuleDao) daoByClass.get(RuleDao.class); + this.userDao = (UserDao) daoByClass.get(UserDao.class); } public ActiveRuleDao activeRuleDao() { return activeRuleDao; } - public IssueDao issueDao() { - return issueDao; - } - - public IssueFilterDao issueFilterDao() { - return issueFilterDao; - } - - public IssueChangeDao issueChangeDao() { - return issueChangeDao; - } - - public QualityProfileDao qualityProfileDao() { - return qualityProfileDao; - } - - public CharacteristicDao debtCharacteristicDao() { - return debtCharacteristicDao; - } - - public LoadedTemplateDao loadedTemplateDao() { - return loadedTemplateDao; - } - - public PropertiesDao propertiesDao() { - return propertiesDao; - } - public ComponentDao componentDao() { return componentDao; } - public SnapshotDao snapshotDao() { - return snapshotDao; - } - - public ResourceDao resourceDao() { - return resourceDao; - } - - public MeasureDao measureDao() { - return measureDao; - } - - public MetricDao metricDao() { - return metricDao; - } - public CustomMeasureDao customMeasureDao() { return customMeasureDao; } - public ActivityDao activityDao() { - return activityDao; - } - - public AuthorizationDao authorizationDao() { - return authorizationDao; - } - - public UserDao userDao() { - return userDao; - } - public GroupDao groupDao() { return groupDao; } - public UserGroupDao userGroupDao() { - return userGroupDao; - } - - public GroupMembershipDao groupMembershipDao() { - return groupMembershipDao; - } - - public RoleDao roleDao() { - return roleDao; - } - - public PermissionTemplateDao permissionTemplateDao() { - return permissionTemplateDao; - } - - public ActionPlanDao actionPlanDao() { - return actionPlanDao; - } - - public AnalysisReportDao analysisReportDao() { - return analysisReportDao; - } - - public DashboardDao dashboardDao() { - return dashboardDao; - } - - public WidgetDao widgetDao() { - return widgetDao; - } - - public WidgetPropertyDao widgetPropertyDao() { - return widgetPropertyDao; - } - - public FileSourceDao fileSourceDao() { - return fileSourceDao; - } - - public AuthorDao authorDao() { - return authorDao; - } - - public ResourceIndexerDao componentIndexDao() { - return componentIndexDao; - } - - public ComponentLinkDao componentLinkDao() { - return componentLinkDao; - } - - public EventDao eventDao() { - return eventDao; - } - - public PurgeDao purgeDao() { - return purgeDao; - } - - public QualityGateConditionDao gateConditionDao() { - return gateConditionDao; - } - - private <K> K getDao(Map<Class, Dao> map, Class<K> clazz) { - return (K) map.get(clazz); - } - - /** - * Create a PreparedStatement for SELECT requests with scrolling of results - */ - public final PreparedStatement newScrollingSelectStatement(Connection connection, String sql) { - int fetchSize = database().getDialect().getScrollDefaultFetchSize(); - return newScrollingSelectStatement(connection, sql, fetchSize); + public MetricDao metricDao() { + return metricDao; } - /** - * Create a PreparedStatement for SELECT requests with scrolling of results row by row (only one row - * in memory at a time) - */ - public final PreparedStatement newScrollingSingleRowSelectStatement(Connection connection, String sql) { - int fetchSize = database().getDialect().getScrollSingleRowFetchSize(); - return newScrollingSelectStatement(connection, sql, fetchSize); + public RuleDao ruleDao() { + return ruleDao; } - private PreparedStatement newScrollingSelectStatement(Connection connection, String sql, int fetchSize) { - try { - PreparedStatement stmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - stmt.setFetchSize(fetchSize); - return stmt; - } catch (SQLException e) { - throw new IllegalStateException("Fail to create SQL statement: " + sql, e); - } + public UserDao userDao() { + return userDao; } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrator.java b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrator.java index f033cc4d55c..cd77d7addcc 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/DatabaseMigrator.java @@ -20,18 +20,17 @@ package org.sonar.server.db.migrations; import com.google.common.annotations.VisibleForTesting; +import java.sql.Connection; import org.apache.commons.dbutils.DbUtils; import org.apache.ibatis.session.SqlSession; import org.picocontainer.Startable; -import org.sonar.api.server.ServerSide; import org.sonar.api.platform.ServerUpgradeStatus; +import org.sonar.api.server.ServerSide; import org.sonar.api.utils.log.Loggers; +import org.sonar.db.DbClient; import org.sonar.db.DdlUtils; -import org.sonar.server.db.DbClient; import org.sonar.server.plugins.ServerPluginRepository; -import java.sql.Connection; - /** * Restore schema by executing DDL scripts. Only H2 database is supported. * Other databases are created by Ruby on Rails migrations. @@ -70,13 +69,13 @@ public class DatabaseMigrator implements Startable { */ @VisibleForTesting boolean createDatabase() { - if (DdlUtils.supportsDialect(dbClient.database().getDialect().getId()) && serverUpgradeStatus.isFreshInstall()) { + if (DdlUtils.supportsDialect(dbClient.getDatabase().getDialect().getId()) && serverUpgradeStatus.isFreshInstall()) { Loggers.get(getClass()).info("Create database"); SqlSession session = dbClient.openSession(false); Connection connection = null; try { connection = session.getConnection(); - createSchema(connection, dbClient.database().getDialect().getId()); + createSchema(connection, dbClient.getDatabase().getDialect().getId()); return true; } finally { session.close(); diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ChangeLogMigrationStep.java b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ChangeLogMigrationStep.java index 6d6d82f9e52..fab24b6f7d8 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ChangeLogMigrationStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ChangeLogMigrationStep.java @@ -35,7 +35,7 @@ import org.sonar.db.qualityprofile.ActiveRuleKey; import org.sonar.core.rule.SeverityUtil; import org.sonar.server.activity.Activity; import org.sonar.db.activity.ActivityDao; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.db.migrations.MigrationStep; import org.sonar.server.qualityprofile.ActiveRuleChange; diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationStep.java b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationStep.java index 75a8f2ace7f..a9f13c6efa5 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationStep.java @@ -30,7 +30,7 @@ import org.sonar.db.DbSession; import org.sonar.db.version.v44.Migration44Mapper; import org.sonar.db.version.v44.ProfileMeasure; import org.sonar.db.version.v44.QProfileDto44; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.db.migrations.MigrationStep; /** diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/FeedQProfileDatesMigrationStep.java b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/FeedQProfileDatesMigrationStep.java index fd379ea8dc6..520528ddfd4 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/FeedQProfileDatesMigrationStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v44/FeedQProfileDatesMigrationStep.java @@ -28,7 +28,7 @@ import org.sonar.core.util.UtcDateUtils; import org.sonar.db.DbSession; import org.sonar.db.version.v44.Migration44Mapper; import org.sonar.db.version.v44.QProfileDto44; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.db.migrations.MigrationStep; /** diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v45/DeleteMeasuresOnDeletedProfilesMigrationStep.java b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v45/DeleteMeasuresOnDeletedProfilesMigrationStep.java index d32d51cee62..fa2efde1b1e 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v45/DeleteMeasuresOnDeletedProfilesMigrationStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v45/DeleteMeasuresOnDeletedProfilesMigrationStep.java @@ -22,7 +22,7 @@ package org.sonar.server.db.migrations.v45; import org.sonar.db.DbSession; import org.sonar.db.version.v44.Migration44Mapper; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.db.migrations.MigrationStep; import org.sonar.server.db.migrations.v44.ConvertProfileMeasuresMigrationStep; diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v451/AddMissingCustomRuleParametersMigrationStep.java b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v451/AddMissingCustomRuleParametersMigrationStep.java index 394c659fc6b..bb131ab5105 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v451/AddMissingCustomRuleParametersMigrationStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v451/AddMissingCustomRuleParametersMigrationStep.java @@ -34,7 +34,7 @@ import org.sonar.db.DbSession; import org.sonar.db.version.v45.Migration45Mapper; import org.sonar.db.version.v45.Rule; import org.sonar.db.version.v45.RuleParameter; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.db.migrations.MigrationStep; import org.sonar.core.util.ProgressLogger; diff --git a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v50/PopulateProjectsUuidColumnsMigrationStep.java b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v50/PopulateProjectsUuidColumnsMigrationStep.java index 63bbbdc43fb..f677eee9c8c 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v50/PopulateProjectsUuidColumnsMigrationStep.java +++ b/server/sonar-server/src/main/java/org/sonar/server/db/migrations/v50/PopulateProjectsUuidColumnsMigrationStep.java @@ -31,7 +31,7 @@ import org.sonar.api.utils.log.Loggers; import org.sonar.db.DbSession; import org.sonar.db.version.v50.Component; import org.sonar.db.version.v50.Migration50Mapper; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.db.migrations.MigrationStep; import org.sonar.core.util.ProgressLogger; diff --git a/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java b/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java index ac65f661afe..db850ec8440 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/duplication/ws/ShowAction.java @@ -34,7 +34,7 @@ import org.sonar.db.measure.MeasureDto; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.server.component.db.ComponentDao; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.exceptions.NotFoundException; import org.sonar.db.measure.MeasureDao; import org.sonar.server.user.UserSession; diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/IssueCommentService.java b/server/sonar-server/src/main/java/org/sonar/server/issue/IssueCommentService.java index faccdb814ed..d821248ac6b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/IssueCommentService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/IssueCommentService.java @@ -31,7 +31,7 @@ import org.sonar.api.utils.System2; import org.sonar.core.issue.IssueUpdater; import org.sonar.db.issue.IssueChangeDto; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/IssueQueryService.java b/server/sonar-server/src/main/java/org/sonar/server/issue/IssueQueryService.java index dfdfaa020c1..39f08218262 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/IssueQueryService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/IssueQueryService.java @@ -48,9 +48,9 @@ import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; -import org.sonar.db.component.ComponentDto; -import org.sonar.db.DbSession; import org.sonar.core.rule.RuleKeyFunctions; +import org.sonar.db.DbSession; +import org.sonar.db.component.ComponentDto; import org.sonar.server.component.ComponentService; import org.sonar.server.db.DbClient; import org.sonar.server.issue.filter.IssueFilterParameters; diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/IssueStorage.java b/server/sonar-server/src/main/java/org/sonar/server/issue/IssueStorage.java index b80bedf8f35..e3359c77db7 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/IssueStorage.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/IssueStorage.java @@ -32,6 +32,7 @@ import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.db.issue.IssueChangeDto; import org.sonar.db.issue.IssueChangeMapper; +import org.sonar.server.db.DbClient; import static com.google.common.collect.Lists.newArrayList; @@ -46,14 +47,18 @@ import static com.google.common.collect.Lists.newArrayList; */ public abstract class IssueStorage { - private final MyBatis mybatis; private final RuleFinder ruleFinder; + private final DbClient dbClient; - protected IssueStorage(MyBatis mybatis, RuleFinder ruleFinder) { - this.mybatis = mybatis; + protected IssueStorage(DbClient dbClient, RuleFinder ruleFinder) { + this.dbClient = dbClient; this.ruleFinder = ruleFinder; } + protected DbClient getDbClient() { + return dbClient; + } + public void save(DefaultIssue issue) { save(newArrayList(issue)); } @@ -63,7 +68,7 @@ public abstract class IssueStorage { } public void save(Iterable<DefaultIssue> issues) { - DbSession session = mybatis.openSession(true); + DbSession session = dbClient.openSession(true); try { doSave(session, issues); } finally { @@ -108,7 +113,7 @@ public abstract class IssueStorage { private void update(List<DefaultIssue> toBeUpdated, long now) { if (!toBeUpdated.isEmpty()) { - DbSession session = mybatis.openSession(false); + DbSession session = dbClient.openSession(false); try { IssueChangeMapper issueChangeMapper = session.getMapper(IssueChangeMapper.class); for (DefaultIssue issue : toBeUpdated) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java b/server/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java index 44d03667462..c9359612698 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/ServerIssueStorage.java @@ -19,13 +19,12 @@ */ package org.sonar.server.issue; +import org.sonar.api.rules.RuleFinder; import org.sonar.api.server.ServerSide; import org.sonar.core.issue.DefaultIssue; -import org.sonar.api.rules.RuleFinder; +import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueDto; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; import org.sonar.server.db.DbClient; import org.sonar.server.issue.index.IssueIndexer; @@ -35,12 +34,10 @@ import org.sonar.server.issue.index.IssueIndexer; @ServerSide public class ServerIssueStorage extends IssueStorage { - private final DbClient dbClient; private final IssueIndexer indexer; - public ServerIssueStorage(MyBatis mybatis, RuleFinder ruleFinder, DbClient dbClient, IssueIndexer indexer) { - super(mybatis, ruleFinder); - this.dbClient = dbClient; + public ServerIssueStorage(RuleFinder ruleFinder, DbClient dbClient, IssueIndexer indexer) { + super(dbClient, ruleFinder); this.indexer = indexer; } @@ -51,14 +48,14 @@ public class ServerIssueStorage extends IssueStorage { int ruleId = rule(issue).getId(); IssueDto dto = IssueDto.toDtoForServerInsert(issue, component, project, ruleId, now); - dbClient.issueDao().insert(session, dto); + getDbClient().issueDao().insert(session, dto); } @Override protected void doUpdate(DbSession session, long now, DefaultIssue issue) { IssueDto dto = IssueDto.toDtoForUpdate(issue, now); - dbClient.issueDao().update(session, dto); + getDbClient().issueDao().update(session, dto); } @Override @@ -67,10 +64,10 @@ public class ServerIssueStorage extends IssueStorage { } protected ComponentDto component(DbSession session, DefaultIssue issue) { - return dbClient.componentDao().selectByKey(session, issue.componentKey()); + return getDbClient().componentDao().selectByKey(session, issue.componentKey()); } protected ComponentDto project(DbSession session, DefaultIssue issue) { - return dbClient.componentDao().selectByKey(session, issue.projectKey()); + return getDbClient().componentDao().selectByKey(session, issue.projectKey()); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanService.java b/server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanService.java index 5b065874d05..be321bda86b 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanService.java @@ -44,7 +44,7 @@ import org.sonar.db.issue.ActionPlanDto; import org.sonar.db.issue.ActionPlanStatsDao; import org.sonar.db.issue.ActionPlanStatsDto; import org.sonar.db.issue.IssueDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.issue.IssueStorage; import org.sonar.server.user.UserSession; diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationDao.java b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationDao.java index f9c473153ea..89227b45e73 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationDao.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationDao.java @@ -21,17 +21,16 @@ package org.sonar.server.issue.index; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.apache.commons.dbutils.DbUtils; -import org.apache.commons.lang.StringUtils; -import org.sonar.server.db.DbClient; - -import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; +import org.apache.commons.dbutils.DbUtils; +import org.apache.commons.lang.StringUtils; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; /** * No streaming because of union of joins -> no need to use ResultSetIterator @@ -146,13 +145,13 @@ public class IssueAuthorizationDao { " AND group_roles.group_id IS NULL " + " ) project_authorization"; - Collection<Dto> selectAfterDate(DbClient dbClient, Connection connection, long afterDate) { + Collection<Dto> selectAfterDate(DbClient dbClient, DbSession session, long afterDate) { try { Map<String, Dto> dtosByProjectUuid = Maps.newHashMap(); PreparedStatement stmt = null; ResultSet rs = null; try { - stmt = createStatement(dbClient, connection, afterDate); + stmt = createStatement(dbClient, session, afterDate); rs = stmt.executeQuery(); while (rs.next()) { processRow(rs, dtosByProjectUuid); @@ -167,14 +166,14 @@ public class IssueAuthorizationDao { } } - private PreparedStatement createStatement(DbClient dbClient, Connection connection, long afterDate) throws SQLException { + private PreparedStatement createStatement(DbClient dbClient, DbSession session, long afterDate) throws SQLException { String sql; if (afterDate > 0L) { sql = StringUtils.replace(SQL_TEMPLATE, "{dateCondition}", " AND projects.authorization_updated_at>? "); } else { sql = StringUtils.replace(SQL_TEMPLATE, "{dateCondition}", ""); } - PreparedStatement stmt = dbClient.newScrollingSelectStatement(connection, sql); + PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql); if (afterDate > 0L) { for (int i = 1; i <= 4; i++) { stmt.setLong(i, afterDate); diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationIndexer.java b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationIndexer.java index 9428e77a6e1..93a3b6e7909 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationIndexer.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueAuthorizationIndexer.java @@ -25,7 +25,7 @@ import org.apache.commons.dbutils.DbUtils; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.update.UpdateRequest; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.es.BaseIndexer; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.EsClient; @@ -58,14 +58,12 @@ public class IssueAuthorizationIndexer extends BaseIndexer { final BulkIndexer bulk = new BulkIndexer(esClient, IssueIndexDefinition.INDEX); DbSession dbSession = dbClient.openSession(false); - Connection dbConnection = dbSession.getConnection(); try { IssueAuthorizationDao dao = new IssueAuthorizationDao(); - Collection<IssueAuthorizationDao.Dto> authorizations = dao.selectAfterDate(dbClient, dbConnection, lastUpdatedAt); + Collection<IssueAuthorizationDao.Dto> authorizations = dao.selectAfterDate(dbClient, dbSession, lastUpdatedAt); return doIndex(bulk, authorizations); } finally { - DbUtils.closeQuietly(dbConnection); dbSession.close(); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexer.java b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexer.java index e6889c1beb4..d7ff6d85eb0 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexer.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueIndexer.java @@ -19,20 +19,17 @@ */ package org.sonar.server.issue.index; -import org.apache.commons.dbutils.DbUtils; +import java.util.Iterator; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; +import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; import org.sonar.server.es.BaseIndexer; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.EsClient; -import java.sql.Connection; -import java.util.Iterator; - public class IssueIndexer extends BaseIndexer { private final DbClient dbClient; @@ -60,16 +57,13 @@ public class IssueIndexer extends BaseIndexer { private long doIndex(BulkIndexer bulk, long lastUpdatedAt) { DbSession dbSession = dbClient.openSession(false); - Connection dbConnection = dbSession.getConnection(); long maxDate; try { - IssueResultSetIterator rowIt = IssueResultSetIterator.create(dbClient, dbConnection, lastUpdatedAt); + IssueResultSetIterator rowIt = IssueResultSetIterator.create(dbClient, dbSession, lastUpdatedAt); maxDate = doIndex(bulk, rowIt); rowIt.close(); return maxDate; - } finally { - DbUtils.closeQuietly(dbConnection); dbSession.close(); } } @@ -97,7 +91,7 @@ public class IssueIndexer extends BaseIndexer { .setQuery(QueryBuilders.filteredQuery( QueryBuilders.matchAllQuery(), FilterBuilders.boolFilter().must(FilterBuilders.termsFilter(IssueIndexDefinition.FIELD_ISSUE_PROJECT_UUID, uuid)) - )); + )); bulk.addDeletion(search); bulk.stop(); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueResultSetIterator.java b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueResultSetIterator.java index 6876a231265..35f3f39c6b6 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueResultSetIterator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/index/IssueResultSetIterator.java @@ -27,7 +27,8 @@ import com.google.common.collect.Maps; import org.apache.commons.lang.StringUtils; import org.sonar.api.resources.Scopes; import org.sonar.api.rule.RuleKey; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; import org.sonar.db.ResultSetIterator; import org.sonar.server.db.migrations.SqlUtil; @@ -100,10 +101,10 @@ class IssueResultSetIterator extends ResultSetIterator<IssueDoc> { super(stmt); } - static IssueResultSetIterator create(DbClient dbClient, Connection connection, long afterDate) { + static IssueResultSetIterator create(DbClient dbClient, DbSession session, long afterDate) { try { String sql = afterDate > 0L ? SQL_AFTER_DATE : SQL_ALL; - PreparedStatement stmt = dbClient.newScrollingSelectStatement(connection, sql); + PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql); if (afterDate > 0L) { stmt.setLong(1, afterDate); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/issue/ws/SearchAction.java b/server/sonar-server/src/main/java/org/sonar/server/issue/ws/SearchAction.java index 3b1d7533bc1..d0958780989 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/issue/ws/SearchAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/issue/ws/SearchAction.java @@ -54,7 +54,7 @@ import org.sonar.db.component.ComponentDto; import org.sonar.core.issue.DefaultIssueComment; import org.sonar.db.DbSession; import org.sonar.server.component.ws.ComponentJsonWriter; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.es.Facets; import org.sonar.server.es.SearchOptions; import org.sonar.server.es.SearchResult; diff --git a/server/sonar-server/src/main/java/org/sonar/server/notification/NotificationService.java b/server/sonar-server/src/main/java/org/sonar/server/notification/NotificationService.java index 7cfa02572f4..185a54e54c4 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/notification/NotificationService.java +++ b/server/sonar-server/src/main/java/org/sonar/server/notification/NotificationService.java @@ -42,7 +42,7 @@ import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; @Properties({ @Property( diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/DatabaseMonitor.java b/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/DatabaseMonitor.java index f75952fc05f..fd6d4ae9a2f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/DatabaseMonitor.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/DatabaseMonitor.java @@ -25,7 +25,7 @@ import org.apache.commons.dbutils.DbUtils; import org.sonar.db.version.DatabaseVersion; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -122,7 +122,7 @@ public class DatabaseMonitor extends BaseMonitorMBean implements DatabaseMonitor } private BasicDataSource commonsDbcp() { - return (BasicDataSource) dbClient.database().getDataSource(); + return (BasicDataSource) dbClient.getDatabase().getDataSource(); } private void completeDbAttributes(Map<String, Object> attributes) { diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel1.java b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel1.java index 69ca28e06ca..621fa7848ec 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel1.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel1.java @@ -107,27 +107,23 @@ public class PlatformLevel1 extends PlatformLevel { // Elasticsearch EsSearchModule.class, - // users + // DAOs to be moved to sonar-db GroupDao.class, UserDao.class, + RuleDao.class, + ActiveRuleDao.class, + MetricDao.class, + CustomMeasureDao.class, + ComponentDao.class, // rules/qprofiles RuleNormalizer.class, ActiveRuleNormalizer.class, RuleIndex.class, ActiveRuleIndex.class, - RuleDao.class, - ActiveRuleDao.class, // issues - IssueIndex.class, - - // measures - MetricDao.class, - CustomMeasureDao.class, - - // components - ComponentDao.class); + IssueIndex.class); addAll(CorePropertyDefinitions.all()); add(MigrationStepModule.class); addAll(DaoUtils.getDaoClasses()); diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ws/StatusAction.java b/server/sonar-server/src/main/java/org/sonar/server/platform/ws/StatusAction.java index 6614dbd65d3..ad0f8cc1369 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ws/StatusAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/ws/StatusAction.java @@ -28,7 +28,7 @@ import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbSession; import org.sonar.db.IsAliveMapper; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.db.migrations.DatabaseMigration; import org.sonar.server.platform.Platform; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackuper.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackuper.java index 6f1a47a091f..afad30cfaab 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackuper.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackuper.java @@ -45,7 +45,7 @@ import org.sonar.api.server.ServerSide; import org.sonar.api.utils.text.XmlWriter; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.qualityprofile.index.ActiveRuleIndex; import org.sonar.server.search.IndexClient; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileComparison.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileComparison.java index 01ec23e3114..9fc6a666628 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileComparison.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileComparison.java @@ -28,7 +28,7 @@ import org.sonar.api.rule.RuleKey; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; import org.sonar.core.util.NonNullInputFunction; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import java.util.Collection; import java.util.Map; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java index 7e9f1abfb8a..22685e1414f 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileCopier.java @@ -26,7 +26,7 @@ import org.sonar.api.server.ServerSide; import org.sonar.api.utils.TempFolder; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import java.io.File; import java.io.IOException; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java index fd526765be7..f90be5b0e86 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileFactory.java @@ -20,25 +20,21 @@ package org.sonar.server.qualityprofile; import com.google.common.collect.Lists; +import java.util.Date; +import java.util.List; +import javax.annotation.CheckForNull; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; -import org.sonar.api.server.ServerSide; +import org.sonar.core.util.Slug; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; import org.sonar.server.db.DbClient; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.Verifications; -import org.sonar.core.util.Slug; - -import javax.annotation.CheckForNull; - -import java.util.Date; -import java.util.List; /** * Create, delete, rename and set as default profile. */ -@ServerSide public class QProfileFactory { private final DbClient db; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLoader.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLoader.java index 84f3e69b812..50ae9a3b777 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLoader.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLoader.java @@ -27,7 +27,7 @@ import org.sonar.api.rule.RuleStatus; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.ActiveRuleKey; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.qualityprofile.index.ActiveRuleIndex; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.rule.index.RuleQuery; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java index 784e88acf5f..5c0ad9b44dd 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileLookup.java @@ -28,7 +28,7 @@ import javax.annotation.Nonnull; import org.sonar.api.server.ServerSide; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import static com.google.common.collect.Lists.newArrayList; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectLookup.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectLookup.java index cea16eeaae1..76100b1d996 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectLookup.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectLookup.java @@ -32,7 +32,7 @@ import org.sonar.api.web.UserRole; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.user.UserSession; import com.google.common.collect.Lists; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java index ba6e90145ff..01d8a08ead5 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RegisterQualityProfiles.java @@ -38,7 +38,7 @@ import org.sonar.api.utils.log.Profiler; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; import org.sonar.db.loadedtemplate.LoadedTemplateDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.platform.PersistentSettings; import javax.annotation.Nullable; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/BackupAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/BackupAction.java index b7c9a97e464..ebeff3fa87d 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/BackupAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/BackupAction.java @@ -29,7 +29,7 @@ import org.sonar.api.server.ws.Response.Stream; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.plugins.MimeTypes; import org.sonar.server.qualityprofile.QProfileBackuper; import org.sonar.server.qualityprofile.QProfileFactory; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ChangeParentAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ChangeParentAction.java index e38514a5aa0..8e203c29970 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ChangeParentAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ChangeParentAction.java @@ -27,7 +27,7 @@ import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.qualityprofile.QProfileFactory; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.user.UserSession; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/CreateAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/CreateAction.java index dea943ce53c..07b626edc24 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/CreateAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/CreateAction.java @@ -29,7 +29,7 @@ import org.sonar.api.utils.text.JsonWriter; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.qualityprofile.QProfileExporters; import org.sonar.server.qualityprofile.QProfileFactory; import org.sonar.server.qualityprofile.QProfileName; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/DeleteAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/DeleteAction.java index 5577a2eca66..124e3626fc4 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/DeleteAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/DeleteAction.java @@ -26,7 +26,7 @@ import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewController; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.qualityprofile.QProfileFactory; import org.sonar.server.user.UserSession; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ExportAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ExportAction.java index 3a6516a2ceb..0c1b6093141 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ExportAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ExportAction.java @@ -31,7 +31,7 @@ import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.plugins.MimeTypes; import org.sonar.server.qualityprofile.QProfileBackuper; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/InheritanceAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/InheritanceAction.java index a1dcc3fadf8..19ce4a83a37 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/InheritanceAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/InheritanceAction.java @@ -28,7 +28,7 @@ import org.sonar.api.server.ws.WebService.NewController; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QualityProfileDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualityprofile.QProfile; import org.sonar.server.qualityprofile.QProfileFactory; diff --git a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ProjectsAction.java b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ProjectsAction.java index a9de9c71b14..534b9654772 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ProjectsAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ProjectsAction.java @@ -37,7 +37,7 @@ import org.sonar.api.web.UserRole; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.ProjectQprofileAssociationDto; import org.sonar.core.util.NonNullInputFunction; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; diff --git a/server/sonar-server/src/main/java/org/sonar/server/rule/RuleCreator.java b/server/sonar-server/src/main/java/org/sonar/server/rule/RuleCreator.java index c76757178d4..69dd9390cd0 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/rule/RuleCreator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/rule/RuleCreator.java @@ -22,10 +22,13 @@ package org.sonar.server.rule; import com.google.common.base.Splitter; import com.google.common.base.Strings; -import org.sonar.api.server.ServerSide; +import java.util.List; +import javax.annotation.CheckForNull; +import javax.annotation.Nullable; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; +import org.sonar.api.server.ServerSide; import org.sonar.api.server.rule.RuleParamType; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDto; @@ -38,11 +41,6 @@ import org.sonar.server.exceptions.Message; import org.sonar.server.rule.index.RuleDoc; import org.sonar.server.util.TypeValidations; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -import java.util.List; - import static com.google.common.collect.Lists.newArrayList; @ServerSide diff --git a/server/sonar-server/src/main/java/org/sonar/server/search/IndexDefinition.java b/server/sonar-server/src/main/java/org/sonar/server/search/IndexDefinition.java index ffafa74a18a..9d8bf8d8311 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/search/IndexDefinition.java +++ b/server/sonar-server/src/main/java/org/sonar/server/search/IndexDefinition.java @@ -39,7 +39,6 @@ public class IndexDefinition { public static final IndexDefinition RULE = new IndexDefinition("rules", "rule"); public static final IndexDefinition ACTIVE_RULE = new IndexDefinition("rules", "activeRule"); - public static final IndexDefinition ISSUES = new IndexDefinition("issues", "issue"); // Only used for test static final IndexDefinition TEST = new IndexDefinition("test", "test"); diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/index/FileSourcesUpdaterHelper.java b/server/sonar-server/src/main/java/org/sonar/server/source/index/FileSourcesUpdaterHelper.java index 698ec88a864..4ebd56a7564 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/index/FileSourcesUpdaterHelper.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/index/FileSourcesUpdaterHelper.java @@ -28,7 +28,8 @@ import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.elasticsearch.action.update.UpdateRequest; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; public class FileSourcesUpdaterHelper { @@ -48,11 +49,11 @@ public class FileSourcesUpdaterHelper { // only static stuff } - public static PreparedStatement preparedStatementToSelectFileSources(DbClient dbClient, Connection connection, String dataType, long afterDate, @Nullable String projectUuid) + public static PreparedStatement preparedStatementToSelectFileSources(DbClient dbClient, DbSession session, String dataType, long afterDate, @Nullable String projectUuid) throws SQLException { String sql = createSQL(dataType, afterDate, projectUuid); // rows are big, so they are scrolled once at a time (one row in memory at a time) - PreparedStatement stmt = dbClient.newScrollingSingleRowSelectStatement(connection, sql); + PreparedStatement stmt = dbClient.getMyBatis().newScrollingSingleRowSelectStatement(session, sql); int index = 1; if (afterDate > 0L) { stmt.setLong(index, afterDate); diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineIndexer.java b/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineIndexer.java index 48dfb9ce7dc..52864517d15 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineIndexer.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineIndexer.java @@ -19,21 +19,18 @@ */ package org.sonar.server.source.index; +import java.util.Iterator; +import javax.annotation.Nullable; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; +import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; import org.sonar.server.es.BaseIndexer; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.EsClient; -import javax.annotation.Nullable; - -import java.sql.Connection; -import java.util.Iterator; - import static org.sonar.server.source.index.SourceLineIndexDefinition.FIELD_FILE_UUID; import static org.sonar.server.source.index.SourceLineIndexDefinition.FIELD_PROJECT_UUID; @@ -50,7 +47,7 @@ public class SourceLineIndexer extends BaseIndexer { this.dbClient = dbClient; } - public void index(final String projectUuid){ + public void index(final String projectUuid) { super.index(new IndexerTask() { @Override public long index(long lastUpdatedAt) { @@ -69,9 +66,8 @@ public class SourceLineIndexer extends BaseIndexer { bulk.setLarge(lastUpdatedAt == 0L); DbSession dbSession = dbClient.openSession(false); - Connection dbConnection = dbSession.getConnection(); try { - SourceLineResultSetIterator rowIt = SourceLineResultSetIterator.create(dbClient, dbConnection, lastUpdatedAt, projectUuid); + SourceLineResultSetIterator rowIt = SourceLineResultSetIterator.create(dbClient, dbSession, lastUpdatedAt, projectUuid); long maxUpdatedAt = doIndex(bulk, rowIt); rowIt.close(); return maxUpdatedAt; @@ -118,7 +114,7 @@ public class SourceLineIndexer extends BaseIndexer { .must(FilterBuilders.termFilter(FIELD_FILE_UUID, fileRow.getFileUuid()).cache(false)) .must(FilterBuilders.rangeFilter(SourceLineIndexDefinition.FIELD_LINE).gt(numberOfLines).cache(false)) .cache(false) - )); + )); bulk.addDeletion(searchRequest); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineResultSetIterator.java b/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineResultSetIterator.java index b899a5fa0b7..dda282ef135 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineResultSetIterator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/source/index/SourceLineResultSetIterator.java @@ -21,8 +21,9 @@ package org.sonar.server.source.index; import org.elasticsearch.action.update.UpdateRequest; import org.sonar.api.utils.text.JsonWriter; +import org.sonar.db.DbSession; import org.sonar.db.source.FileSourceDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.db.ResultSetIterator; import org.sonar.server.es.EsUtils; import org.sonar.server.source.db.FileSourceDb; @@ -46,9 +47,9 @@ import static org.sonar.server.source.index.FileSourcesUpdaterHelper.Row; */ public class SourceLineResultSetIterator extends ResultSetIterator<FileSourcesUpdaterHelper.Row> { - public static SourceLineResultSetIterator create(DbClient dbClient, Connection connection, long afterDate, @Nullable String projectUuid) { + public static SourceLineResultSetIterator create(DbClient dbClient, DbSession session, long afterDate, @Nullable String projectUuid) { try { - return new SourceLineResultSetIterator(FileSourcesUpdaterHelper.preparedStatementToSelectFileSources(dbClient, connection, FileSourceDto.Type.SOURCE, afterDate, + return new SourceLineResultSetIterator(FileSourcesUpdaterHelper.preparedStatementToSelectFileSources(dbClient, session, FileSourceDto.Type.SOURCE, afterDate, projectUuid)); } catch (SQLException e) { throw new IllegalStateException("Fail to prepare SQL request to select all file sources", e); diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java index 27b31a4d354..383d349e624 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/RegisterMetrics.java @@ -32,9 +32,9 @@ import org.sonar.api.measures.Metrics; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; -import org.sonar.db.metric.MetricDto; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; +import org.sonar.db.metric.MetricDto; import org.sonar.server.db.DbClient; import static com.google.common.collect.FluentIterable.from; diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/RenameIssueWidgets.java b/server/sonar-server/src/main/java/org/sonar/server/startup/RenameIssueWidgets.java index bce54a6a15e..0862b23e707 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/RenameIssueWidgets.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/RenameIssueWidgets.java @@ -32,7 +32,7 @@ import org.sonar.db.issue.IssueFilterDto; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; import org.sonar.db.loadedtemplate.LoadedTemplateDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.issue.filter.RegisterIssueFilters; import java.util.Date; diff --git a/server/sonar-server/src/main/java/org/sonar/server/test/index/TestIndexer.java b/server/sonar-server/src/main/java/org/sonar/server/test/index/TestIndexer.java index 1d7ce182aef..69476a22fed 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/test/index/TestIndexer.java +++ b/server/sonar-server/src/main/java/org/sonar/server/test/index/TestIndexer.java @@ -20,23 +20,24 @@ package org.sonar.server.test.index; +import java.util.Iterator; +import javax.annotation.Nullable; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders; +import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; import org.sonar.server.es.BaseIndexer; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.EsClient; import org.sonar.server.source.index.FileSourcesUpdaterHelper; -import javax.annotation.Nullable; -import java.sql.Connection; -import java.util.Iterator; - import static org.sonar.server.source.index.SourceLineIndexDefinition.FIELD_PROJECT_UUID; -import static org.sonar.server.test.index.TestIndexDefinition.*; +import static org.sonar.server.test.index.TestIndexDefinition.FIELD_FILE_UUID; +import static org.sonar.server.test.index.TestIndexDefinition.FIELD_UPDATED_AT; +import static org.sonar.server.test.index.TestIndexDefinition.INDEX; +import static org.sonar.server.test.index.TestIndexDefinition.TYPE; /** * Add to Elasticsearch index {@link TestIndexDefinition} the rows of @@ -76,9 +77,8 @@ public class TestIndexer extends BaseIndexer { bulk.setLarge(lastUpdatedAt == 0L); DbSession dbSession = dbClient.openSession(false); - Connection dbConnection = dbSession.getConnection(); try { - TestResultSetIterator rowIt = TestResultSetIterator.create(dbClient, dbConnection, lastUpdatedAt, projectUuid); + TestResultSetIterator rowIt = TestResultSetIterator.create(dbClient, dbSession, lastUpdatedAt, projectUuid); long maxUpdatedAt = doIndex(bulk, rowIt); rowIt.close(); return maxUpdatedAt; diff --git a/server/sonar-server/src/main/java/org/sonar/server/test/index/TestResultSetIterator.java b/server/sonar-server/src/main/java/org/sonar/server/test/index/TestResultSetIterator.java index 61af8323129..67e9bb72e6a 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/test/index/TestResultSetIterator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/test/index/TestResultSetIterator.java @@ -22,8 +22,9 @@ package org.sonar.server.test.index; import org.elasticsearch.action.update.UpdateRequest; import org.sonar.api.utils.text.JsonWriter; +import org.sonar.db.DbSession; import org.sonar.db.source.FileSourceDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.db.ResultSetIterator; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.source.index.FileSourcesUpdaterHelper; @@ -61,9 +62,9 @@ import static org.sonar.server.test.index.TestIndexDefinition.TYPE; */ public class TestResultSetIterator extends ResultSetIterator<Row> { - public static TestResultSetIterator create(DbClient dbClient, Connection connection, long afterDate, @Nullable String projectUuid) { + public static TestResultSetIterator create(DbClient dbClient, DbSession session, long afterDate, @Nullable String projectUuid) { try { - return new TestResultSetIterator(FileSourcesUpdaterHelper.preparedStatementToSelectFileSources(dbClient, connection, FileSourceDto.Type.TEST, afterDate, projectUuid)); + return new TestResultSetIterator(FileSourcesUpdaterHelper.preparedStatementToSelectFileSources(dbClient, session, FileSourceDto.Type.TEST, afterDate, projectUuid)); } catch (SQLException e) { throw new IllegalStateException("Fail to prepare SQL request to select all tests", e); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java b/server/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java index 8cacd9ef64b..ec9acf8f431 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java +++ b/server/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java @@ -46,7 +46,7 @@ import org.sonar.db.version.DatabaseVersion; import org.sonar.core.platform.ComponentContainer; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.core.timemachine.Periods; import org.sonar.process.ProcessProperties; import org.sonar.server.component.ComponentCleanerService; @@ -304,11 +304,11 @@ public final class JRubyFacade { } public void indexProjects() { - get(ResourceIndexerDao.class).indexProjects(); + get(ResourceIndexDao.class).indexProjects(); } public void indexResource(long resourceId) { - get(ResourceIndexerDao.class).indexResource(resourceId); + get(ResourceIndexDao.class).indexResource(resourceId); } /* diff --git a/server/sonar-server/src/main/java/org/sonar/server/user/index/UserIndexer.java b/server/sonar-server/src/main/java/org/sonar/server/user/index/UserIndexer.java index 8dc99faeff7..11db2d50caa 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/user/index/UserIndexer.java +++ b/server/sonar-server/src/main/java/org/sonar/server/user/index/UserIndexer.java @@ -20,12 +20,10 @@ package org.sonar.server.user.index; -import java.sql.Connection; import java.util.Iterator; -import org.apache.commons.dbutils.DbUtils; import org.elasticsearch.action.update.UpdateRequest; +import org.sonar.db.DbClient; import org.sonar.db.DbSession; -import org.sonar.server.db.DbClient; import org.sonar.server.es.BaseIndexer; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.EsClient; @@ -45,15 +43,12 @@ public class UserIndexer extends BaseIndexer { bulk.setLarge(lastUpdatedAt == 0L); DbSession dbSession = dbClient.openSession(false); - Connection dbConnection = dbSession.getConnection(); try { - UserResultSetIterator rowIt = UserResultSetIterator.create(dbClient, dbConnection, lastUpdatedAt); + UserResultSetIterator rowIt = UserResultSetIterator.create(dbClient, dbSession, lastUpdatedAt); long maxUpdatedAt = doIndex(bulk, rowIt); rowIt.close(); return maxUpdatedAt; - } finally { - DbUtils.closeQuietly(dbConnection); dbSession.close(); } } diff --git a/server/sonar-server/src/main/java/org/sonar/server/user/index/UserResultSetIterator.java b/server/sonar-server/src/main/java/org/sonar/server/user/index/UserResultSetIterator.java index 22d1111613b..ce94f359865 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/user/index/UserResultSetIterator.java +++ b/server/sonar-server/src/main/java/org/sonar/server/user/index/UserResultSetIterator.java @@ -21,8 +21,9 @@ package org.sonar.server.user.index; import com.google.common.collect.Maps; import org.apache.commons.lang.StringUtils; +import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.db.ResultSetIterator; import java.sql.Connection; @@ -50,10 +51,10 @@ class UserResultSetIterator extends ResultSetIterator<UserDoc> { private static final String SQL_AFTER_DATE = SQL_ALL + " where u.updated_at>?"; - static UserResultSetIterator create(DbClient dbClient, Connection connection, long afterDate) { + static UserResultSetIterator create(DbClient dbClient, DbSession session, long afterDate) { try { String sql = afterDate > 0L ? SQL_AFTER_DATE : SQL_ALL; - PreparedStatement stmt = dbClient.newScrollingSelectStatement(connection, sql); + PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql); if (afterDate > 0L) { stmt.setLong(1, afterDate); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/user/ws/DeactivateAction.java b/server/sonar-server/src/main/java/org/sonar/server/user/ws/DeactivateAction.java index 2f6f5af199b..c62f4742e13 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/user/ws/DeactivateAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/user/ws/DeactivateAction.java @@ -31,7 +31,7 @@ import org.sonar.api.utils.text.JsonWriter; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; diff --git a/server/sonar-server/src/main/java/org/sonar/server/user/ws/SearchAction.java b/server/sonar-server/src/main/java/org/sonar/server/user/ws/SearchAction.java index bfb41852ae8..f5bbe77ccd0 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/user/ws/SearchAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/user/ws/SearchAction.java @@ -35,7 +35,7 @@ import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.es.SearchOptions; import org.sonar.server.es.SearchResult; import org.sonar.server.user.index.UserDoc; diff --git a/server/sonar-server/src/main/java/org/sonar/server/user/ws/UpdateAction.java b/server/sonar-server/src/main/java/org/sonar/server/user/ws/UpdateAction.java index 3836b33390a..8ad3ffa1305 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/user/ws/UpdateAction.java +++ b/server/sonar-server/src/main/java/org/sonar/server/user/ws/UpdateAction.java @@ -30,7 +30,7 @@ import org.sonar.api.utils.text.JsonWriter; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; -import org.sonar.server.db.DbClient; +import org.sonar.db.DbClient; import org.sonar.server.user.UpdateUser; import org.sonar.server.user.UserSession; import org.sonar.server.user.UserUpdater; diff --git a/server/sonar-server/src/test/java/org/sonar/server/activity/index/ActivityResultSetIteratorTest.java b/server/sonar-server/src/test/java/org/sonar/server/activity/index/ActivityResultSetIteratorTest.java index 0ece66fcd57..184c841177d 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/activity/index/ActivityResultSetIteratorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/activity/index/ActivityResultSetIteratorTest.java @@ -22,12 +22,14 @@ package org.sonar.server.activity.index; import org.apache.commons.dbutils.DbUtils; import org.assertj.core.data.MapEntry; import org.elasticsearch.action.update.UpdateRequest; +import org.jruby.RubyProcess; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.sonar.api.utils.DateUtils; +import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.db.DbClient; import org.sonar.test.DbTests; @@ -41,21 +43,11 @@ import static org.assertj.core.api.Assertions.assertThat; public class ActivityResultSetIteratorTest { @ClassRule - public static DbTester dbTester = new DbTester(); - - DbClient client; - Connection connection; + public static DbTester dbTester = DbTester.create(System2.INSTANCE); @Before public void setUp() throws Exception { dbTester.truncateTables(); - client = new DbClient(dbTester.database(), dbTester.myBatis()); - connection = dbTester.openConnection(); - } - - @After - public void tearDown() { - DbUtils.closeQuietly(connection); } /** @@ -64,7 +56,7 @@ public class ActivityResultSetIteratorTest { @Test public void traverse() { dbTester.prepareDbUnit(getClass(), "traverse.xml"); - ActivityResultSetIterator it = ActivityResultSetIterator.create(client, connection, 0L); + ActivityResultSetIterator it = ActivityResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L); assertThat(it.hasNext()).isTrue(); UpdateRequest request = it.next(); @@ -86,7 +78,7 @@ public class ActivityResultSetIteratorTest { @Test public void traverse_after_date() { dbTester.prepareDbUnit(getClass(), "traverse.xml"); - ActivityResultSetIterator it = ActivityResultSetIterator.create(client, connection, DateUtils.parseDate("2014-12-01").getTime()); + ActivityResultSetIterator it = ActivityResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), DateUtils.parseDate("2014-12-01").getTime()); assertThat(it.hasNext()).isTrue(); UpdateRequest request = it.next(); @@ -103,7 +95,7 @@ public class ActivityResultSetIteratorTest { @Test public void nothing_to_traverse() { dbTester.prepareDbUnit(getClass(), "traverse.xml"); - ActivityResultSetIterator it = ActivityResultSetIterator.create(client, connection, DateUtils.parseDate("2030-01-01").getTime()); + ActivityResultSetIterator it = ActivityResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), DateUtils.parseDate("2030-01-01").getTime()); assertThat(it.hasNext()).isFalse(); it.close(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/ComponentServiceTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/ComponentServiceTest.java index ae711a2e0d1..79a6a91e3d8 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/ComponentServiceTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/ComponentServiceTest.java @@ -38,7 +38,7 @@ import org.sonar.db.component.ComponentDto; import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.DbSession; import org.sonar.db.DbTester; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.db.component.ResourceKeyUpdaterDao; import org.sonar.server.component.db.ComponentDao; import org.sonar.server.db.DbClient; @@ -75,7 +75,7 @@ public class ComponentServiceTest { when(i18n.message(Locale.getDefault(), "qualifier.TRK", "Project")).thenReturn("Project"); - service = new ComponentService(dbClient, new ResourceKeyUpdaterDao(dbTester.myBatis()), i18n, new ResourceIndexerDao(dbTester.myBatis(), mock(System2.class)), + service = new ComponentService(dbClient, new ResourceKeyUpdaterDao(dbTester.myBatis()), i18n, new ResourceIndexDao(dbTester.myBatis(), mock(System2.class)), userSessionRule, System2.INSTANCE); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java index 1d5069f921b..9682255f18b 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/component/ws/SearchActionTest.java @@ -29,7 +29,7 @@ import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbTester; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.db.user.AuthorizationDao; import org.sonar.server.component.db.ComponentDao; import org.sonar.server.db.DbClient; @@ -55,7 +55,7 @@ public class SearchActionTest { public void setUp() { dbTester.truncateTables(); DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), - new ComponentDao(), new AuthorizationDao(dbTester.myBatis()), new ResourceIndexerDao(dbTester.myBatis(), mock(System2.class)) + new ComponentDao(), new AuthorizationDao(dbTester.myBatis()), new ResourceIndexDao(dbTester.myBatis(), mock(System2.class)) ); tester = new WsTester(new ComponentsWs(mock(AppAction.class), new SearchAction(dbClient, userSessionRule))); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexComponentsStepTest.java b/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexComponentsStepTest.java index f5fe742e7ca..30a65aea399 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexComponentsStepTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexComponentsStepTest.java @@ -23,7 +23,7 @@ package org.sonar.server.computation.step; import java.io.IOException; import org.junit.Rule; import org.junit.Test; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.server.computation.batch.BatchReportReaderRule; import org.sonar.server.computation.batch.TreeRootHolderRule; import org.sonar.server.computation.component.Component; @@ -43,9 +43,9 @@ public class IndexComponentsStepTest extends BaseStepTest { @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); - ResourceIndexerDao resourceIndexerDao = mock(ResourceIndexerDao.class); + ResourceIndexDao resourceIndexDao = mock(ResourceIndexDao.class); DbIdsRepository dbIdsRepository = new DbIdsRepository(); - IndexComponentsStep sut = new IndexComponentsStep(resourceIndexerDao, dbIdsRepository, treeRootHolder); + IndexComponentsStep sut = new IndexComponentsStep(resourceIndexDao, dbIdsRepository, treeRootHolder); @Test public void call_indexProject_of_dao() throws IOException { @@ -55,7 +55,7 @@ public class IndexComponentsStepTest extends BaseStepTest { sut.execute(); - verify(resourceIndexerDao).indexProject(123L); + verify(resourceIndexDao).indexProject(123L); } @Override diff --git a/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexSourceLinesStepTest.java b/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexSourceLinesStepTest.java index 61384933f6b..35f57a1b8bb 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexSourceLinesStepTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexSourceLinesStepTest.java @@ -28,13 +28,13 @@ import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Settings; import org.sonar.db.DbTester; +import org.sonar.db.source.FileSourceDao; import org.sonar.server.computation.batch.TreeRootHolderRule; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DumbComponent; import org.sonar.server.db.DbClient; import org.sonar.server.es.EsTester; -import org.sonar.db.source.FileSourceDao; -import org.sonar.server.source.db.FileSourceTesting; +import org.sonar.server.source.index.FileSourceTesting; import org.sonar.server.source.index.SourceLineDoc; import org.sonar.server.source.index.SourceLineIndexDefinition; import org.sonar.server.source.index.SourceLineIndexer; @@ -69,9 +69,9 @@ public class IndexSourceLinesStepTest extends BaseStepTest { @Test public void index_source() throws Exception { dbTester.prepareDbUnit(getClass(), "index_source.xml"); - Connection connection = dbTester.openConnection(); - FileSourceTesting.updateDataColumn(connection, "FILE1_UUID", FileSourceTesting.newRandomData(1).build()); - connection.close(); + try (Connection connection = dbTester.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "FILE1_UUID", FileSourceTesting.newRandomData(1).build()); + } treeRootHolder.setRoot(DumbComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey("PROJECT_KEY").build()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexTestsStepTest.java b/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexTestsStepTest.java index a4b020c034a..31653fafac3 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexTestsStepTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/computation/step/IndexTestsStepTest.java @@ -20,7 +20,6 @@ package org.sonar.server.computation.step; -import java.sql.Connection; import java.util.List; import org.elasticsearch.search.SearchHit; import org.junit.Before; @@ -28,13 +27,14 @@ import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Settings; +import org.sonar.api.utils.System2; import org.sonar.db.DbTester; +import org.sonar.db.source.FileSourceDao; import org.sonar.server.computation.batch.TreeRootHolderRule; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DumbComponent; import org.sonar.server.db.DbClient; import org.sonar.server.es.EsTester; -import org.sonar.db.source.FileSourceDao; import org.sonar.server.test.db.TestTesting; import org.sonar.server.test.index.TestDoc; import org.sonar.server.test.index.TestIndexDefinition; @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class IndexTestsStepTest extends BaseStepTest { @ClassRule - public static DbTester dbTester = new DbTester(); + public static DbTester dbTester = DbTester.create(System2.INSTANCE); @ClassRule public static EsTester esTester = new EsTester().addDefinitions(new TestIndexDefinition(new Settings())); @@ -71,9 +71,7 @@ public class IndexTestsStepTest extends BaseStepTest { @Test public void index_test() throws Exception { dbTester.prepareDbUnit(getClass(), "index_source.xml"); - Connection connection = dbTester.openConnection(); - TestTesting.updateDataColumn(connection, "FILE1_UUID", TestTesting.newRandomTests(1)); - connection.close(); + TestTesting.updateDataColumn(dbTester.getSession(), "FILE1_UUID", TestTesting.newRandomTests(1)); treeRootHolder.setRoot(DumbComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey("PROJECT_KEY").build()); diff --git a/server/sonar-server/src/test/java/org/sonar/server/db/DbClientTest.java b/server/sonar-server/src/test/java/org/sonar/server/db/DbClientTest.java index 8c9ae2e8e45..c1726c38da5 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/db/DbClientTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/db/DbClientTest.java @@ -40,7 +40,7 @@ public class DbClientTest { public DbTester db = new DbTester(); @Test - public void facade() throws Exception { + public void get_daos() throws Exception { MyBatis myBatis = db.myBatis(); RuleDao ruleDao = new RuleDao(System2.INSTANCE); QualityProfileDao qualityProfileDao = new QualityProfileDao(myBatis, System2.INSTANCE); @@ -48,7 +48,7 @@ public class DbClientTest { DbClient client = new DbClient(db.database(), myBatis, ruleDao, activeRuleDao, qualityProfileDao); - assertThat(client.database()).isSameAs(db.database()); + assertThat(client.getDatabase()).isSameAs(db.database()); DbSession dbSession = client.openSession(true); assertThat(dbSession).isNotNull(); assertThat(dbSession.getConnection().isClosed()).isFalse(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/db/migrations/DatabaseMigratorTest.java b/server/sonar-server/src/test/java/org/sonar/server/db/migrations/DatabaseMigratorTest.java index 15e6e013aba..9575d534eee 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/db/migrations/DatabaseMigratorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/db/migrations/DatabaseMigratorTest.java @@ -58,7 +58,7 @@ public class DatabaseMigratorTest extends AbstractDaoTestCase { @Test public void should_support_only_creation_of_h2_database() { - when(dbClient.database().getDialect()).thenReturn(new MySql()); + when(dbClient.getDatabase().getDialect()).thenReturn(new MySql()); assertThat(migrator.createDatabase()).isFalse(); verify(dbClient, never()).openSession(anyBoolean()); @@ -82,7 +82,7 @@ public class DatabaseMigratorTest extends AbstractDaoTestCase { @Test public void should_create_schema_on_h2() { Dialect supportedDialect = new H2(); - when(dbClient.database().getDialect()).thenReturn(supportedDialect); + when(dbClient.getDatabase().getDialect()).thenReturn(supportedDialect); Connection connection = mock(Connection.class); DbSession session = mock(DbSession.class); when(session.getConnection()).thenReturn(connection); diff --git a/server/sonar-server/src/test/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationTest.java b/server/sonar-server/src/test/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationTest.java index 7b83ac06d5c..e54d28ba0b5 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/db/migrations/v44/ConvertProfileMeasuresMigrationTest.java @@ -20,6 +20,9 @@ package org.sonar.server.db.migrations.v44; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; @@ -27,10 +30,6 @@ import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.db.DbClient; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; - import static org.assertj.core.api.Assertions.assertThat; public class ConvertProfileMeasuresMigrationTest { @@ -100,16 +99,16 @@ public class ConvertProfileMeasuresMigrationTest { migration.execute(); - Connection connection = db.openConnection(); - Statement stmt = connection.createStatement(); - ResultSet rs = stmt.executeQuery("select * from project_measures where id=2"); - try { - // measure is deleted - assertThat(rs.next()).isFalse(); - } finally { - rs.close(); - stmt.close(); - connection.close(); + try (Connection connection = db.openConnection()) { + Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("select * from project_measures where id=2"); + try { + // measure is deleted + assertThat(rs.next()).isFalse(); + } finally { + rs.close(); + stmt.close(); + } } } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/IssueStorageTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/IssueStorageTest.java index 1ec06c32961..c6c9cbdfd91 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/IssueStorageTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/IssueStorageTest.java @@ -35,10 +35,10 @@ import org.sonar.core.issue.DefaultIssueComment; import org.sonar.core.issue.IssueChangeContext; import org.sonar.db.AbstractDaoTestCase; import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueDto; import org.sonar.db.issue.IssueMapper; +import org.sonar.server.db.DbClient; public class IssueStorageTest extends AbstractDaoTestCase { @@ -58,7 +58,8 @@ public class IssueStorageTest extends AbstractDaoTestCase { @Test public void batch_insert_new_issues() { - FakeBatchSaver saver = new FakeBatchSaver(getMyBatis(), new FakeRuleFinder()); + DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis()); + FakeBatchSaver saver = new FakeBatchSaver(dbClient, new FakeRuleFinder()); DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment"); // override generated key @@ -93,7 +94,8 @@ public class IssueStorageTest extends AbstractDaoTestCase { @Test public void batch_insert_new_issues_with_session() { - FakeBatchSaver saver = new FakeBatchSaver(getMyBatis(), new FakeRuleFinder()); + DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis()); + FakeBatchSaver saver = new FakeBatchSaver(dbClient, new FakeRuleFinder()); DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment"); // override generated key @@ -131,7 +133,8 @@ public class IssueStorageTest extends AbstractDaoTestCase { public void server_insert_new_issues_with_session() { ComponentDto project = new ComponentDto().setId(10L).setUuid("uuid-10"); ComponentDto component = new ComponentDto().setId(100L).setUuid("uuid-100"); - FakeServerSaver saver = new FakeServerSaver(getMyBatis(), new FakeRuleFinder(), component, project); + DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis()); + FakeServerSaver saver = new FakeServerSaver(dbClient, new FakeRuleFinder(), component, project); DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment"); // override generated key @@ -169,7 +172,8 @@ public class IssueStorageTest extends AbstractDaoTestCase { public void batch_update_issues() { setupData("should_update_issues"); - FakeBatchSaver saver = new FakeBatchSaver(getMyBatis(), new FakeRuleFinder()); + DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis()); + FakeBatchSaver saver = new FakeBatchSaver(dbClient, new FakeRuleFinder()); DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment"); // override generated key @@ -215,7 +219,8 @@ public class IssueStorageTest extends AbstractDaoTestCase { ComponentDto project = new ComponentDto().setId(10L).setUuid("whatever-uuid"); ComponentDto component = new ComponentDto().setId(100L).setUuid("whatever-uuid-2"); - FakeServerSaver saver = new FakeServerSaver(getMyBatis(), new FakeRuleFinder(), component, project); + DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis()); + FakeServerSaver saver = new FakeServerSaver(dbClient, new FakeRuleFinder(), component, project); DefaultIssueComment comment = DefaultIssueComment.create("ABCDE", "emmerik", "the comment"); // override generated key @@ -256,8 +261,8 @@ public class IssueStorageTest extends AbstractDaoTestCase { static class FakeBatchSaver extends IssueStorage { - protected FakeBatchSaver(MyBatis mybatis, RuleFinder ruleFinder) { - super(mybatis, ruleFinder); + protected FakeBatchSaver(DbClient dbClient, RuleFinder ruleFinder) { + super(dbClient, ruleFinder); } @Override @@ -280,8 +285,8 @@ public class IssueStorageTest extends AbstractDaoTestCase { private final ComponentDto component; private final ComponentDto project; - protected FakeServerSaver(MyBatis mybatis, RuleFinder ruleFinder, ComponentDto component, ComponentDto project) { - super(mybatis, ruleFinder); + protected FakeServerSaver(DbClient dbClient, RuleFinder ruleFinder, ComponentDto component, ComponentDto project) { + super(dbClient, ruleFinder); this.component = component; this.project = project; } diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/ServerIssueStorageTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/ServerIssueStorageTest.java index 5b2b9d9c675..26237ec1925 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/ServerIssueStorageTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/ServerIssueStorageTest.java @@ -51,7 +51,6 @@ import static org.mockito.Mockito.when; public class ServerIssueStorageTest extends AbstractDaoTestCase { DbClient dbClient; - DbSession session; ServerIssueStorage storage; @@ -59,26 +58,19 @@ public class ServerIssueStorageTest extends AbstractDaoTestCase { public void setupDbClient() { System2 system = mock(System2.class); when(system.now()).thenReturn(2000000000L); - dbClient = new DbClient(getDatabase(), getMyBatis(), + dbClient = new DbClient(dbTester.database(), getMyBatis(), new ComponentDao(), new IssueDao(getMyBatis()), new ResourceDao(getMyBatis(), system)); - session = dbClient.openSession(false); - storage = new ServerIssueStorage(getMyBatis(), new FakeRuleFinder(), dbClient, mock(IssueIndexer.class)); - } - - @After - public void tearDown() { - session.close(); + storage = new ServerIssueStorage(new FakeRuleFinder(), dbClient, mock(IssueIndexer.class)); } @Test public void load_component_id_from_db() { setupData("load_component_id_from_db"); - session.commit(); - long componentId = storage.component(session, new DefaultIssue().setComponentKey("struts:Action")).getId(); + long componentId = storage.component(dbTester.getSession(), new DefaultIssue().setComponentKey("struts:Action")).getId(); assertThat(componentId).isEqualTo(100); } @@ -86,9 +78,8 @@ public class ServerIssueStorageTest extends AbstractDaoTestCase { @Test public void load_project_id_from_db() { setupData("load_project_id_from_db"); - session.commit(); - long projectId = storage.project(session, new DefaultIssue().setProjectKey("struts")).getId(); + long projectId = storage.project(dbTester.getSession(), new DefaultIssue().setProjectKey("struts")).getId(); assertThat(projectId).isEqualTo(1); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueAuthorizationDaoTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueAuthorizationDaoTest.java index cbfd4918f22..c0e8293cea5 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueAuthorizationDaoTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueAuthorizationDaoTest.java @@ -21,48 +21,35 @@ package org.sonar.server.issue.index; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; -import org.apache.commons.dbutils.DbUtils; -import org.junit.After; +import java.util.Collection; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.sonar.api.utils.System2; import org.sonar.db.DbTester; -import org.sonar.server.db.DbClient; import org.sonar.test.DbTests; -import java.sql.Connection; -import java.util.Collection; - import static org.assertj.core.api.Assertions.assertThat; @Category(DbTests.class) public class IssueAuthorizationDaoTest { @ClassRule - public static DbTester dbTester = new DbTester(); + public static DbTester dbTester = DbTester.create(System2.INSTANCE); IssueAuthorizationDao dao = new IssueAuthorizationDao(); - DbClient client; - Connection connection; @Before public void setUp() throws Exception { dbTester.truncateTables(); - client = new DbClient(dbTester.database(), dbTester.myBatis()); - connection = dbTester.openConnection(); - } - - @After - public void tearDown() { - DbUtils.closeQuietly(connection); } @Test public void select_all() { dbTester.prepareDbUnit(getClass(), "shared.xml"); - Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(client, connection, 0L); + Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(dbTester.getDbClient(), dbTester.getSession(), 0L); assertThat(dtos).hasSize(2); IssueAuthorizationDao.Dto abc = Iterables.find(dtos, new ProjectPredicate("ABC")); @@ -80,7 +67,7 @@ public class IssueAuthorizationDaoTest { public void select_after_date() { dbTester.prepareDbUnit(getClass(), "shared.xml"); - Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(client, connection, 1500000000L); + Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(dbTester.getDbClient(), dbTester.getSession(), 1500000000L); // only project DEF was updated in this period assertThat(dtos).hasSize(1); @@ -94,7 +81,7 @@ public class IssueAuthorizationDaoTest { public void no_authorization() { dbTester.prepareDbUnit(getClass(), "no_authorization.xml"); - Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(client, connection, 0L); + Collection<IssueAuthorizationDao.Dto> dtos = dao.selectAfterDate(dbTester.getDbClient(), dbTester.getSession(), 0L); assertThat(dtos).hasSize(1); IssueAuthorizationDao.Dto abc = Iterables.find(dtos, new ProjectPredicate("ABC")); diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueResultSetIteratorTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueResultSetIteratorTest.java index 9c9fd49f67f..ffd4017770d 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueResultSetIteratorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/index/IssueResultSetIteratorTest.java @@ -22,12 +22,14 @@ package org.sonar.server.issue.index; import com.google.common.base.Function; import com.google.common.collect.Maps; import org.apache.commons.dbutils.DbUtils; +import org.jruby.RubyProcess; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.sonar.api.rule.RuleKey; +import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.db.DbClient; import org.sonar.test.DbTests; @@ -41,27 +43,18 @@ import static org.assertj.core.api.Assertions.assertThat; public class IssueResultSetIteratorTest { @ClassRule - public static DbTester dbTester = new DbTester(); + public static DbTester dbTester = DbTester.create(System2.INSTANCE); - DbClient client; - Connection connection; @Before public void setUp() throws Exception { dbTester.truncateTables(); - client = new DbClient(dbTester.database(), dbTester.myBatis()); - connection = dbTester.openConnection(); - } - - @After - public void tearDown() { - DbUtils.closeQuietly(connection); } @Test public void iterator_over_one_issue() { dbTester.prepareDbUnit(getClass(), "one_issue.xml"); - IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L); + IssueResultSetIterator it = IssueResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L); Map<String, IssueDoc> issuesByKey = issuesByKey(it); it.close(); @@ -95,7 +88,7 @@ public class IssueResultSetIteratorTest { @Test public void iterator_over_issues() { dbTester.prepareDbUnit(getClass(), "shared.xml"); - IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L); + IssueResultSetIterator it = IssueResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L); Map<String, IssueDoc> issuesByKey = issuesByKey(it); it.close(); @@ -153,7 +146,7 @@ public class IssueResultSetIteratorTest { @Test public void extract_directory_path() { dbTester.prepareDbUnit(getClass(), "extract_directory_path.xml"); - IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L); + IssueResultSetIterator it = IssueResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L); Map<String, IssueDoc> issuesByKey = issuesByKey(it); it.close(); @@ -175,7 +168,7 @@ public class IssueResultSetIteratorTest { @Test public void extract_file_path() { dbTester.prepareDbUnit(getClass(), "extract_file_path.xml"); - IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 0L); + IssueResultSetIterator it = IssueResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L); Map<String, IssueDoc> issuesByKey = issuesByKey(it); it.close(); @@ -197,7 +190,7 @@ public class IssueResultSetIteratorTest { @Test public void select_after_date() { dbTester.prepareDbUnit(getClass(), "shared.xml"); - IssueResultSetIterator it = IssueResultSetIterator.create(client, connection, 1420000000000L); + IssueResultSetIterator it = IssueResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 1_420_000_000_000L); assertThat(it.hasNext()).isTrue(); IssueDoc issue = it.next(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java index a5c3487e6ff..a9c6752d12e 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java @@ -66,7 +66,7 @@ public class RegisterRulesTest extends AbstractDaoTestCase { when(system.now()).thenReturn(DATE1.getTime()); RuleDao ruleDao = new RuleDao(system); ActiveRuleDao activeRuleDao = new ActiveRuleDao(new QualityProfileDao(getMyBatis(), system), ruleDao, system); - dbClient = new DbClient(getDatabase(), getMyBatis(), ruleDao, activeRuleDao, + dbClient = new DbClient(dbTester.database(), getMyBatis(), ruleDao, activeRuleDao, new QualityProfileDao(getMyBatis(), system), new CharacteristicDao(getMyBatis())); dbSession = dbClient.openSession(false); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/source/db/FileSourceTesting.java b/server/sonar-server/src/test/java/org/sonar/server/source/index/FileSourceTesting.java index 5722ad60cdf..f6f0a0d7de6 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/source/db/FileSourceTesting.java +++ b/server/sonar-server/src/test/java/org/sonar/server/source/index/FileSourceTesting.java @@ -17,7 +17,7 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.sonar.server.source.db; +package org.sonar.server.source.index; import java.io.IOException; import java.sql.Connection; @@ -27,6 +27,7 @@ import java.util.Arrays; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.math.RandomUtils; import org.sonar.db.source.FileSourceDto; +import org.sonar.server.source.db.FileSourceDb; public class FileSourceTesting { @@ -44,6 +45,7 @@ public class FileSourceTesting { stmt.setString(2, fileUuid); stmt.executeUpdate(); stmt.close(); + connection.commit(); } /** diff --git a/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineIndexerTest.java index cae481e0995..a93cfbe8454 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineIndexerTest.java @@ -21,6 +21,11 @@ package org.sonar.server.source.index; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; +import java.io.IOException; +import java.sql.Connection; +import java.util.Date; +import java.util.List; +import java.util.Map; import org.apache.commons.io.FileUtils; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; @@ -36,16 +41,9 @@ import org.sonar.db.DbTester; import org.sonar.server.db.DbClient; import org.sonar.server.es.EsTester; import org.sonar.server.source.db.FileSourceDb; -import org.sonar.server.source.db.FileSourceTesting; import org.sonar.test.DbTests; import org.sonar.test.TestUtils; -import java.io.IOException; -import java.sql.Connection; -import java.util.Date; -import java.util.List; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.sonar.server.source.index.SourceLineIndexDefinition.FIELD_DUPLICATIONS; @@ -90,9 +88,9 @@ public class SourceLineIndexerTest { public void index_source_lines() throws Exception { db.prepareDbUnit(getClass(), "db.xml"); - Connection connection = db.openConnection(); - FileSourceTesting.updateDataColumn(connection, "FILE_UUID", FileSourceTesting.newRandomData(3).build()); - connection.close(); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "FILE_UUID", FileSourceTesting.newRandomData(3).build()); + } indexer.index(); assertThat(countDocuments()).isEqualTo(3); @@ -102,9 +100,9 @@ public class SourceLineIndexerTest { public void index_source_lines_from_project() throws Exception { db.prepareDbUnit(getClass(), "db.xml"); - Connection connection = db.openConnection(); - FileSourceTesting.updateDataColumn(connection, "FILE_UUID", FileSourceTesting.newRandomData(3).build()); - connection.close(); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "FILE_UUID", FileSourceTesting.newRandomData(3).build()); + } indexer.index("PROJECT_UUID"); assertThat(countDocuments()).isEqualTo(3); @@ -114,9 +112,9 @@ public class SourceLineIndexerTest { public void index_nothing_from_unknown_project() throws Exception { db.prepareDbUnit(getClass(), "db.xml"); - Connection connection = db.openConnection(); - FileSourceTesting.updateDataColumn(connection, "FILE_UUID", FileSourceTesting.newRandomData(3).build()); - connection.close(); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "FILE_UUID", FileSourceTesting.newRandomData(3).build()); + } indexer.index("UNKNOWN"); assertThat(countDocuments()).isZero(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineResultSetIteratorTest.java b/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineResultSetIteratorTest.java index 8d927b7b7be..058990e7b03 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineResultSetIteratorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/source/index/SourceLineResultSetIteratorTest.java @@ -19,23 +19,18 @@ */ package org.sonar.server.source.index; +import java.sql.Connection; +import java.util.Map; import org.assertj.core.data.MapEntry; import org.elasticsearch.action.update.UpdateRequest; -import org.junit.After; -import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; -import org.sonar.server.db.DbClient; import org.sonar.server.source.db.FileSourceDb; -import org.sonar.server.source.db.FileSourceTesting; import org.sonar.test.DbTests; -import java.sql.Connection; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -43,34 +38,24 @@ import static org.junit.Assert.fail; public class SourceLineResultSetIteratorTest { @ClassRule - public static DbTester db = DbTester.createForSchema(System2.INSTANCE, SourceLineResultSetIteratorTest.class, "schema.sql"); - - DbClient dbClient; - - Connection connection; + public static DbTester db = DbTester.create(System2.INSTANCE); SourceLineResultSetIterator iterator; - @Before - public void setUp() throws Exception { - dbClient = new DbClient(db.database(), db.myBatis()); - connection = db.openConnection(); - } - - @After public void after() throws Exception { if (iterator != null) { iterator.close(); } - connection.close(); } @Test public void traverse_db() throws Exception { db.prepareDbUnit(getClass(), "shared.xml"); - FileSourceTesting.updateDataColumn(connection, "F1", FileSourceTesting.newFakeData(3).build()); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "F1", FileSourceTesting.newFakeData(3).build()); + } - iterator = SourceLineResultSetIterator.create(dbClient, connection, 0L, null); + iterator = SourceLineResultSetIterator.create(db.getDbClient(), db.getSession(), 0L, null); assertThat(iterator.hasNext()).isTrue(); FileSourcesUpdaterHelper.Row row = iterator.next(); assertThat(row.getProjectUuid()).isEqualTo("P1"); @@ -97,7 +82,7 @@ public class SourceLineResultSetIteratorTest { MapEntry.entry(SourceLineIndexDefinition.FIELD_OVERALL_LINE_HITS, 7), MapEntry.entry(SourceLineIndexDefinition.FIELD_OVERALL_CONDITIONS, 8), MapEntry.entry(SourceLineIndexDefinition.FIELD_OVERALL_COVERED_CONDITIONS, 9) - ); + ); } /** @@ -108,9 +93,11 @@ public class SourceLineResultSetIteratorTest { db.prepareDbUnit(getClass(), "shared.xml"); FileSourceDb.Data.Builder dataBuilder = FileSourceDb.Data.newBuilder(); dataBuilder.addLinesBuilder().setLine(1).build(); - FileSourceTesting.updateDataColumn(connection, "F1", dataBuilder.build()); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "F1", dataBuilder.build()); + } - iterator = SourceLineResultSetIterator.create(dbClient, connection, 0L, null); + iterator = SourceLineResultSetIterator.create(db.getDbClient(), db.getSession(), 0L, null); FileSourcesUpdaterHelper.Row row = iterator.next(); assertThat(row.getProjectUuid()).isEqualTo("P1"); assertThat(row.getFileUuid()).isEqualTo("F1"); @@ -122,7 +109,7 @@ public class SourceLineResultSetIteratorTest { MapEntry.entry(SourceLineIndexDefinition.FIELD_PROJECT_UUID, "P1"), MapEntry.entry(SourceLineIndexDefinition.FIELD_FILE_UUID, "F1"), MapEntry.entry(SourceLineIndexDefinition.FIELD_LINE, 1) - ); + ); // null values assertThat(doc).containsKeys( SourceLineIndexDefinition.FIELD_SCM_REVISION, @@ -138,14 +125,14 @@ public class SourceLineResultSetIteratorTest { SourceLineIndexDefinition.FIELD_OVERALL_LINE_HITS, SourceLineIndexDefinition.FIELD_OVERALL_CONDITIONS, SourceLineIndexDefinition.FIELD_OVERALL_COVERED_CONDITIONS - ); + ); } @Test public void filter_by_date() { db.prepareDbUnit(getClass(), "shared.xml"); - iterator = SourceLineResultSetIterator.create(dbClient, connection, 2000000000000L, null); + iterator = SourceLineResultSetIterator.create(db.getDbClient(), db.getSession(), 2000000000000L, null); assertThat(iterator.hasNext()).isFalse(); } @@ -154,9 +141,11 @@ public class SourceLineResultSetIteratorTest { db.prepareDbUnit(getClass(), "filter_by_project.xml"); FileSourceDb.Data.Builder dataBuilder = FileSourceDb.Data.newBuilder(); dataBuilder.addLinesBuilder().setLine(1).build(); - FileSourceTesting.updateDataColumn(connection, "F1", dataBuilder.build()); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "F1", dataBuilder.build()); + } - iterator = SourceLineResultSetIterator.create(dbClient, connection, 0L, "P1"); + iterator = SourceLineResultSetIterator.create(db.getDbClient(), db.getSession(), 0L, "P1"); FileSourcesUpdaterHelper.Row row = iterator.next(); assertThat(row.getProjectUuid()).isEqualTo("P1"); @@ -171,9 +160,11 @@ public class SourceLineResultSetIteratorTest { db.prepareDbUnit(getClass(), "filter_by_project_and_date.xml"); FileSourceDb.Data.Builder dataBuilder = FileSourceDb.Data.newBuilder(); dataBuilder.addLinesBuilder().setLine(1).build(); - FileSourceTesting.updateDataColumn(connection, "F1", dataBuilder.build()); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "F1", dataBuilder.build()); + } - iterator = SourceLineResultSetIterator.create(dbClient, connection, 1400000000000L, "P1"); + iterator = SourceLineResultSetIterator.create(db.getDbClient(), db.getSession(), 1400000000000L, "P1"); FileSourcesUpdaterHelper.Row row = iterator.next(); assertThat(row.getProjectUuid()).isEqualTo("P1"); @@ -187,9 +178,11 @@ public class SourceLineResultSetIteratorTest { public void fail_on_bad_data_format() throws Exception { db.prepareDbUnit(getClass(), "shared.xml"); - FileSourceTesting.updateDataColumn(connection, "F1", "THIS_IS_NOT_PROTOBUF".getBytes()); + try (Connection connection = db.openConnection()) { + FileSourceTesting.updateDataColumn(connection, "F1", "THIS_IS_NOT_PROTOBUF".getBytes()); + } - iterator = SourceLineResultSetIterator.create(dbClient, connection, 0L, null); + iterator = SourceLineResultSetIterator.create(db.getDbClient(), db.getSession(), 0L, null); try { assertThat(iterator.hasNext()).isTrue(); iterator.next(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/test/db/TestTesting.java b/server/sonar-server/src/test/java/org/sonar/server/test/db/TestTesting.java index 79ef35166db..bf900c2dd39 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/test/db/TestTesting.java +++ b/server/sonar-server/src/test/java/org/sonar/server/test/db/TestTesting.java @@ -23,6 +23,7 @@ package org.sonar.server.test.db; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.math.RandomUtils; import org.sonar.api.utils.internal.Uuids; +import org.sonar.db.DbSession; import org.sonar.db.source.FileSourceDto; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.source.db.FileSourceDb.Test.TestStatus; @@ -40,16 +41,18 @@ public class TestTesting { // only static stuff } - public static void updateDataColumn(Connection connection, String fileUuid, List<FileSourceDb.Test> tests) throws SQLException { - updateDataColumn(connection, fileUuid, FileSourceDto.encodeTestData(tests)); + public static void updateDataColumn(DbSession session, String fileUuid, List<FileSourceDb.Test> tests) throws SQLException { + updateDataColumn(session, fileUuid, FileSourceDto.encodeTestData(tests)); } - public static void updateDataColumn(Connection connection, String fileUuid, byte[] data) throws SQLException { + public static void updateDataColumn(DbSession session, String fileUuid, byte[] data) throws SQLException { + Connection connection = session.getConnection(); PreparedStatement stmt = connection.prepareStatement("UPDATE file_sources SET binary_data = ? WHERE file_uuid=? AND data_type='TEST'"); stmt.setBytes(1, data); stmt.setString(2, fileUuid); stmt.executeUpdate(); stmt.close(); + connection.commit(); } /** diff --git a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java index ae1809eefe9..c9fc0f497dc 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestIndexerTest.java @@ -21,6 +21,11 @@ package org.sonar.server.test.index; import com.google.common.collect.Iterators; +import java.io.IOException; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; import org.apache.commons.io.FileUtils; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; @@ -31,6 +36,7 @@ import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.sonar.api.config.Settings; +import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.db.DbClient; import org.sonar.server.es.EsTester; @@ -41,13 +47,6 @@ import org.sonar.server.test.db.TestTesting; import org.sonar.test.DbTests; import org.sonar.test.TestUtils; -import java.io.IOException; -import java.sql.Connection; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.sonar.server.test.index.TestIndexDefinition.FIELD_DURATION_IN_MS; @@ -68,7 +67,7 @@ public class TestIndexerTest { public static EsTester es = new EsTester().addDefinitions(new TestIndexDefinition(new Settings())); @ClassRule - public static DbTester db = new DbTester(); + public static DbTester db = DbTester.create(System2.INSTANCE); private TestIndexer sut; @@ -83,9 +82,7 @@ public class TestIndexerTest { @Test public void index_tests() throws Exception { db.prepareDbUnit(getClass(), "db.xml"); - Connection connection = db.openConnection(); - TestTesting.updateDataColumn(connection, "FILE_UUID", TestTesting.newRandomTests(3)); - connection.close(); + TestTesting.updateDataColumn(db.getSession(), "FILE_UUID", TestTesting.newRandomTests(3)); sut.index(); @@ -96,9 +93,7 @@ public class TestIndexerTest { public void index_tests_from_project() throws Exception { db.prepareDbUnit(getClass(), "db.xml"); - Connection connection = db.openConnection(); - TestTesting.updateDataColumn(connection, "FILE_UUID", TestTesting.newRandomTests(3)); - connection.close(); + TestTesting.updateDataColumn(db.getSession(), "FILE_UUID", TestTesting.newRandomTests(3)); sut.index("PROJECT_UUID"); assertThat(countDocuments()).isEqualTo(3); @@ -108,9 +103,7 @@ public class TestIndexerTest { public void index_nothing_from_unknown_project() throws Exception { db.prepareDbUnit(getClass(), "db.xml"); - Connection connection = db.openConnection(); - TestTesting.updateDataColumn(connection, "FILE_UUID", TestTesting.newRandomTests(3)); - connection.close(); + TestTesting.updateDataColumn(db.getSession(), "FILE_UUID", TestTesting.newRandomTests(3)); sut.index("UNKNOWN"); assertThat(countDocuments()).isZero(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestResultSetIteratorTest.java b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestResultSetIteratorTest.java index b144a107620..e18a89a85c1 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/test/index/TestResultSetIteratorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/test/index/TestResultSetIteratorTest.java @@ -20,29 +20,24 @@ package org.sonar.server.test.index; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; import org.assertj.core.data.MapEntry; import org.elasticsearch.action.update.UpdateRequest; import org.junit.After; -import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; -import org.sonar.server.db.DbClient; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.source.db.FileSourceDb.Test.TestStatus; import org.sonar.server.source.index.FileSourcesUpdaterHelper; -import org.sonar.server.source.index.SourceLineResultSetIteratorTest; import org.sonar.server.test.db.TestTesting; import org.sonar.test.DbTests; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; @@ -50,33 +45,22 @@ import static org.assertj.core.api.Assertions.fail; public class TestResultSetIteratorTest { @ClassRule - public static DbTester db = DbTester.createForSchema(System2.INSTANCE, SourceLineResultSetIteratorTest.class, "schema.sql"); - - DbClient dbClient; - - Connection connection; + public static DbTester dbTester = DbTester.create(System2.INSTANCE); TestResultSetIterator sut; - @Before - public void setUp() throws Exception { - dbClient = new DbClient(db.database(), db.myBatis()); - connection = db.openConnection(); - } - @After public void after() throws Exception { if (sut != null) { sut.close(); } - connection.close(); } @Test public void traverse_db() throws Exception { - db.prepareDbUnit(getClass(), "shared.xml"); - TestTesting.updateDataColumn(connection, "F1", newFakeTests(3)); - sut = TestResultSetIterator.create(dbClient, connection, 0L, null); + dbTester.prepareDbUnit(getClass(), "shared.xml"); + TestTesting.updateDataColumn(dbTester.getSession(), "F1", newFakeTests(3)); + sut = TestResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L, null); FileSourcesUpdaterHelper.Row row = sut.next(); assertThat(row.getProjectUuid()).isEqualTo("P1"); @@ -103,15 +87,15 @@ public class TestResultSetIteratorTest { */ @Test public void minimal_data() throws Exception { - db.prepareDbUnit(getClass(), "shared.xml"); + dbTester.prepareDbUnit(getClass(), "shared.xml"); List<FileSourceDb.Test> tests = Arrays.asList( FileSourceDb.Test.newBuilder() .setUuid("U1") .setName("N1") .build() ); - TestTesting.updateDataColumn(connection, "F1", tests); - sut = TestResultSetIterator.create(dbClient, connection, 0L, null); + TestTesting.updateDataColumn(dbTester.getSession(), "F1", tests); + sut = TestResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L, null); FileSourcesUpdaterHelper.Row row = sut.next(); @@ -139,18 +123,18 @@ public class TestResultSetIteratorTest { @Test public void filter_by_date() { - db.prepareDbUnit(getClass(), "shared.xml"); - sut = TestResultSetIterator.create(dbClient, connection, 2000000000000L, null); + dbTester.prepareDbUnit(getClass(), "shared.xml"); + sut = TestResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 2000000000000L, null); assertThat(sut.hasNext()).isFalse(); } @Test public void filter_by_project() throws Exception { - db.prepareDbUnit(getClass(), "filter_by_project.xml"); - TestTesting.updateDataColumn(connection, "F1", newFakeTests(1)); + dbTester.prepareDbUnit(getClass(), "filter_by_project.xml"); + TestTesting.updateDataColumn(dbTester.getSession(), "F1", newFakeTests(1)); - sut = TestResultSetIterator.create(dbClient, connection, 0L, "P1"); + sut = TestResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L, "P1"); FileSourcesUpdaterHelper.Row row = sut.next(); assertThat(row.getProjectUuid()).isEqualTo("P1"); @@ -162,10 +146,10 @@ public class TestResultSetIteratorTest { @Test public void filter_by_project_and_date() throws Exception { - db.prepareDbUnit(getClass(), "filter_by_project_and_date.xml"); - TestTesting.updateDataColumn(connection, "F1", newFakeTests(1)); + dbTester.prepareDbUnit(getClass(), "filter_by_project_and_date.xml"); + TestTesting.updateDataColumn(dbTester.getSession(), "F1", newFakeTests(1)); - sut = TestResultSetIterator.create(dbClient, connection, 1400000000000L, "P1"); + sut = TestResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 1400000000000L, "P1"); FileSourcesUpdaterHelper.Row row = sut.next(); assertThat(row.getProjectUuid()).isEqualTo("P1"); @@ -177,11 +161,11 @@ public class TestResultSetIteratorTest { @Test public void fail_on_bad_data_format() throws Exception { - db.prepareDbUnit(getClass(), "shared.xml"); + dbTester.prepareDbUnit(getClass(), "shared.xml"); - TestTesting.updateDataColumn(connection, "F1", "THIS_IS_NOT_PROTOBUF".getBytes()); + TestTesting.updateDataColumn(dbTester.getSession(), "F1", "THIS_IS_NOT_PROTOBUF".getBytes()); - sut = TestResultSetIterator.create(dbClient, connection, 0L, null); + sut = TestResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L, null); try { assertThat(sut.hasNext()).isTrue(); sut.next(); diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/index/UserResultSetIteratorTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/index/UserResultSetIteratorTest.java index ec9285357f4..8d56bf29ca1 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/user/index/UserResultSetIteratorTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/user/index/UserResultSetIteratorTest.java @@ -21,46 +21,32 @@ package org.sonar.server.user.index; import com.google.common.base.Function; import com.google.common.collect.Maps; -import org.apache.commons.dbutils.DbUtils; -import org.junit.After; +import java.util.Map; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.sonar.api.utils.System2; import org.sonar.db.DbTester; -import org.sonar.server.db.DbClient; import org.sonar.test.DbTests; -import java.sql.Connection; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; @Category(DbTests.class) public class UserResultSetIteratorTest { @ClassRule - public static DbTester dbTester = new DbTester(); - - DbClient client; - Connection connection; + public static DbTester dbTester = DbTester.create(System2.INSTANCE); @Before public void setUp() throws Exception { dbTester.truncateTables(); - client = new DbClient(dbTester.database(), dbTester.myBatis()); - connection = dbTester.openConnection(); - } - - @After - public void tearDown() { - DbUtils.closeQuietly(connection); } @Test public void iterator_over_users() { dbTester.prepareDbUnit(getClass(), "shared.xml"); - UserResultSetIterator it = UserResultSetIterator.create(client, connection, 0L); + UserResultSetIterator it = UserResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 0L); Map<String, UserDoc> usersByLogin = Maps.uniqueIndex(it, new Function<UserDoc, String>() { @Override public String apply(UserDoc user) { @@ -99,7 +85,7 @@ public class UserResultSetIteratorTest { @Test public void select_after_date() { dbTester.prepareDbUnit(getClass(), "shared.xml"); - UserResultSetIterator it = UserResultSetIterator.create(client, connection, 1520000000000L); + UserResultSetIterator it = UserResultSetIterator.create(dbTester.getDbClient(), dbTester.getSession(), 1520000000000L); assertThat(it.hasNext()).isTrue(); UserDoc user = it.next(); diff --git a/sonar-db/src/main/java/org/sonar/db/DaoUtils.java b/sonar-db/src/main/java/org/sonar/db/DaoUtils.java index 7e3773f2b0d..4269182f2a7 100644 --- a/sonar-db/src/main/java/org/sonar/db/DaoUtils.java +++ b/sonar-db/src/main/java/org/sonar/db/DaoUtils.java @@ -24,7 +24,7 @@ import java.util.List; import org.sonar.db.activity.ActivityDao; import org.sonar.db.component.ComponentLinkDao; import org.sonar.db.component.ResourceDao; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.db.component.ResourceKeyUpdaterDao; import org.sonar.db.component.SnapshotDao; import org.sonar.db.compute.AnalysisReportDao; @@ -97,7 +97,7 @@ public final class DaoUtils { QualityProfileDao.class, PurgeDao.class, CharacteristicDao.class, - ResourceIndexerDao.class, + ResourceIndexDao.class, ResourceDao.class, ResourceKeyUpdaterDao.class, RoleDao.class, diff --git a/sonar-db/src/main/java/org/sonar/db/DbClient2.java b/sonar-db/src/main/java/org/sonar/db/DbClient.java index 92cbd39c2c5..aad304f08aa 100644 --- a/sonar-db/src/main/java/org/sonar/db/DbClient2.java +++ b/sonar-db/src/main/java/org/sonar/db/DbClient.java @@ -25,7 +25,7 @@ import javax.annotation.Nullable; import org.sonar.db.activity.ActivityDao; import org.sonar.db.component.ComponentLinkDao; import org.sonar.db.component.ResourceDao; -import org.sonar.db.component.ResourceIndexerDao; +import org.sonar.db.component.ResourceIndexDao; import org.sonar.db.component.SnapshotDao; import org.sonar.db.compute.AnalysisReportDao; import org.sonar.db.dashboard.DashboardDao; @@ -52,8 +52,9 @@ import org.sonar.db.user.GroupMembershipDao; import org.sonar.db.user.RoleDao; import org.sonar.db.user.UserGroupDao; -public class DbClient2 { +public class DbClient { + private final Database database; private final MyBatis myBatis; private final QualityProfileDao qualityProfileDao; private final CharacteristicDao debtCharacteristicDao; @@ -79,13 +80,14 @@ public class DbClient2 { private final WidgetPropertyDao widgetPropertyDao; private final FileSourceDao fileSourceDao; private final AuthorDao authorDao; - private final ResourceIndexerDao componentIndexDao; + private final ResourceIndexDao componentIndexDao; private final ComponentLinkDao componentLinkDao; private final EventDao eventDao; private final PurgeDao purgeDao; private final QualityGateConditionDao gateConditionDao; - public DbClient2(MyBatis myBatis, Dao[] daos) { + public DbClient(Database database, MyBatis myBatis, Dao[] daos) { + this.database = database; this.myBatis = myBatis; Map<Class, Dao> map = new IdentityHashMap<>(); @@ -116,11 +118,17 @@ public class DbClient2 { widgetPropertyDao = getDao(map, WidgetPropertyDao.class); fileSourceDao = getDao(map, FileSourceDao.class); authorDao = getDao(map, AuthorDao.class); - componentIndexDao = getDao(map, ResourceIndexerDao.class); + componentIndexDao = getDao(map, ResourceIndexDao.class); componentLinkDao = getDao(map, ComponentLinkDao.class); eventDao = getDao(map, EventDao.class); purgeDao = getDao(map, PurgeDao.class); gateConditionDao = getDao(map, QualityGateConditionDao.class); + doOnLoad(map); + } + + // should be removed, but till used by sonar-server + protected void doOnLoad(Map<Class, Dao> daoByClass) { + } public DbSession openSession(boolean batch) { @@ -131,6 +139,10 @@ public class DbClient2 { MyBatis.closeQuietly(session); } + public Database getDatabase() { + return database; + } + public IssueDao issueDao() { return issueDao; } @@ -223,7 +235,7 @@ public class DbClient2 { return authorDao; } - public ResourceIndexerDao componentIndexDao() { + public ResourceIndexDao componentIndexDao() { return componentIndexDao; } @@ -247,7 +259,12 @@ public class DbClient2 { return gateConditionDao; } - private <K extends Dao> K getDao(Map<Class, Dao> map, Class<K> clazz) { + protected <K extends Dao> K getDao(Map<Class, Dao> map, Class<K> clazz) { return (K) map.get(clazz); } + + // should be removed. Still used by some old DAO in sonar-server + public MyBatis getMyBatis() { + return myBatis; + } } diff --git a/sonar-db/src/main/java/org/sonar/db/MyBatis.java b/sonar-db/src/main/java/org/sonar/db/MyBatis.java index 5926def8753..e4e3bce008b 100644 --- a/sonar-db/src/main/java/org/sonar/db/MyBatis.java +++ b/sonar-db/src/main/java/org/sonar/db/MyBatis.java @@ -48,7 +48,7 @@ import org.sonar.db.component.ComponentMapper; import org.sonar.db.component.FilePathWithHashDto; import org.sonar.db.component.ResourceDto; import org.sonar.db.component.ResourceIndexDto; -import org.sonar.db.component.ResourceIndexerMapper; +import org.sonar.db.component.ResourceIndexMapper; import org.sonar.db.component.ResourceKeyUpdaterMapper; import org.sonar.db.component.ResourceMapper; import org.sonar.db.component.SnapshotDto; @@ -249,7 +249,7 @@ public class MyBatis { IssueMapper.class, IssueChangeMapper.class, IssueFilterMapper.class, IssueFilterFavouriteMapper.class, IsAliveMapper.class, LoadedTemplateMapper.class, MeasureFilterMapper.class, Migration44Mapper.class, PermissionTemplateMapper.class, PropertiesMapper.class, PurgeMapper.class, - ResourceKeyUpdaterMapper.class, ResourceIndexerMapper.class, RoleMapper.class, RuleMapper.class, + ResourceKeyUpdaterMapper.class, ResourceIndexMapper.class, RoleMapper.class, RuleMapper.class, SchemaMigrationMapper.class, SemaphoreMapper.class, UserMapper.class, GroupMapper.class, UserGroupMapper.class, WidgetMapper.class, WidgetPropertyMapper.class, FileSourceMapper.class, ActionPlanMapper.class, ActionPlanStatsMapper.class, diff --git a/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexerDao.java b/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexDao.java index 827ece8fd1b..b146a517f65 100644 --- a/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexerDao.java +++ b/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexDao.java @@ -31,9 +31,9 @@ import org.sonar.db.AbstractDao; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; -public class ResourceIndexerDao extends AbstractDao { +public class ResourceIndexDao extends AbstractDao { - private static final String SELECT_RESOURCES = "org.sonar.db.component.ResourceIndexerMapper.selectResources"; + private static final String SELECT_RESOURCES = "org.sonar.db.component.ResourceIndexMapper.selectResources"; public static final int MINIMUM_KEY_SIZE = 3; public static final int SINGLE_INDEX_SIZE = 2; @@ -44,18 +44,18 @@ public class ResourceIndexerDao extends AbstractDao { private static final String[] NOT_RENAMABLE_QUALIFIERS = {Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE, Qualifiers.CLASS}; private static final String[] NOT_RENAMABLE_SCOPES = {Scopes.FILE}; - public ResourceIndexerDao(MyBatis myBatis, System2 system2) { + public ResourceIndexDao(MyBatis myBatis, System2 system2) { super(myBatis, system2); } public List<Long> selectProjectIdsFromQueryAndViewOrSubViewUuid(DbSession session, String query, String viewOrSubViewUuid) { - return session.getMapper(ResourceIndexerMapper.class).selectProjectIdsFromQueryAndViewOrSubViewUuid(query + "%", "%." + viewOrSubViewUuid + ".%"); + return session.getMapper(ResourceIndexMapper.class).selectProjectIdsFromQueryAndViewOrSubViewUuid(query + "%", "%." + viewOrSubViewUuid + ".%"); } /** * This method is reentrant. It can be executed even if the project is already indexed. */ - public ResourceIndexerDao indexProject(final long rootProjectId) { + public ResourceIndexDao indexProject(final long rootProjectId) { DbSession session = myBatis().openSession(true); try { indexProject(rootProjectId, session); @@ -68,18 +68,18 @@ public class ResourceIndexerDao extends AbstractDao { } public void indexProject(final long rootProjectId, DbSession session) { - ResourceIndexerMapper mapper = session.getMapper(ResourceIndexerMapper.class); + ResourceIndexMapper mapper = session.getMapper(ResourceIndexMapper.class); doIndexProject(rootProjectId, session, mapper); } /** * This method is reentrant. It can be executed even if some projects are already indexed. */ - public ResourceIndexerDao indexProjects() { + public ResourceIndexDao indexProjects() { final DbSession session = myBatis().openSession(true); try { - final ResourceIndexerMapper mapper = session.getMapper(ResourceIndexerMapper.class); - session.select("org.sonar.db.component.ResourceIndexerMapper.selectRootProjectIds", /* workaround to get booleans */ResourceIndexerQuery.create(), new ResultHandler() { + final ResourceIndexMapper mapper = session.getMapper(ResourceIndexMapper.class); + session.select(ResourceIndexMapper.class.getName() + ".selectRootProjectIds", /* workaround to get booleans */ResourceIndexQuery.create(), new ResultHandler() { @Override public void handleResult(ResultContext context) { Integer rootProjectId = (Integer) context.getResultObject(); @@ -94,9 +94,9 @@ public class ResourceIndexerDao extends AbstractDao { } } - private void doIndexProject(long rootProjectId, SqlSession session, final ResourceIndexerMapper mapper) { + private void doIndexProject(long rootProjectId, SqlSession session, final ResourceIndexMapper mapper) { // non indexed resources - ResourceIndexerQuery query = ResourceIndexerQuery.create() + ResourceIndexQuery query = ResourceIndexQuery.create() .setNonIndexedOnly(true) .setQualifiers(NOT_RENAMABLE_QUALIFIERS) .setScopes(NOT_RENAMABLE_SCOPES) @@ -112,7 +112,7 @@ public class ResourceIndexerDao extends AbstractDao { // some resources can be renamed, so index must be regenerated // -> delete existing rows and create them again - query = ResourceIndexerQuery.create() + query = ResourceIndexQuery.create() .setNonIndexedOnly(false) .setQualifiers(RENAMABLE_QUALIFIERS) .setScopes(RENAMABLE_SCOPES) @@ -129,7 +129,7 @@ public class ResourceIndexerDao extends AbstractDao { }); } - void doIndex(ResourceDto resource, ResourceIndexerMapper mapper) { + void doIndex(ResourceDto resource, ResourceIndexMapper mapper) { String key = nameToKey(resource.getName()); if (key.length() >= MINIMUM_KEY_SIZE || key.length() == SINGLE_INDEX_SIZE) { insertIndexEntries(key, resource.getId(), resource.getQualifier(), resource.getRootId(), resource.getName().length(), mapper); @@ -147,7 +147,7 @@ public class ResourceIndexerDao extends AbstractDao { public boolean indexResource(DbSession session, long id) { boolean indexed = false; - ResourceIndexerMapper mapper = session.getMapper(ResourceIndexerMapper.class); + ResourceIndexMapper mapper = session.getMapper(ResourceIndexMapper.class); ResourceDto resource = mapper.selectResourceToIndex(id); if (resource != null) { Long rootId = resource.getRootId(); @@ -162,7 +162,7 @@ public class ResourceIndexerDao extends AbstractDao { public boolean indexResource(int id, String name, String qualifier, int rootId) { boolean indexed = false; SqlSession session = myBatis().openSession(false); - ResourceIndexerMapper mapper = session.getMapper(ResourceIndexerMapper.class); + ResourceIndexMapper mapper = session.getMapper(ResourceIndexMapper.class); try { indexed = indexResource(id, name, qualifier, rootId, session, mapper); } finally { @@ -171,7 +171,7 @@ public class ResourceIndexerDao extends AbstractDao { return indexed; } - private boolean indexResource(long id, String name, String qualifier, long rootId, SqlSession session, ResourceIndexerMapper mapper) { + private boolean indexResource(long id, String name, String qualifier, long rootId, SqlSession session, ResourceIndexMapper mapper) { boolean indexed = false; String key = nameToKey(name); if (key.length() >= MINIMUM_KEY_SIZE || key.length() == SINGLE_INDEX_SIZE) { @@ -185,7 +185,7 @@ public class ResourceIndexerDao extends AbstractDao { return indexed; } - private void insertIndexEntries(String key, long resourceId, String qualifier, long rootId, int nameLength, ResourceIndexerMapper mapper) { + private void insertIndexEntries(String key, long resourceId, String qualifier, long rootId, int nameLength, ResourceIndexMapper mapper) { ResourceIndexDto dto = new ResourceIndexDto() .setResourceId(resourceId) .setQualifier(qualifier) @@ -205,7 +205,7 @@ public class ResourceIndexerDao extends AbstractDao { * If the resource is indexed with a different key, then this index is dropped and the * resource must be indexed again. */ - private boolean sanitizeIndex(long resourceId, String key, ResourceIndexerMapper mapper) { + private boolean sanitizeIndex(long resourceId, String key, ResourceIndexMapper mapper) { ResourceIndexDto masterIndex = mapper.selectMasterIndexByResourceId(resourceId); if (masterIndex != null && !StringUtils.equals(key, masterIndex.getKey())) { // resource has been renamed -> drop existing indexes diff --git a/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexerMapper.java b/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexMapper.java index a0cb17b2ccf..31efd21338e 100644 --- a/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexerMapper.java +++ b/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexMapper.java @@ -22,7 +22,7 @@ package org.sonar.db.component; import java.util.List; import org.apache.ibatis.annotations.Param; -public interface ResourceIndexerMapper { +public interface ResourceIndexMapper { List<Long> selectProjectIdsFromQueryAndViewOrSubViewUuid(@Param("query") String query, @Param("viewUuidQuery") String viewUuidQuery); diff --git a/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexerQuery.java b/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexQuery.java index f05204aa130..6d5e495aad3 100644 --- a/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexerQuery.java +++ b/sonar-db/src/main/java/org/sonar/db/component/ResourceIndexQuery.java @@ -19,17 +19,17 @@ */ package org.sonar.db.component; -final class ResourceIndexerQuery { +final class ResourceIndexQuery { private long rootProjectId; private String[] scopes = null; private String[] qualifiers = null; private boolean nonIndexedOnly = false; - private ResourceIndexerQuery() { + private ResourceIndexQuery() { } - public static ResourceIndexerQuery create() { - return new ResourceIndexerQuery(); + public static ResourceIndexQuery create() { + return new ResourceIndexQuery(); } public String[] getScopes() { @@ -40,12 +40,12 @@ final class ResourceIndexerQuery { return qualifiers; } - public ResourceIndexerQuery setScopes(String[] scopes) { + public ResourceIndexQuery setScopes(String[] scopes) { this.scopes = scopes; return this; } - public ResourceIndexerQuery setQualifiers(String[] qualifiers) { + public ResourceIndexQuery setQualifiers(String[] qualifiers) { this.qualifiers = qualifiers; return this; } @@ -54,7 +54,7 @@ final class ResourceIndexerQuery { return rootProjectId; } - public ResourceIndexerQuery setRootProjectId(long i) { + public ResourceIndexQuery setRootProjectId(long i) { this.rootProjectId = i; return this; } @@ -63,7 +63,7 @@ final class ResourceIndexerQuery { return nonIndexedOnly; } - public ResourceIndexerQuery setNonIndexedOnly(boolean b) { + public ResourceIndexQuery setNonIndexedOnly(boolean b) { this.nonIndexedOnly = b; return this; } diff --git a/sonar-db/src/main/resources/org/sonar/db/component/ResourceIndexerMapper.xml b/sonar-db/src/main/resources/org/sonar/db/component/ResourceIndexMapper.xml index b9a10673e3c..1228c975365 100644 --- a/sonar-db/src/main/resources/org/sonar/db/component/ResourceIndexerMapper.xml +++ b/sonar-db/src/main/resources/org/sonar/db/component/ResourceIndexMapper.xml @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> -<mapper namespace="org.sonar.db.component.ResourceIndexerMapper"> +<mapper namespace="org.sonar.db.component.ResourceIndexMapper"> <select id="selectProjectIdsFromQueryAndViewOrSubViewUuid" parameterType="map" resultType="long"> SELECT r.resource_id FROM resource_index r diff --git a/sonar-db/src/test/java/org/sonar/db/AbstractDaoTestCase.java b/sonar-db/src/test/java/org/sonar/db/AbstractDaoTestCase.java index 756a3437595..43b8c75e036 100644 --- a/sonar-db/src/test/java/org/sonar/db/AbstractDaoTestCase.java +++ b/sonar-db/src/test/java/org/sonar/db/AbstractDaoTestCase.java @@ -19,50 +19,13 @@ */ package org.sonar.db; -import com.google.common.collect.Maps; -import com.google.common.io.Closeables; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Map; -import java.util.Properties; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.text.StrSubstitutor; -import org.dbunit.Assertion; -import org.dbunit.DataSourceDatabaseTester; -import org.dbunit.DatabaseUnitException; -import org.dbunit.IDatabaseTester; -import org.dbunit.database.DatabaseConfig; -import org.dbunit.database.IDatabaseConnection; -import org.dbunit.dataset.CompositeDataSet; -import org.dbunit.dataset.DataSetException; -import org.dbunit.dataset.IDataSet; -import org.dbunit.dataset.ITable; -import org.dbunit.dataset.ReplacementDataSet; -import org.dbunit.dataset.filter.DefaultColumnFilter; -import org.dbunit.dataset.xml.FlatXmlDataSet; -import org.dbunit.ext.mssql.InsertIdentityOperation; -import org.dbunit.ext.mysql.MySqlMetadataHandler; -import org.dbunit.operation.DatabaseOperation; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; +import java.util.ArrayList; +import java.util.List; +import org.junit.Rule; import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.config.Settings; -import org.sonar.db.deprecated.NullQueue; -import org.sonar.db.dialect.MySql; +import org.sonar.api.utils.System2; import org.sonar.test.DbTests; -import static org.junit.Assert.fail; - /** * @deprecated use an instance of {@link DbTester instead} instead, * and do no forget to annotated the test class with {@link org.sonar.test.DbTests}. @@ -71,130 +34,15 @@ import static org.junit.Assert.fail; @Deprecated public abstract class AbstractDaoTestCase { - private static final Logger LOG = LoggerFactory.getLogger(AbstractDaoTestCase.class); - private static Database database; - private static DatabaseCommands databaseCommands; - private static MyBatis myBatis; - private static String login; - - private IDatabaseTester databaseTester; - - @BeforeClass - public static void startDatabase() throws Exception { - if (database == null) { - Settings settings = new Settings().setProperties(Maps.fromProperties(System.getProperties())); - if (settings.hasKey("orchestrator.configUrl")) { - loadOrchestratorSettings(settings); - } - login = settings.getString("sonar.jdbc.username"); - for (String key : settings.getKeysStartingWith("sonar.jdbc")) { - LOG.info(key + ": " + settings.getString(key)); - } - boolean hasDialect = settings.hasKey("sonar.jdbc.dialect"); - if (hasDialect) { - database = new DefaultDatabase(settings); - } else { - database = new H2Database("test", true); - } - database.start(); - LOG.info("Test Database: " + database); - databaseCommands = DatabaseCommands.forDialect(database.getDialect()); - - myBatis = new MyBatis(database, new NullQueue()); - myBatis.start(); - } - } - - /** - * Orchestrator is the name of a SonarSource close-source library for database and integration testing. - */ - private static void loadOrchestratorSettings(Settings settings) throws URISyntaxException, IOException { - String url = settings.getString("orchestrator.configUrl"); - URI uri = new URI(url); - InputStream input = null; - try { - if (url.startsWith("file:")) { - File file = new File(uri); - input = FileUtils.openInputStream(file); - } else { - HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); - int responseCode = connection.getResponseCode(); - if (responseCode >= 400) { - throw new IllegalStateException("Fail to request: " + uri + ". Status code=" + responseCode); - } - - input = connection.getInputStream(); - - } - Properties props = new Properties(); - props.load(input); - settings.addProperties(props); - for (Map.Entry<String, String> entry : settings.getProperties().entrySet()) { - String interpolatedValue = StrSubstitutor.replace(entry.getValue(), System.getenv(), "${", "}"); - settings.setProperty(entry.getKey(), interpolatedValue); - } - } finally { - IOUtils.closeQuietly(input); - } - } - - private static RuntimeException translateException(String msg, Exception cause) { - RuntimeException runtimeException = new RuntimeException(String.format("%s: [%s] %s", msg, cause.getClass().getName(), cause.getMessage())); - runtimeException.setStackTrace(cause.getStackTrace()); - return runtimeException; - } - - @Before - public void startDbUnit() throws Exception { - databaseCommands.truncateDatabase(database.getDataSource()); - databaseTester = new DataSourceDatabaseTester(database.getDataSource(), databaseCommands.useLoginAsSchema() ? login : null); - } - - protected MyBatis getMyBatis() { - return myBatis; - } - - protected Database getDatabase() { - return database; - } + @Rule + public DbTester dbTester = DbTester.create(System2.INSTANCE); protected void setupData(String... testNames) { - InputStream[] streams = new InputStream[testNames.length]; - try { - for (int i = 0; i < testNames.length; i++) { - String className = getClass().getName(); - className = String.format("/%s/%s.xml", className.replace(".", "/"), testNames[i]); - streams[i] = getClass().getResourceAsStream(className); - if (streams[i] == null) { - throw new RuntimeException("Test not found :" + className); - } - } - - setupData(streams); - databaseCommands.resetPrimaryKeys(database.getDataSource()); - } catch (SQLException e) { - throw translateException("Could not setup DBUnit data", e); - } finally { - for (InputStream stream : streams) { - IOUtils.closeQuietly(stream); - } - } - } - - private void setupData(InputStream... dataSetStream) { - IDatabaseConnection connection = openDbUnitConnection(); - try { - IDataSet[] dataSets = new IDataSet[dataSetStream.length]; - for (int i = 0; i < dataSetStream.length; i++) { - dataSets[i] = getData(dataSetStream[i]); - } - databaseTester.setDataSet(new CompositeDataSet(dataSets)); - new InsertIdentityOperation(DatabaseOperation.INSERT).execute(connection, databaseTester.getDataSet()); - } catch (Exception e) { - throw translateException("Could not setup DBUnit data", e); - } finally { - closeDbUnitConnection(connection); + List<String> filenames = new ArrayList<>(); + for (String testName : testNames) { + filenames.add(testName + (testName.endsWith(".xml") ? "" : ".xml")); } + dbTester.prepareDbUnit(getClass(), filenames.toArray(new String[filenames.size()])); } protected void checkTables(String testName, String... tables) { @@ -202,107 +50,15 @@ public abstract class AbstractDaoTestCase { } protected void checkTables(String testName, String[] excludedColumnNames, String... tables) { - IDatabaseConnection connection = openDbUnitConnection(); - try { - IDataSet dataSet = connection.createDataSet(); - IDataSet expectedDataSet = getExpectedData(testName); - for (String table : tables) { - ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(dataSet.getTable(table), excludedColumnNames); - ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedDataSet.getTable(table), excludedColumnNames); - Assertion.assertEquals(filteredExpectedTable, filteredTable); - } - } catch (DatabaseUnitException e) { - fail(e.getMessage()); - } catch (SQLException e) { - throw translateException("Error while checking results", e); - } finally { - closeDbUnitConnection(connection); - } + dbTester.assertDbUnit(getClass(), testName + (testName.endsWith("-result.xml") ? "" : "-result.xml"), excludedColumnNames, tables); } protected void checkTable(String testName, String table, String... columns) { - IDatabaseConnection connection = openDbUnitConnection(); - try { - IDataSet dataSet = connection.createDataSet(); - IDataSet expectedDataSet = getExpectedData(testName); - ITable filteredTable = DefaultColumnFilter.includedColumnsTable(dataSet.getTable(table), columns); - ITable filteredExpectedTable = DefaultColumnFilter.includedColumnsTable(expectedDataSet.getTable(table), columns); - Assertion.assertEquals(filteredExpectedTable, filteredTable); - } catch (DatabaseUnitException e) { - fail(e.getMessage()); - } catch (SQLException e) { - throw translateException("Error while checking results", e); - } finally { - closeDbUnitConnection(connection); - } - } - - protected void assertEmptyTables(String... emptyTables) { - IDatabaseConnection connection = openDbUnitConnection(); - try { - IDataSet dataSet = connection.createDataSet(); - for (String table : emptyTables) { - try { - Assert.assertEquals("Table " + table + " not empty.", 0, dataSet.getTable(table).getRowCount()); - } catch (DataSetException e) { - throw translateException("Error while checking results", e); - } - } - } catch (SQLException e) { - throw translateException("Error while checking results", e); - } finally { - closeDbUnitConnection(connection); - } - } - - private IDatabaseConnection openDbUnitConnection() { - try { - IDatabaseConnection connection = databaseTester.getConnection(); - connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, databaseCommands.getDbUnitFactory()); - connection.getConfig().setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, false); - connection.getConfig().setFeature(DatabaseConfig.FEATURE_SKIP_ORACLE_RECYCLEBIN_TABLES, true); - if (MySql.ID.equals(database.getDialect().getId())) { - connection.getConfig().setProperty(DatabaseConfig.FEATURE_CASE_SENSITIVE_TABLE_NAMES, false); - connection.getConfig().setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler()); - } - return connection; - } catch (Exception e) { - throw new IllegalStateException("Fail to open dbunit connection", e); - } + dbTester.assertDbUnitTable(getClass(), testName + (testName.endsWith("-result.xml") ? "" : "-result.xml"), table, columns); } - private void closeDbUnitConnection(IDatabaseConnection c) { - try { - c.close(); - } catch (SQLException e) { - throw new IllegalStateException("Fail to close dbunit connection", e); - } - } - - private IDataSet getExpectedData(String testName) { - String className = getClass().getName(); - String fileName = String.format("/%s/%s-result.xml", className.replace('.', '/'), testName); - InputStream in = getClass().getResourceAsStream(fileName); - try { - return getData(in); - } finally { - Closeables.closeQuietly(in); - } - } - - private IDataSet getData(InputStream stream) { - try { - ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(stream)); - dataSet.addReplacementObject("[null]", null); - dataSet.addReplacementObject("[false]", Boolean.FALSE); - dataSet.addReplacementObject("[true]", Boolean.TRUE); - return dataSet; - } catch (Exception e) { - throw translateException("Could not read the dataset stream", e); - } - } - - protected Connection getConnection() throws SQLException { - return database.getDataSource().getConnection(); + @Deprecated + protected MyBatis getMyBatis() { + return dbTester.myBatis(); } } diff --git a/sonar-db/src/test/java/org/sonar/db/DatabaseUtilsTest.java b/sonar-db/src/test/java/org/sonar/db/DatabaseUtilsTest.java index 1b6acbb3eb2..9a619b36a1e 100644 --- a/sonar-db/src/test/java/org/sonar/db/DatabaseUtilsTest.java +++ b/sonar-db/src/test/java/org/sonar/db/DatabaseUtilsTest.java @@ -41,8 +41,8 @@ import static org.mockito.Mockito.verify; public class DatabaseUtilsTest extends AbstractDaoTestCase { @Test - public void should_close_connection() throws SQLException { - Connection connection = getConnection(); + public void should_close_connection() throws Exception { + Connection connection = dbTester.openConnection(); assertThat(isClosed(connection)).isFalse(); DatabaseUtils.closeQuietly(connection); @@ -56,8 +56,8 @@ public class DatabaseUtilsTest extends AbstractDaoTestCase { } @Test - public void should_close_statement_and_resultset() throws SQLException { - Connection connection = getConnection(); + public void should_close_statement_and_resultset() throws Exception { + Connection connection = dbTester.openConnection(); try { PreparedStatement statement = connection.prepareStatement(selectDual()); ResultSet rs = statement.executeQuery(); @@ -143,7 +143,7 @@ public class DatabaseUtilsTest extends AbstractDaoTestCase { private String selectDual() { String sql = "SELECT 1"; - if (Oracle.ID.equals(getDatabase().getDialect().getId())) { + if (Oracle.ID.equals(dbTester.database().getDialect().getId())) { sql = "SELECT 1 FROM DUAL"; } return sql; diff --git a/sonar-db/src/test/java/org/sonar/db/DbTester.java b/sonar-db/src/test/java/org/sonar/db/DbTester.java index dfa4e9cfef0..30bc65fa1e3 100644 --- a/sonar-db/src/test/java/org/sonar/db/DbTester.java +++ b/sonar-db/src/test/java/org/sonar/db/DbTester.java @@ -49,7 +49,6 @@ import org.dbunit.dataset.filter.DefaultColumnFilter; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.dbunit.ext.mssql.InsertIdentityOperation; import org.dbunit.operation.DatabaseOperation; -import org.junit.After; import org.junit.rules.ExternalResource; import org.picocontainer.containers.TransientPicoContainer; import org.sonar.api.utils.System2; @@ -71,7 +70,7 @@ public class DbTester extends ExternalResource { private final System2 system2; private final TestDb db; - private DbClient2 client; + private DbClient client; private DbSession session = null; @Deprecated @@ -100,11 +99,12 @@ public class DbTester extends ExternalResource { truncateTables(); } - @After - public void closeSession() throws Exception { + @Override + protected void after() { if (session != null) { MyBatis.closeQuietly(session); } + db.close(); } public DbSession getSession() { @@ -118,7 +118,7 @@ public class DbTester extends ExternalResource { db.truncateTables(); } - public DbClient2 getDbClient() { + public DbClient getDbClient() { if (client == null) { TransientPicoContainer ioc = new TransientPicoContainer(); ioc.addComponent(db.getMyBatis()); @@ -127,7 +127,7 @@ public class DbTester extends ExternalResource { ioc.addComponent(daoClass); } List<Dao> daos = ioc.getComponents(Dao.class); - client = new DbClient2(db.getMyBatis(), daos.toArray(new Dao[daos.size()])); + client = new DbClient(db.getDatabase(), db.getMyBatis(), daos.toArray(new Dao[daos.size()])); } return client; } @@ -263,6 +263,24 @@ public class DbTester extends ExternalResource { } } + public void assertDbUnitTable(Class testClass, String filename, String table, String... columns) { + IDatabaseConnection connection = dbUnitConnection(); + try { + IDataSet dataSet = connection.createDataSet(); + String path = "/" + testClass.getName().replace('.', '/') + "/" + filename; + IDataSet expectedDataSet = dbUnitDataSet(testClass.getResourceAsStream(path)); + ITable filteredTable = DefaultColumnFilter.includedColumnsTable(dataSet.getTable(table), columns); + ITable filteredExpectedTable = DefaultColumnFilter.includedColumnsTable(expectedDataSet.getTable(table), columns); + Assertion.assertEquals(filteredExpectedTable, filteredTable); + } catch (DatabaseUnitException e) { + fail(e.getMessage()); + } catch (SQLException e) { + throw translateException("Error while checking results", e); + } finally { + closeQuietly(connection); + } + } + public void assertDbUnit(Class testClass, String filename, String... tables) { assertDbUnit(testClass, filename, new String[0], tables); } @@ -372,7 +390,7 @@ public class DbTester extends ExternalResource { } } - private static RuntimeException translateException(String msg, Exception cause) { + public static RuntimeException translateException(String msg, Exception cause) { RuntimeException runtimeException = new RuntimeException(String.format("%s: [%s] %s", msg, cause.getClass().getName(), cause.getMessage())); runtimeException.setStackTrace(cause.getStackTrace()); return runtimeException; @@ -400,4 +418,9 @@ public class DbTester extends ExternalResource { public Database database() { return db.getDatabase(); } + + public DatabaseCommands getCommands() { + return db.getCommands(); + } + } diff --git a/sonar-db/src/test/java/org/sonar/db/ResultSetIteratorTest.java b/sonar-db/src/test/java/org/sonar/db/ResultSetIteratorTest.java index 970f9090fd1..4326aa15b88 100644 --- a/sonar-db/src/test/java/org/sonar/db/ResultSetIteratorTest.java +++ b/sonar-db/src/test/java/org/sonar/db/ResultSetIteratorTest.java @@ -24,9 +24,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.NoSuchElementException; -import org.apache.commons.dbutils.DbUtils; -import org.junit.After; -import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; @@ -42,107 +39,105 @@ public class ResultSetIteratorTest { @ClassRule public static DbTester dbTester = DbTester.createForSchema(System2.INSTANCE, ResultSetIteratorTest.class, "schema.sql"); - Connection connection = null; - - @Before - public void setUp() throws Exception { - connection = dbTester.openConnection(); - } - - @After - public void tearDown() { - DbUtils.closeQuietly(connection); - } - @Test public void create_iterator_from_statement() throws Exception { dbTester.prepareDbUnit(getClass(), "feed.xml"); - PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); - FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt); + try (Connection connection = dbTester.openConnection()) { + PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); + FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt); - assertThat(iterator.hasNext()).isTrue(); + assertThat(iterator.hasNext()).isTrue(); - // calling multiple times hasNext() is ok - assertThat(iterator.hasNext()).isTrue(); + // calling multiple times hasNext() is ok + assertThat(iterator.hasNext()).isTrue(); - assertThat(iterator.next()).isEqualTo(10); - assertThat(iterator.hasNext()).isTrue(); - assertThat(iterator.next()).isEqualTo(20); + assertThat(iterator.next()).isEqualTo(10); + assertThat(iterator.hasNext()).isTrue(); + assertThat(iterator.next()).isEqualTo(20); - // call next() without calling hasNext() - assertThat(iterator.next()).isEqualTo(30); - assertThat(iterator.hasNext()).isFalse(); + // call next() without calling hasNext() + assertThat(iterator.next()).isEqualTo(30); + assertThat(iterator.hasNext()).isFalse(); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException e) { - // ok - } + try { + iterator.next(); + fail(); + } catch (NoSuchElementException e) { + // ok + } - iterator.close(); - // statement is closed by ResultSetIterator - assertThat(stmt.isClosed()).isTrue(); + iterator.close(); + // statement is closed by ResultSetIterator + assertThat(stmt.isClosed()).isTrue(); + } } @Test public void iterate_empty_list() throws Exception { dbTester.prepareDbUnit(getClass(), "feed.xml"); - PreparedStatement stmt = connection.prepareStatement("select * from issues where id < 0"); - FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt); + try (Connection connection = dbTester.openConnection()) { + PreparedStatement stmt = connection.prepareStatement("select * from issues where id < 0"); + FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt); - assertThat(iterator.hasNext()).isFalse(); + assertThat(iterator.hasNext()).isFalse(); + } } @Test public void create_iterator_from_result_set() throws Exception { dbTester.prepareDbUnit(getClass(), "feed.xml"); - PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); - ResultSet rs = stmt.executeQuery(); - FirstIntColumnIterator iterator = new FirstIntColumnIterator(rs); + try (Connection connection = dbTester.openConnection()) { + PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); + ResultSet rs = stmt.executeQuery(); + FirstIntColumnIterator iterator = new FirstIntColumnIterator(rs); - assertThat(iterator.next()).isEqualTo(10); - assertThat(iterator.next()).isEqualTo(20); - assertThat(iterator.next()).isEqualTo(30); + assertThat(iterator.next()).isEqualTo(10); + assertThat(iterator.next()).isEqualTo(20); + assertThat(iterator.next()).isEqualTo(30); - iterator.close(); - assertThat(rs.isClosed()).isTrue(); - stmt.close(); + iterator.close(); + assertThat(rs.isClosed()).isTrue(); + stmt.close(); + } } @Test public void remove_row_is_not_supported() throws Exception { - PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); - FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt); - - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException ok) { - // ok + try (Connection connection = dbTester.openConnection()) { + PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); + FirstIntColumnIterator iterator = new FirstIntColumnIterator(stmt); + + try { + iterator.remove(); + fail(); + } catch (UnsupportedOperationException ok) { + // ok + } + + iterator.close(); } - - iterator.close(); } @Test public void fail_to_read_row() throws Exception { dbTester.prepareDbUnit(getClass(), "feed.xml"); - PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); - FailIterator iterator = new FailIterator(stmt); - - assertThat(iterator.hasNext()).isTrue(); - try { - iterator.next(); - fail(); - } catch (IllegalStateException e) { - assertThat(e.getCause()).isInstanceOf(SQLException.class); + try (Connection connection = dbTester.openConnection()) { + PreparedStatement stmt = connection.prepareStatement("select * from issues order by id"); + FailIterator iterator = new FailIterator(stmt); + + assertThat(iterator.hasNext()).isTrue(); + try { + iterator.next(); + fail(); + } catch (IllegalStateException e) { + assertThat(e.getCause()).isInstanceOf(SQLException.class); + } + iterator.close(); } - iterator.close(); } private static class FirstIntColumnIterator extends ResultSetIterator<Integer> { diff --git a/sonar-db/src/test/java/org/sonar/db/TestDb.java b/sonar-db/src/test/java/org/sonar/db/TestDb.java index 715ea17af6d..3ab4fc41346 100644 --- a/sonar-db/src/test/java/org/sonar/db/TestDb.java +++ b/sonar-db/src/test/java/org/sonar/db/TestDb.java @@ -60,6 +60,17 @@ class TestDb { private DatabaseCommands commands; private IDatabaseTester tester; private MyBatis myBatis; + private boolean isDefault; + + static TestDb create(@Nullable String schemaPath) { + if (schemaPath == null) { + if (DEFAULT == null) { + DEFAULT = new TestDb(null); + } + return DEFAULT; + } + return new TestDb(schemaPath); + } private TestDb(@Nullable String schemaPath) { if (db == null) { @@ -87,6 +98,7 @@ class TestDb { throw new AssumptionViolatedException("Test disabled because it supports only H2"); } } + isDefault = (schemaPath == null); LOG.info("Test Database: " + db); commands = DatabaseCommands.forDialect(db.getDialect()); @@ -105,20 +117,10 @@ class TestDb { } } - static TestDb create(@Nullable String schemaPath) { - if (schemaPath == null) { - if (DEFAULT == null) { - DEFAULT = new TestDb(null); - } - return DEFAULT; + void close() { + if (!isDefault) { + db.stop(); } - return new TestDb(schemaPath); - } - - void stop() { - db.stop(); - db = null; - myBatis = null; } Database getDatabase() { diff --git a/sonar-db/src/test/java/org/sonar/db/component/ResourceDaoTest.java b/sonar-db/src/test/java/org/sonar/db/component/ResourceDaoTest.java index a6c809330f1..0936f6c8f76 100644 --- a/sonar-db/src/test/java/org/sonar/db/component/ResourceDaoTest.java +++ b/sonar-db/src/test/java/org/sonar/db/component/ResourceDaoTest.java @@ -307,7 +307,7 @@ public class ResourceDaoTest extends AbstractDaoTestCase { session.rollback(); - assertEmptyTables("projects"); + assertThat(dbTester.countRowsOfTable("projects")).isZero(); } @Test diff --git a/sonar-db/src/test/java/org/sonar/db/component/ResourceIndexerDaoTest.java b/sonar-db/src/test/java/org/sonar/db/component/ResourceIndexDaoTest.java index deb992be365..df1195d46ff 100644 --- a/sonar-db/src/test/java/org/sonar/db/component/ResourceIndexerDaoTest.java +++ b/sonar-db/src/test/java/org/sonar/db/component/ResourceIndexDaoTest.java @@ -19,27 +19,17 @@ */ package org.sonar.db.component; -import java.sql.Connection; -import java.sql.ResultSet; import java.sql.SQLException; -import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; -import org.sonar.api.utils.System2; import org.sonar.db.AbstractDaoTestCase; import org.sonar.db.DbSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -public class ResourceIndexerDaoTest extends AbstractDaoTestCase { +public class ResourceIndexDaoTest extends AbstractDaoTestCase { - private static ResourceIndexerDao dao; - - @Before - public void createDao() { - dao = new ResourceIndexerDao(getMyBatis(), mock(System2.class)); - } + ResourceIndexDao dao = dbTester.getDbClient().componentIndexDao(); @Test public void shouldIndexResource() { @@ -82,29 +72,12 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { setupData("shouldNotIndexPackages"); dao.indexProject(1); - - Connection connection = getConnection(); - ResultSet rs = null; - try { - // project - rs = connection.createStatement().executeQuery("select count(resource_id) from resource_index where resource_id=1"); - rs.next(); - assertThat(rs.getInt(1)).isGreaterThan(0); - - // directory - rs = connection.createStatement().executeQuery("select count(resource_id) from resource_index where resource_id=2"); - rs.next(); - assertThat(rs.getInt(1)).isEqualTo(0); - - // file - rs = connection.createStatement().executeQuery("select count(resource_id) from resource_index where resource_id=3"); - rs.next(); - assertThat(rs.getInt(1)).isGreaterThan(0); - } finally { - if (null != rs) { - rs.close(); - } - } + // project + assertThat(dbTester.countSql("select count(resource_id) from resource_index where resource_id=1")).isGreaterThan(0); + // directory + assertThat(dbTester.countSql("select count(resource_id) from resource_index where resource_id=2")).isEqualTo(0); + // file + assertThat(dbTester.countSql("select count(resource_id) from resource_index where resource_id=3")).isGreaterThan(0); } @Test @@ -157,7 +130,7 @@ public class ResourceIndexerDaoTest extends AbstractDaoTestCase { setupData("select_project_ids_from_query_and_view_or_sub_view_uuid"); String viewUuid = "EFGH"; - DbSession session = getMyBatis().openSession(false); + DbSession session = dbTester.getSession(); assertThat(dao.selectProjectIdsFromQueryAndViewOrSubViewUuid(session, "project", viewUuid)).containsOnly(1L, 2L); assertThat(dao.selectProjectIdsFromQueryAndViewOrSubViewUuid(session, "one", viewUuid)).containsOnly(1L); assertThat(dao.selectProjectIdsFromQueryAndViewOrSubViewUuid(session, "two", viewUuid)).containsOnly(2L); diff --git a/sonar-db/src/test/java/org/sonar/db/issue/ActionPlanDaoTest.java b/sonar-db/src/test/java/org/sonar/db/issue/ActionPlanDaoTest.java index 939fc01ed36..85439f61db8 100644 --- a/sonar-db/src/test/java/org/sonar/db/issue/ActionPlanDaoTest.java +++ b/sonar-db/src/test/java/org/sonar/db/issue/ActionPlanDaoTest.java @@ -22,23 +22,15 @@ package org.sonar.db.issue; import java.util.Collection; import java.util.List; -import org.apache.ibatis.session.SqlSession; -import org.junit.Before; import org.junit.Test; import org.sonar.db.AbstractDaoTestCase; -import org.sonar.db.MyBatis; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; public class ActionPlanDaoTest extends AbstractDaoTestCase { - ActionPlanDao dao; - - @Before - public void createDao() { - dao = new ActionPlanDao(getMyBatis()); - } + ActionPlanDao dao = dbTester.getDbClient().actionPlanDao(); @Test public void should_insert_new_action_plan() { @@ -92,13 +84,11 @@ public class ActionPlanDaoTest extends AbstractDaoTestCase { public void should_find_by_keys_on_huge_number_of_keys() { setupData("shared"); - SqlSession session = getMyBatis().openSession(); List<String> hugeNbOKeys = newArrayList(); for (int i = 0; i < 4500; i++) { hugeNbOKeys.add("ABCD" + i); } List<ActionPlanDto> result = dao.findByKeys(hugeNbOKeys); - MyBatis.closeQuietly(session); // The goal of this test is only to check that the query do no fail, not to check the number of results assertThat(result).isEmpty(); diff --git a/sonar-db/src/test/java/org/sonar/db/purge/PurgeCommandsTest.java b/sonar-db/src/test/java/org/sonar/db/purge/PurgeCommandsTest.java index 0da36e52b04..1c6e6f67b8f 100644 --- a/sonar-db/src/test/java/org/sonar/db/purge/PurgeCommandsTest.java +++ b/sonar-db/src/test/java/org/sonar/db/purge/PurgeCommandsTest.java @@ -27,6 +27,7 @@ import org.sonar.db.AbstractDaoTestCase; import org.sonar.db.MyBatis; import static com.google.common.collect.Lists.newArrayList; +import static org.assertj.core.api.Assertions.assertThat; public class PurgeCommandsTest extends AbstractDaoTestCase { @@ -117,7 +118,12 @@ public class PurgeCommandsTest extends AbstractDaoTestCase { new PurgeCommands(session, profiler).deleteResources(newArrayList(new IdUuidPair(1L, "1"))); } - assertEmptyTables("projects", "snapshots", "events", "issues", "issue_changes", "authors"); + assertThat(dbTester.countRowsOfTable("projects")).isZero(); + assertThat(dbTester.countRowsOfTable("snapshots")).isZero(); + assertThat(dbTester.countRowsOfTable("events")).isZero(); + assertThat(dbTester.countRowsOfTable("issues")).isZero(); + assertThat(dbTester.countRowsOfTable("issue_changes")).isZero(); + assertThat(dbTester.countRowsOfTable("authors")).isZero(); } /** diff --git a/sonar-db/src/test/java/org/sonar/db/purge/PurgeDaoTest.java b/sonar-db/src/test/java/org/sonar/db/purge/PurgeDaoTest.java index 11aa33abc18..0417fb5e919 100644 --- a/sonar-db/src/test/java/org/sonar/db/purge/PurgeDaoTest.java +++ b/sonar-db/src/test/java/org/sonar/db/purge/PurgeDaoTest.java @@ -20,61 +20,46 @@ package org.sonar.db.purge; import java.util.List; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.experimental.categories.Category; import org.sonar.api.resources.Scopes; import org.sonar.api.utils.System2; -import org.sonar.db.AbstractDaoTestCase; -import org.sonar.db.DbSession; -import org.sonar.db.MyBatis; -import org.sonar.db.component.ResourceDao; +import org.sonar.db.DbTester; +import org.sonar.test.DbTests; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class PurgeDaoTest extends AbstractDaoTestCase { +@Category(DbTests.class) +public class PurgeDaoTest { - private PurgeDao sut; - private System2 system2; - private DbSession dbSession; + System2 system2 = mock(System2.class); - private static PurgeableSnapshotDto getById(List<PurgeableSnapshotDto> snapshots, long id) { - for (PurgeableSnapshotDto snapshot : snapshots) { - if (snapshot.getSnapshotId() == id) { - return snapshot; - } - } - return null; - } + @Rule + public DbTester dbTester = DbTester.create(system2); + + PurgeDao sut = dbTester.getDbClient().purgeDao(); @Before public void before() { - system2 = mock(System2.class); when(system2.now()).thenReturn(1450000000000L); - dbSession = getMyBatis().openSession(false); - - sut = new PurgeDao(getMyBatis(), new ResourceDao(getMyBatis(), system2), system2); - } - - @After - public void after() { - MyBatis.closeQuietly(dbSession); } @Test public void shouldDeleteAbortedBuilds() { - setupData("shouldDeleteAbortedBuilds"); + dbTester.prepareDbUnit(getClass(), "shouldDeleteAbortedBuilds.xml"); sut.purge(newConfigurationWith30Days(), PurgeListener.EMPTY, new PurgeProfiler()); - checkTables("shouldDeleteAbortedBuilds", "snapshots"); + dbTester.assertDbUnit(getClass(), "shouldDeleteAbortedBuilds-result.xml", "snapshots"); } @Test public void should_purge_project() { - setupData("shouldPurgeProject"); + dbTester.prepareDbUnit(getClass(), "shouldPurgeProject.xml"); sut.purge(newConfigurationWith30Days(), PurgeListener.EMPTY, new PurgeProfiler()); - checkTables("shouldPurgeProject", "projects", "snapshots"); + dbTester.assertDbUnit(getClass(), "shouldPurgeProject-result.xml", "projects", "snapshots"); } private PurgeConfiguration newConfigurationWith30Days() { @@ -87,35 +72,35 @@ public class PurgeDaoTest extends AbstractDaoTestCase { @Test public void delete_file_sources_of_disabled_resources() { - setupData("delete_file_sources_of_disabled_resources"); + dbTester.prepareDbUnit(getClass(), "delete_file_sources_of_disabled_resources.xml"); sut.purge(newConfigurationWith30Days(system2), PurgeListener.EMPTY, new PurgeProfiler()); - checkTables("delete_file_sources_of_disabled_resources", "file_sources"); + dbTester.assertDbUnit(getClass(), "delete_file_sources_of_disabled_resources-result.xml", "file_sources"); } @Test public void shouldDeleteHistoricalDataOfDirectoriesAndFiles() { - setupData("shouldDeleteHistoricalDataOfDirectoriesAndFiles"); + dbTester.prepareDbUnit(getClass(), "shouldDeleteHistoricalDataOfDirectoriesAndFiles.xml"); sut.purge(new PurgeConfiguration(new IdUuidPair(1L, "1"), new String[] {Scopes.DIRECTORY, Scopes.FILE}, 30), PurgeListener.EMPTY, new PurgeProfiler()); - checkTables("shouldDeleteHistoricalDataOfDirectoriesAndFiles", "projects", "snapshots"); + dbTester.assertDbUnit(getClass(), "shouldDeleteHistoricalDataOfDirectoriesAndFiles-result.xml", "projects", "snapshots"); } @Test public void disable_resources_without_last_snapshot() { - setupData("disable_resources_without_last_snapshot"); + dbTester.prepareDbUnit(getClass(), "disable_resources_without_last_snapshot.xml"); sut.purge(newConfigurationWith30Days(system2), PurgeListener.EMPTY, new PurgeProfiler()); - checkTables("disable_resources_without_last_snapshot", new String[] {"issue_close_date", "issue_update_date"}, "projects", "snapshots", "issues"); + dbTester.assertDbUnit(getClass(), "disable_resources_without_last_snapshot-result.xml", new String[]{"issue_close_date", "issue_update_date"}, "projects", "snapshots", "issues"); } @Test public void shouldDeleteSnapshots() { - setupData("shouldDeleteSnapshots"); + dbTester.prepareDbUnit(getClass(), "shouldDeleteSnapshots.xml"); sut.deleteSnapshots(PurgeSnapshotQuery.create().setIslast(false).setResourceId(1L), new PurgeProfiler()); - checkTables("shouldDeleteSnapshots", "snapshots"); + dbTester.assertDbUnit(getClass(), "shouldDeleteSnapshots-result.xml", "snapshots"); } @Test public void shouldSelectPurgeableSnapshots() { - setupData("shouldSelectPurgeableSnapshots"); + dbTester.prepareDbUnit(getClass(), "shouldSelectPurgeableSnapshots.xml"); List<PurgeableSnapshotDto> snapshots = sut.selectPurgeableSnapshots(1L); assertThat(snapshots).hasSize(3); @@ -129,31 +114,45 @@ public class PurgeDaoTest extends AbstractDaoTestCase { @Test public void should_delete_project_and_associated_data() { - setupData("shouldDeleteProject"); + dbTester.prepareDbUnit(getClass(), "shouldDeleteProject.xml"); sut.deleteResourceTree(new IdUuidPair(1L, "A"), new PurgeProfiler()); - assertEmptyTables("projects", "snapshots", "action_plans", "issues", "issue_changes", "file_sources"); + assertThat(dbTester.countRowsOfTable("projects")).isZero(); + assertThat(dbTester.countRowsOfTable("snapshots")).isZero(); + assertThat(dbTester.countRowsOfTable("action_plans")).isZero(); + assertThat(dbTester.countRowsOfTable("issues")).isZero(); + assertThat(dbTester.countRowsOfTable("issue_changes")).isZero(); + assertThat(dbTester.countRowsOfTable("file_sources")).isZero(); } @Test public void should_delete_old_closed_issues() { - setupData("should_delete_old_closed_issues"); + dbTester.prepareDbUnit(getClass(), "should_delete_old_closed_issues.xml"); sut.purge(newConfigurationWith30Days(), PurgeListener.EMPTY, new PurgeProfiler()); - checkTables("should_delete_old_closed_issues", "issues", "issue_changes"); + dbTester.assertDbUnit(getClass(), "should_delete_old_closed_issues-result.xml", "issues", "issue_changes"); } @Test public void should_delete_all_closed_issues() { - setupData("should_delete_all_closed_issues"); + dbTester.prepareDbUnit(getClass(), "should_delete_all_closed_issues.xml"); sut.purge(new PurgeConfiguration(new IdUuidPair(1L, "1"), new String[0], 0), PurgeListener.EMPTY, new PurgeProfiler()); - checkTables("should_delete_all_closed_issues", "issues", "issue_changes"); + dbTester.assertDbUnit(getClass(), "should_delete_all_closed_issues-result.xml", "issues", "issue_changes"); } @Test public void select_purgeable_file_uuids_and_only_them() { - setupData("select_purgeable_file_uuids"); + dbTester.prepareDbUnit(getClass(), "select_purgeable_file_uuids.xml"); - List<String> uuids = sut.selectPurgeableFiles(dbSession, 1L); + List<String> uuids = sut.selectPurgeableFiles(dbTester.getSession(), 1L); assertThat(uuids).containsOnly("GHIJ"); } + + private static PurgeableSnapshotDto getById(List<PurgeableSnapshotDto> snapshots, long id) { + for (PurgeableSnapshotDto snapshot : snapshots) { + if (snapshot.getSnapshotId() == id) { + return snapshot; + } + } + return null; + } } diff --git a/sonar-db/src/test/java/org/sonar/db/qualitygate/QualityGateConditionDaoTest.java b/sonar-db/src/test/java/org/sonar/db/qualitygate/QualityGateConditionDaoTest.java index 8e2840e09df..daa5b1d5777 100644 --- a/sonar-db/src/test/java/org/sonar/db/qualitygate/QualityGateConditionDaoTest.java +++ b/sonar-db/src/test/java/org/sonar/db/qualitygate/QualityGateConditionDaoTest.java @@ -31,16 +31,11 @@ public class QualityGateConditionDaoTest extends AbstractDaoTestCase { "id", "qgate_id", "metric_id", "operator", "value_warning", "value_error", "period" }; - private static QualityGateConditionDao dao; - - @Before - public void createDao() { - dao = new QualityGateConditionDao(getMyBatis()); - } + QualityGateConditionDao dao = dbTester.getDbClient().gateConditionDao(); @Test public void testInsert() throws Exception { - setupData("insert"); + setupData("insert.xml"); QualityGateConditionDto newCondition = new QualityGateConditionDto() .setQualityGateId(1L).setMetricId(2L).setOperator("GT").setWarningThreshold("10").setErrorThreshold("20").setPeriod(3); dao.insert(newCondition); @@ -50,14 +45,14 @@ public class QualityGateConditionDaoTest extends AbstractDaoTestCase { @Test public void testSelectForQualityGate() throws Exception { - setupData("selectForQualityGate"); + setupData("selectForQualityGate.xml"); assertThat(dao.selectForQualityGate(1L)).hasSize(3); assertThat(dao.selectForQualityGate(2L)).hasSize(2); } @Test public void testSelectById() throws Exception { - setupData("selectForQualityGate"); + setupData("selectForQualityGate.xml"); QualityGateConditionDto selectById = dao.selectById(1L); assertThat(selectById).isNotNull(); assertThat(selectById.getId()).isNotNull().isNotEqualTo(0L); @@ -72,21 +67,22 @@ public class QualityGateConditionDaoTest extends AbstractDaoTestCase { @Test public void testDelete() throws Exception { - setupData("selectForQualityGate"); + setupData("selectForQualityGate.xml"); dao.delete(new QualityGateConditionDto().setId(1L)); checkTable("delete", "quality_gate_conditions", COLUMNS_WITHOUT_TIMESTAMPS); } @Test public void testUpdate() throws Exception { - setupData("selectForQualityGate"); + setupData("selectForQualityGate.xml"); dao.update(new QualityGateConditionDto().setId(1L).setMetricId(7L).setOperator(">").setPeriod(1).setWarningThreshold("50").setErrorThreshold("80")); - checkTable("update", "quality_gate_conditions", COLUMNS_WITHOUT_TIMESTAMPS); + checkTable("update-result.xml", "quality_gate_conditions", COLUMNS_WITHOUT_TIMESTAMPS); } + @Test public void shouldCleanConditions() { - setupData("shouldCleanConditions"); + setupData("shouldCleanConditions.xml"); dao.deleteConditionsWithInvalidMetrics(); - checkTables("shouldCleanConditions", "quality_gate_conditions"); + checkTables("shouldCleanConditions-result.xml", new String[]{"created_at", "updated_at"}, "quality_gate_conditions"); } } diff --git a/sonar-db/src/test/java/org/sonar/db/user/AuthorDaoTest.java b/sonar-db/src/test/java/org/sonar/db/user/AuthorDaoTest.java index 9cda23c3417..4c845c60381 100644 --- a/sonar-db/src/test/java/org/sonar/db/user/AuthorDaoTest.java +++ b/sonar-db/src/test/java/org/sonar/db/user/AuthorDaoTest.java @@ -19,11 +19,8 @@ */ package org.sonar.db.user; -import org.junit.Before; import org.junit.Test; -import org.sonar.api.utils.System2; import org.sonar.db.AbstractDaoTestCase; -import org.sonar.db.component.ResourceDao; import org.sonar.db.component.ResourceDto; import static org.assertj.core.api.Assertions.assertThat; @@ -31,12 +28,7 @@ import static org.junit.Assert.fail; public class AuthorDaoTest extends AbstractDaoTestCase { - private AuthorDao dao; - - @Before - public void setUp() { - dao = new AuthorDao(getMyBatis(), new ResourceDao(getMyBatis(), System2.INSTANCE)); - } + AuthorDao dao = dbTester.getDbClient().authorDao(); @Test public void shouldSelectByLogin() { diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/select_project_ids_from_query_and_view_or_sub_view_uuid.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/select_project_ids_from_query_and_view_or_sub_view_uuid.xml index aff69473ce1..aff69473ce1 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/select_project_ids_from_query_and_view_or_sub_view_uuid.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/select_project_ids_from_query_and_view_or_sub_view_uuid.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexMultiModulesProject-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexMultiModulesProject-result.xml index 48899d945c3..48899d945c3 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexMultiModulesProject-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexMultiModulesProject-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexMultiModulesProject.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexMultiModulesProject.xml index a1cd4ef6f5a..a1cd4ef6f5a 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexMultiModulesProject.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexMultiModulesProject.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexProjects-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexProjects-result.xml index ee9ab480a7c..ee9ab480a7c 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexProjects-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexProjects-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexProjects.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexProjects.xml index 0043b4ced0b..0043b4ced0b 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexProjects.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexProjects.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexResource-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexResource-result.xml index f4cf0805ede..f4cf0805ede 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexResource-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexResource-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexResource.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexResource.xml index 5a4a28b7df3..5a4a28b7df3 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexResource.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexResource.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexTwoLettersLongResource-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexTwoLettersLongResource-result.xml index c9941e492bd..c9941e492bd 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexTwoLettersLongResource-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexTwoLettersLongResource-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexTwoLettersLongResource.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexTwoLettersLongResource.xml index 5a4a28b7df3..5a4a28b7df3 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldIndexTwoLettersLongResource.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldIndexTwoLettersLongResource.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldNotIndexPackages.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldNotIndexPackages.xml index 0043b4ced0b..0043b4ced0b 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldNotIndexPackages.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldNotIndexPackages.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldNotReindexUnchangedResource-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldNotReindexUnchangedResource-result.xml index 4292af5708d..4292af5708d 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldNotReindexUnchangedResource-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldNotReindexUnchangedResource-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldNotReindexUnchangedResource.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldNotReindexUnchangedResource.xml index 89a3a8c465d..89a3a8c465d 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldNotReindexUnchangedResource.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldNotReindexUnchangedResource.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexNewTwoLettersLongResource-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexNewTwoLettersLongResource-result.xml index 52db35f3ad4..52db35f3ad4 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexNewTwoLettersLongResource-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexNewTwoLettersLongResource-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexNewTwoLettersLongResource.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexNewTwoLettersLongResource.xml index af5863edbda..af5863edbda 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexNewTwoLettersLongResource.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexNewTwoLettersLongResource.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexTwoLettersLongResource-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexTwoLettersLongResource-result.xml index 52db35f3ad4..52db35f3ad4 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexTwoLettersLongResource-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexTwoLettersLongResource-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexTwoLettersLongResource.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexTwoLettersLongResource.xml index 529e83c1a44..529e83c1a44 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReIndexTwoLettersLongResource.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReIndexTwoLettersLongResource.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexProjectAfterRenaming-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexProjectAfterRenaming-result.xml index e28b5945816..e28b5945816 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexProjectAfterRenaming-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexProjectAfterRenaming-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexProjectAfterRenaming.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexProjectAfterRenaming.xml index 84815e52e64..84815e52e64 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexProjectAfterRenaming.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexProjectAfterRenaming.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexResource-result.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexResource-result.xml index b9f39157aea..b9f39157aea 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexResource-result.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexResource-result.xml diff --git a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexResource.xml b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexResource.xml index 89a3a8c465d..89a3a8c465d 100644 --- a/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexerDaoTest/shouldReindexResource.xml +++ b/sonar-db/src/test/resources/org/sonar/db/component/ResourceIndexDaoTest/shouldReindexResource.xml |