repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.ce;
import java.util.stream.Stream;
import org.sonar.db.DbSession;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS;
import static org.sonar.db.ce.CeQueueDto.Status.PENDING;
public class CeQueueTesting {
private CeQueueTesting() {
// static methods only
}
public static CeQueueDto newCeQueueDto(String uuid) {
return new CeQueueDto()
.setUuid(uuid)
.setComponentUuid(randomAlphanumeric(40))
.setEntityUuid(randomAlphanumeric(39))
.setStatus(CeQueueDto.Status.PENDING)
.setTaskType(CeTaskTypes.REPORT)
.setSubmitterUuid(randomAlphanumeric(255))
.setCreatedAt(nextLong())
.setUpdatedAt(nextLong());
}
public static void makeInProgress(DbSession dbSession, String workerUuid, long now, CeQueueDto... ceQueueDtos) {
Stream.of(ceQueueDtos).forEach(ceQueueDto -> {
CeQueueMapper mapper = dbSession.getMapper(CeQueueMapper.class);
int touchedRows = mapper.updateIf(ceQueueDto.getUuid(),
new UpdateIf.NewProperties(IN_PROGRESS, workerUuid, now, now),
new UpdateIf.OldProperties(PENDING));
assertThat(touchedRows).isOne();
});
}
public static void reset(DbSession dbSession, long now, CeQueueDto... ceQueueDtos) {
Stream.of(ceQueueDtos).forEach(ceQueueDto -> {
checkArgument(ceQueueDto.getStatus() == IN_PROGRESS);
checkArgument(ceQueueDto.getWorkerUuid() != null);
CeQueueMapper mapper = dbSession.getMapper(CeQueueMapper.class);
int touchedRows = mapper.updateIf(ceQueueDto.getUuid(),
new UpdateIf.NewProperties(PENDING, ceQueueDto.getUuid(), now, now),
new UpdateIf.OldProperties(IN_PROGRESS));
assertThat(touchedRows).isOne();
});
}
}
| 2,845 | 38.527778 | 114 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.portfolio.PortfolioDto;
import org.sonar.db.portfolio.PortfolioProjectDto;
import org.sonar.db.project.ProjectDto;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Arrays.asList;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.SUBVIEW;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.db.portfolio.PortfolioDto.SelectionMode.NONE;
public class ComponentDbTester {
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public ComponentDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public SnapshotDto insertProjectAndSnapshot(ComponentDto component) {
insertComponentAndBranchAndProject(component, null, defaults(), defaults(), defaults());
return insertSnapshot(component);
}
public ProjectData insertProjectDataAndSnapshot(ComponentDto component) {
ProjectData projectData = insertComponentAndBranchAndProject(component, null, defaults(), defaults(), defaults());
insertSnapshot(component);
return projectData;
}
public SnapshotDto insertPortfolioAndSnapshot(ComponentDto component) {
dbClient.componentDao().insert(dbSession, component, true);
return insertSnapshot(component);
}
public ComponentDto insertComponent(ComponentDto component) {
return insertComponentImpl(component, null, defaults());
}
public ProjectData insertPrivateProject() {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(), true,
defaults(), defaults(), defaults());
}
public BranchDto getBranchDto(ComponentDto branch) {
return db.getDbClient().branchDao().selectByUuid(dbSession, branch.uuid())
.orElseThrow(() -> new IllegalStateException("Project has invalid configuration"));
}
public ProjectDto getProjectDtoByMainBranch(ComponentDto mainBranch) {
return db.getDbClient().projectDao().selectByBranchUuid(dbSession, mainBranch.uuid())
.orElseThrow(() -> new IllegalStateException("Project has invalid configuration"));
}
public ComponentDto getComponentDto(ProjectDto project) {
BranchDto branchDto = db.getDbClient().branchDao().selectMainBranchByProjectUuid(dbSession, project.getUuid()).get();
return db.getDbClient().componentDao().selectByUuid(dbSession, branchDto.getUuid())
.orElseThrow(() -> new IllegalStateException("Can't find project"));
}
public ComponentDto getComponentDto(BranchDto branch) {
return db.getDbClient().componentDao().selectByUuid(dbSession, branch.getUuid())
.orElseThrow(() -> new IllegalStateException("Can't find branch"));
}
public ProjectData insertPrivateProject(ComponentDto componentDto) {
return insertComponentAndBranchAndProject(componentDto, true);
}
public ProjectData insertPublicProject() {
return insertComponentAndBranchAndProject(ComponentTesting.newPublicProjectDto(), false);
}
public ProjectData insertPublicProject(String uuid) {
return insertComponentAndBranchAndProject(ComponentTesting.newPublicProjectDto(), false, defaults(), defaults(), p -> p.setUuid(uuid));
}
public ProjectData insertPublicProject(String uuid, Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPublicProjectDto(), false, defaults(), dtoPopulator, p -> p.setUuid(uuid));
}
public ProjectData insertPublicProject(ComponentDto componentDto) {
return insertComponentAndBranchAndProject(componentDto, false);
}
public ProjectData insertPrivateProject(String projectUuid) {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(), true, defaults(), defaults(), p -> p.setUuid(projectUuid));
}
public ProjectData insertPrivateProject(String projectUuid, ComponentDto mainBranch) {
return insertComponentAndBranchAndProject(mainBranch, true, defaults(), defaults(), p -> p.setUuid(projectUuid));
}
public final ProjectData insertPrivateProject(Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(), true, defaults(), dtoPopulator);
}
public final ProjectData insertPrivateProject(Consumer<ComponentDto> componentDtoPopulator, Consumer<ProjectDto> projectDtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(),
true, defaults(), componentDtoPopulator, projectDtoPopulator);
}
public final ProjectData insertPublicProject(Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPublicProjectDto(), false, defaults(), dtoPopulator);
}
public final ProjectData insertPublicProject(Consumer<ComponentDto> componentDtoPopulator, Consumer<ProjectDto> projectDtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPublicProjectDto(), false, defaults(), componentDtoPopulator, projectDtoPopulator);
}
public ProjectData insertPrivateProject(Consumer<BranchDto> branchPopulator, Consumer<ComponentDto> componentDtoPopulator, Consumer<ProjectDto> projectDtoPopulator) {
return insertPrivateProjectWithCustomBranch(branchPopulator, componentDtoPopulator, projectDtoPopulator);
}
public final ComponentDto insertFile(BranchDto branch) {
ComponentDto projectComponent = getComponentDto(branch);
return insertComponent(ComponentTesting.newFileDto(projectComponent));
}
public final ProjectData insertPrivateProject(String uuid, Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(), true, defaults(), dtoPopulator, p -> p.setUuid(uuid));
}
public final ProjectData insertPrivateProjectWithCustomBranch(String branchKey) {
return insertPrivateProjectWithCustomBranch(b -> b.setBranchType(BRANCH).setKey(branchKey), defaults());
}
public final ProjectData insertPrivateProjectWithCustomBranch(Consumer<BranchDto> branchPopulator, Consumer<ComponentDto> componentPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(), true, branchPopulator, componentPopulator);
}
public final ProjectData insertPublicProjectWithCustomBranch(Consumer<BranchDto> branchPopulator, Consumer<ComponentDto> componentPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPublicProjectDto(), false, branchPopulator, componentPopulator);
}
public final ProjectData insertPrivateProjectWithCustomBranch(Consumer<BranchDto> branchPopulator, Consumer<ComponentDto> componentPopulator,
Consumer<ProjectDto> projectPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(), true, branchPopulator, componentPopulator, projectPopulator);
}
public final ComponentDto insertPublicPortfolio() {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(false), false, defaults(), defaults());
}
public final ComponentDto insertPublicPortfolio(String uuid, Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio(uuid).setPrivate(false), false, dtoPopulator, defaults());
}
public final ComponentDto insertPublicPortfolio(Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(false), false, dtoPopulator, defaults());
}
public final ComponentDto insertPublicPortfolio(Consumer<ComponentDto> dtoPopulator, Consumer<PortfolioDto> portfolioPopulator) {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(false), false, dtoPopulator, portfolioPopulator);
}
public final PortfolioDto insertPublicPortfolioDto() {
return insertPublicPortfolioDto(defaults());
}
public final PortfolioDto insertPublicPortfolioDto(Consumer<ComponentDto> dtoPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(false), false, dtoPopulator, defaults());
return getPortfolioDto(component);
}
public final PortfolioDto insertPrivatePortfolioDto(String uuid) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio(uuid).setPrivate(true), true, defaults(), defaults());
return getPortfolioDto(component);
}
public final PortfolioDto insertPrivatePortfolioDto(String uuid, Consumer<PortfolioDto> portfolioPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio(uuid).setPrivate(true), true, defaults(), portfolioPopulator);
return getPortfolioDto(component);
}
public final PortfolioDto insertPrivatePortfolioDto() {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, defaults(), defaults());
return getPortfolioDto(component);
}
public final PortfolioData insertPrivatePortfolioData() {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, defaults(), defaults());
PortfolioDto portfolioDto = getPortfolioDto(component);
return new PortfolioData(portfolioDto, component);
}
public final PortfolioData insertPrivatePortfolioData(Consumer<ComponentDto> dtoPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, dtoPopulator, defaults());
PortfolioDto portfolioDto = getPortfolioDto(component);
return new PortfolioData(portfolioDto, component);
}
public final PortfolioDto insertPrivatePortfolioDto(Consumer<ComponentDto> dtoPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, dtoPopulator, defaults());
return getPortfolioDto(component);
}
public final PortfolioDto insertPrivatePortfolioDto(Consumer<ComponentDto> dtoPopulator, Consumer<PortfolioDto> portfolioPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, dtoPopulator, portfolioPopulator);
return getPortfolioDto(component);
}
public final PortfolioDto insertPublicPortfolioDto(String uuid, Consumer<ComponentDto> dtoPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio(uuid).setPrivate(false), false, dtoPopulator, defaults());
return getPortfolioDto(component);
}
public final PortfolioDto insertPublicPortfolioDto(String uuid, Consumer<ComponentDto> dtoPopulator, Consumer<PortfolioDto> portfolioPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio(uuid).setPrivate(false), false, dtoPopulator, portfolioPopulator);
return getPortfolioDto(component);
}
public final PortfolioDto insertPublicPortfolioDto(Consumer<ComponentDto> dtoPopulator, Consumer<PortfolioDto> portfolioPopulator) {
ComponentDto component = insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(false), false, dtoPopulator, portfolioPopulator);
return getPortfolioDto(component);
}
public PortfolioDto getPortfolioDto(ComponentDto portfolio) {
return db.getDbClient().portfolioDao().selectByUuid(dbSession, portfolio.uuid())
.orElseThrow(() -> new IllegalStateException("Portfolio has invalid configuration"));
}
public ComponentDto insertComponentAndPortfolio(ComponentDto componentDto, boolean isPrivate, Consumer<ComponentDto> componentPopulator,
Consumer<PortfolioDto> portfolioPopulator) {
insertComponentImpl(componentDto, isPrivate, componentPopulator);
PortfolioDto portfolioDto = toPortfolioDto(componentDto, System2.INSTANCE.now());
portfolioPopulator.accept(portfolioDto);
dbClient.portfolioDao().insert(dbSession, portfolioDto);
db.commit();
return componentDto;
}
public final ComponentDto insertPrivatePortfolio() {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, defaults(), defaults());
}
public final ComponentDto insertPrivatePortfolio(String uuid, Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio(uuid).setPrivate(true), true, dtoPopulator, defaults());
}
public final ComponentDto insertPrivatePortfolio(Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, dtoPopulator, defaults());
}
public final ComponentDto insertPrivatePortfolio(Consumer<ComponentDto> dtoPopulator, Consumer<PortfolioDto> portfolioPopulator) {
return insertComponentAndPortfolio(ComponentTesting.newPortfolio().setPrivate(true), true, dtoPopulator, portfolioPopulator);
}
public final ComponentDto insertSubportfolio(ComponentDto parentPortfolio) {
return insertSubportfolio(parentPortfolio, defaults());
}
public final ComponentDto insertSubportfolio(ComponentDto parentPortfolio, Consumer<ComponentDto> consumer) {
ComponentDto subPortfolioComponent = ComponentTesting.newSubPortfolio(parentPortfolio).setPrivate(true);
return insertComponentAndPortfolio(subPortfolioComponent, true, consumer, sp -> sp.setParentUuid(sp.getRootUuid()));
}
public void addPortfolioReference(String portfolioUuid, String... referencerUuids) {
for (String uuid : referencerUuids) {
EntityDto entityDto = dbClient.entityDao().selectByUuid(dbSession, uuid)
.orElseThrow();
switch (entityDto.getQualifier()) {
case APP -> {
BranchDto appMainBranch = dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, entityDto.getUuid())
.orElseThrow();
dbClient.portfolioDao().addReferenceBranch(dbSession, portfolioUuid, uuid, appMainBranch.getUuid());
}
case VIEW, SUBVIEW -> dbClient.portfolioDao().addReference(dbSession, portfolioUuid, uuid);
default -> throw new IllegalStateException("Unexpected value: " + entityDto.getQualifier());
}
}
db.commit();
}
public void addPortfolioReference(ComponentDto portfolio, String... referencerUuids) {
addPortfolioReference(portfolio.uuid(), referencerUuids);
}
public void addPortfolioReference(PortfolioDto portfolio, String... referencerUuids) {
addPortfolioReference(portfolio.getUuid(), referencerUuids);
}
public void addPortfolioReference(PortfolioDto portfolio, PortfolioDto reference) {
addPortfolioReference(portfolio.getUuid(), reference.getUuid());
}
public void addPortfolioProject(String portfolioUuid, String... projectUuids) {
for (String uuid : projectUuids) {
dbClient.portfolioDao().addProject(dbSession, portfolioUuid, uuid);
}
db.commit();
}
public void addPortfolioProject(ComponentDto portfolio, String... projectUuids) {
addPortfolioProject(portfolio.uuid(), projectUuids);
}
public void addPortfolioProject(ComponentDto portfolio, ProjectDto... projects) {
for (ProjectDto project : projects) {
dbClient.portfolioDao().addProject(dbSession, portfolio.uuid(), project.getUuid());
}
db.commit();
}
public void addPortfolioProject(ComponentDto portfolio, ComponentDto... mainBranches) {
List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(db.getSession(), Arrays.stream(mainBranches).map(ComponentDto::uuid).toList());
addPortfolioProject(portfolio, branchDtos.stream().map(BranchDto::getProjectUuid).toArray(String[]::new));
}
public void addPortfolioProject(PortfolioDto portfolioDto, ProjectDto... projects) {
for (ProjectDto project : projects) {
dbClient.portfolioDao().addProject(dbSession, portfolioDto.getUuid(), project.getUuid());
}
db.commit();
}
public void addPortfolioProjectBranch(PortfolioDto portfolio, ProjectDto project, String branchUuid) {
addPortfolioProjectBranch(portfolio, project.getUuid(), branchUuid);
}
public void addPortfolioProjectBranch(PortfolioDto portfolio, String projectUuid, String branchUuid) {
addPortfolioProjectBranch(portfolio.getUuid(), projectUuid, branchUuid);
}
public void addPortfolioProjectBranch(String portfolioUuid, String projectUuid, String branchUuid) {
PortfolioProjectDto portfolioProject = dbClient.portfolioDao().selectPortfolioProjectOrFail(dbSession, portfolioUuid, projectUuid);
dbClient.portfolioDao().addBranch(db.getSession(), portfolioProject.getUuid(), branchUuid);
db.commit();
}
public final ProjectData insertPublicApplication() {
return insertPublicApplication(defaults());
}
public final ProjectData insertPublicApplication(Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newApplication().setPrivate(false), false, defaults(), dtoPopulator);
}
public final ProjectData insertPrivateApplication(String uuid, Consumer<ComponentDto> dtoPopulator) {
return insertPrivateApplication(dtoPopulator, p -> p.setUuid(uuid));
}
public final ProjectData insertPrivateApplication(String uuid) {
return insertPrivateApplication(defaults(), p -> p.setUuid(uuid));
}
public final ProjectData insertPrivateApplication(Consumer<ComponentDto> dtoPopulator) {
return insertPrivateApplication(dtoPopulator, defaults());
}
public final ProjectData insertPrivateApplication() {
return insertPrivateApplication(defaults(), defaults());
}
public final ProjectData insertPrivateApplication(Consumer<ComponentDto> dtoPopulator, Consumer<ProjectDto> projectPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newApplication().setPrivate(true), true, defaults(), dtoPopulator, projectPopulator);
}
public final ComponentDto insertSubView(ComponentDto view) {
return insertSubView(view, defaults());
}
public final ComponentDto insertSubView(ComponentDto view, Consumer<ComponentDto> dtoPopulator) {
ComponentDto subViewComponent = ComponentTesting.newSubPortfolio(view);
return insertComponentAndPortfolio(subViewComponent, view.isPrivate(), dtoPopulator, p -> p.setParentUuid(view.uuid()));
}
public void addPortfolioApplicationBranch(String portfolioUuid, String applicationUuid, String branchUuid) {
dbClient.portfolioDao().addReferenceBranch(db.getSession(), portfolioUuid, applicationUuid, branchUuid);
db.commit();
}
private ProjectData insertComponentAndBranchAndProject(ComponentDto component, @Nullable Boolean isPrivate, Consumer<BranchDto> branchPopulator,
Consumer<ComponentDto> componentDtoPopulator, Consumer<ProjectDto> projectDtoPopulator) {
insertComponentImpl(component, isPrivate, componentDtoPopulator);
ProjectDto projectDto = toProjectDto(component, System2.INSTANCE.now());
projectDtoPopulator.accept(projectDto);
dbClient.projectDao().insert(dbSession, projectDto);
BranchDto branchDto = ComponentTesting.newMainBranchDto(component, projectDto.getUuid());
branchDto.setExcludeFromPurge(true);
branchPopulator.accept(branchDto);
branchDto.setIsMain(true);
dbClient.branchDao().insert(dbSession, branchDto);
db.commit();
return new ProjectData(getProjectDtoByMainBranch(component), branchDto, component);
}
public void addApplicationProject(ProjectDto application, ProjectDto... projects) {
for (ProjectDto project : projects) {
dbClient.applicationProjectsDao().addProject(dbSession, application.getUuid(), project.getUuid());
}
db.commit();
}
public void addApplicationProject(ProjectData application, ProjectData... projects) {
for (ProjectData project : projects) {
dbClient.applicationProjectsDao().addProject(dbSession, application.getProjectDto().getUuid(), project.getProjectDto().getUuid());
}
db.commit();
}
public void addProjectBranchToApplicationBranch(ComponentDto applicationBranchComponent, ComponentDto... projectBranchesComponent) {
BranchDto applicationBranch = getBranchDto(applicationBranchComponent);
BranchDto[] componentDtos = Arrays.stream(projectBranchesComponent).map(this::getBranchDto).toArray(BranchDto[]::new);
addProjectBranchToApplicationBranch(applicationBranch, componentDtos);
}
public void addProjectBranchToApplicationBranch(BranchDto applicationBranch, BranchDto... projectBranches) {
for (BranchDto projectBranch : projectBranches) {
dbClient.applicationProjectsDao().addProjectBranchToAppBranch(dbSession, applicationBranch, projectBranch);
}
db.commit();
}
private ProjectData insertComponentAndBranchAndProject(ComponentDto component, @Nullable Boolean isPrivate, Consumer<BranchDto> branchPopulator,
Consumer<ComponentDto> componentDtoPopulator) {
return insertComponentAndBranchAndProject(component, isPrivate, branchPopulator, componentDtoPopulator, defaults());
}
private ProjectData insertComponentAndBranchAndProject(ComponentDto component, @Nullable Boolean isPrivate, Consumer<BranchDto> branchPopulator) {
return insertComponentAndBranchAndProject(component, isPrivate, branchPopulator, defaults());
}
private ProjectData insertComponentAndBranchAndProject(ComponentDto component, @Nullable Boolean isPrivate) {
return insertComponentAndBranchAndProject(component, isPrivate, defaults());
}
private ComponentDto insertComponentImpl(ComponentDto component, @Nullable Boolean isPrivate, Consumer<ComponentDto> dtoPopulator) {
dtoPopulator.accept(component);
checkState(isPrivate == null || component.isPrivate() == isPrivate, "Illegal modification of private flag");
dbClient.componentDao().insert(dbSession, component, true);
db.commit();
return component;
}
public void insertComponents(ComponentDto... components) {
dbClient.componentDao().insert(dbSession, asList(components), true);
db.commit();
}
public SnapshotDto insertSnapshot(SnapshotDto snapshotDto) {
SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, snapshotDto);
db.commit();
return snapshot;
}
public SnapshotDto insertSnapshot(ComponentDto componentDto) {
return insertSnapshot(componentDto, defaults());
}
public SnapshotDto insertSnapshot(ComponentDto componentDto, Consumer<SnapshotDto> consumer) {
SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(componentDto);
consumer.accept(snapshotDto);
return insertSnapshot(snapshotDto);
}
public SnapshotDto insertSnapshot(BranchDto branchDto) {
return insertSnapshot(branchDto, defaults());
}
public SnapshotDto insertSnapshot(ProjectDto project) {
return insertSnapshot(project, defaults());
}
public SnapshotDto insertSnapshot(ProjectData project, Consumer<SnapshotDto> consumer) {
return insertSnapshot(project.getMainBranchDto(), consumer);
}
/**
* Add a snapshot to the main branch of a project
* Should use insertSnapshot(org.sonar.db.component.BranchDto, java.util.function.Consumer<org.sonar.db.component.SnapshotDto>) instead
*/
@Deprecated
public SnapshotDto insertSnapshot(ProjectDto project, Consumer<SnapshotDto> consumer) {
BranchDto mainBranchDto = db.getDbClient().branchDao().selectMainBranchByProjectUuid(dbSession, project.getUuid()).orElseThrow();
SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(mainBranchDto.getUuid());
consumer.accept(snapshotDto);
return insertSnapshot(snapshotDto);
}
public SnapshotDto insertSnapshot(PortfolioDto portfolio) {
SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(portfolio.getUuid());
return insertSnapshot(snapshotDto);
}
public SnapshotDto insertSnapshot(BranchDto branchDto, Consumer<SnapshotDto> consumer) {
SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(branchDto);
consumer.accept(snapshotDto);
return insertSnapshot(snapshotDto);
}
public void insertSnapshots(SnapshotDto... snapshotDtos) {
dbClient.snapshotDao().insert(dbSession, asList(snapshotDtos));
db.commit();
}
@SafeVarargs
public final ComponentDto insertProjectBranch(ComponentDto mainBranchComponent, Consumer<BranchDto>... dtoPopulators) {
BranchDto mainBranch = dbClient.branchDao().selectByUuid(db.getSession(), mainBranchComponent.branchUuid()).orElseThrow(IllegalArgumentException::new);
BranchDto branchDto = ComponentTesting.newBranchDto(mainBranch.getProjectUuid(), BRANCH);
Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(branchDto));
return insertProjectBranch(mainBranchComponent, branchDto);
}
@SafeVarargs
public final BranchDto insertProjectBranch(ProjectDto project, Consumer<BranchDto>... dtoPopulators) {
BranchDto branchDto = ComponentTesting.newBranchDto(project.getUuid(), BRANCH);
Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(branchDto));
insertProjectBranch(project, branchDto);
return branchDto;
}
public final ComponentDto insertProjectBranch(ProjectDto project, BranchDto branchDto) {
checkArgument(branchDto.getProjectUuid().equals(project.getUuid()));
ComponentDto branch = ComponentTesting.newBranchComponent(project, branchDto);
insertComponent(branch);
dbClient.branchDao().insert(dbSession, branchDto);
db.commit();
return branch;
}
public final ComponentDto insertProjectBranch(ComponentDto project, BranchDto branchDto) {
ComponentDto branch = ComponentTesting.newBranchComponent(project, branchDto);
insertComponent(branch);
dbClient.branchDao().insert(dbSession, branchDto);
db.commit();
return branch;
}
public static ProjectDto toProjectDto(ComponentDto componentDto, long createTime) {
return new ProjectDto()
.setUuid(Uuids.createFast())
.setKey(componentDto.getKey())
.setQualifier(componentDto.qualifier() != null ? componentDto.qualifier() : Qualifiers.PROJECT)
.setCreatedAt(createTime)
.setUpdatedAt(createTime)
.setPrivate(componentDto.isPrivate())
.setDescription(componentDto.description())
.setName(componentDto.name());
}
public static PortfolioDto toPortfolioDto(ComponentDto componentDto, long createTime) {
return new PortfolioDto()
.setUuid(componentDto.uuid())
.setKey(componentDto.getKey())
.setRootUuid(componentDto.branchUuid())
.setSelectionMode(NONE.name())
.setCreatedAt(createTime)
.setUpdatedAt(createTime)
.setPrivate(componentDto.isPrivate())
.setDescription(componentDto.description())
.setName(componentDto.name());
}
public static <T> Consumer<T> defaults() {
return t -> {
};
}
}
| 28,080 | 45.491722 | 168 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import java.util.Date;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.core.util.Uuids;
import org.sonar.db.portfolio.PortfolioDto;
import org.sonar.db.project.ProjectDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent;
import static org.sonar.db.component.ComponentDto.generateBranchKey;
import static org.sonar.db.portfolio.PortfolioDto.SelectionMode.NONE;
public class ComponentTesting {
public static ComponentDto newFileDto(ComponentDto branch) {
return newFileDto(branch, (ComponentDto) null);
}
public static ComponentDto newFileDto(ComponentDto branch, @Nullable ComponentDto directory) {
return newFileDto(branch, directory, Uuids.createFast());
}
public static ComponentDto newFileDto(ComponentDto branch, String mainBranchUuid) {
return newFileDto(mainBranchUuid, branch, null);
}
public static ComponentDto newFileDto(String mainBranchUuid, ComponentDto projectOrBranch, @Nullable ComponentDto directory) {
return newFileDto(projectOrBranch, directory, Uuids.createFast(), mainBranchUuid);
}
public static ComponentDto newFileDto(ComponentDto branch, @Nullable ComponentDto directory, String fileUuid) {
return newFileDto(branch, directory, fileUuid, null);
}
public static ComponentDto newFileDto(ComponentDto branch, @Nullable ComponentDto directory, String fileUuid, @Nullable String mainBranchUuid) {
String filename = "NAME_" + fileUuid;
String path = directory != null ? directory.path() + "/" + filename : branch.path() + "/" + filename;
return newChildComponent(fileUuid, branch, directory == null ? branch : directory)
.setKey("FILE_KEY_" + fileUuid)
.setName(filename)
.setLongName(path)
.setScope(Scopes.FILE)
.setBranchUuid(branch.branchUuid())
.setQualifier(Qualifiers.FILE)
.setPath(path)
.setCreatedAt(new Date())
.setLanguage("xoo");
}
public static ComponentDto newDirectory(ComponentDto branch, String path) {
return newDirectory(branch, Uuids.createFast(), path);
}
public static ComponentDto newDirectoryOnBranch(ComponentDto branch, String path, String mainBranchUuid) {
return newDirectory(branch, Uuids.createFast(), path, mainBranchUuid);
}
private static ComponentDto newDirectory(ComponentDto branch, String uuid, String path, String mainBranchUuid) {
String key = !path.equals("/") ? branch.getKey() + ":" + path : branch.getKey() + ":/";
return newChildComponent(uuid, branch, branch)
.setKey(key)
.setName(path)
.setLongName(path)
.setBranchUuid(branch.branchUuid())
.setPath(path)
.setScope(Scopes.DIRECTORY)
.setQualifier(Qualifiers.DIRECTORY);
}
public static ComponentDto newDirectory(ComponentDto branch, String uuid, String path) {
return newDirectory(branch, uuid, path, null);
}
public static ComponentDto newSubPortfolio(ComponentDto portfolioOrSubPortfolio, String uuid, String key) {
return newChildComponent(uuid, portfolioOrSubPortfolio, portfolioOrSubPortfolio)
.setKey(key)
.setName(key)
.setLongName(key)
.setScope(Scopes.PROJECT)
.setQualifier(Qualifiers.SUBVIEW)
.setPath(null);
}
public static ComponentDto newSubPortfolio(ComponentDto viewOrSubView) {
String uuid = Uuids.createFast();
return newSubPortfolio(viewOrSubView, uuid, "KEY_" + uuid);
}
public static ComponentDto newPrivateProjectDto() {
return newProjectDto(Uuids.createFast(), true);
}
public static ComponentDto newPrivateProjectDto(String uuid) {
return newProjectDto(uuid, true);
}
public static ComponentDto newPublicProjectDto() {
return newProjectDto(Uuids.createFast(), false);
}
public static ComponentDto newPublicProjectDto(String uuid) {
return newProjectDto(uuid, false);
}
private static ComponentDto newProjectDto(String uuid, boolean isPrivate) {
return new ComponentDto()
.setUuid(uuid)
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid(uuid)
.setKey("KEY_" + uuid)
.setName("NAME_" + uuid)
.setLongName("LONG_NAME_" + uuid)
.setDescription("DESCRIPTION_" + uuid)
.setScope(Scopes.PROJECT)
.setQualifier(Qualifiers.PROJECT)
.setPath(null)
.setLanguage(null)
.setEnabled(true)
.setPrivate(isPrivate);
}
public static ComponentDto newPortfolio() {
return newPortfolio(Uuids.createFast());
}
public static ComponentDto newPortfolio(String uuid) {
return newPrivateProjectDto(uuid)
.setUuid(uuid)
.setScope(Scopes.PROJECT)
.setQualifier(Qualifiers.VIEW)
.setPrivate(false);
}
public static PortfolioDto newPortfolioDto(String uuid, String key, String name, @Nullable PortfolioDto parent) {
return new PortfolioDto()
.setUuid(uuid)
.setKey(key)
.setParentUuid(parent == null ? null : parent.getUuid())
.setRootUuid(parent == null ? uuid : parent.getRootUuid())
.setSelectionMode(NONE.name())
.setCreatedAt(1L)
.setUpdatedAt(1L)
.setPrivate(false)
.setName(name);
}
public static ComponentDto newApplication() {
return newPortfolio(Uuids.createFast()).setQualifier(Qualifiers.APP);
}
public static ComponentDto newProjectCopy(ProjectData project, ProjectData view) {
return newProjectCopy(Uuids.createFast(), project.getMainBranchComponent(), view.getMainBranchComponent());
}
public static ComponentDto newProjectCopy(ComponentDto project, ComponentDto view) {
return newProjectCopy(Uuids.createFast(), project, view);
}
public static ComponentDto newProjectCopy(String uuid, ComponentDto project, ComponentDto view) {
return newChildComponent(uuid, view, view)
.setKey(view.getKey() + project.getKey())
.setName(project.name())
.setLongName(project.longName())
.setCopyComponentUuid(project.uuid())
.setScope(Scopes.FILE)
.setQualifier(Qualifiers.PROJECT)
.setPath(null)
.setLanguage(null);
}
public static ComponentDto newProjectBranchCopy(String uuid, ComponentDto project, ComponentDto view, String branch) {
return newChildComponent(uuid, view, view)
.setKey(generateBranchKey(view.getKey() + project.getKey(), branch))
.setName(project.name())
.setLongName(project.longName())
.setCopyComponentUuid(project.uuid())
.setScope(Scopes.FILE)
.setQualifier(Qualifiers.PROJECT)
.setPath(null)
.setLanguage(null);
}
public static ComponentDto newChildComponent(String uuid, ComponentDto branch, ComponentDto parent) {
checkArgument(branch.isPrivate() == parent.isPrivate(),
"private flag inconsistent between branch (%s) and parent (%s)",
branch.isPrivate(), parent.isPrivate());
return new ComponentDto()
.setUuid(uuid)
.setUuidPath(formatUuidPathFromParent(parent))
.setKey(uuid)
.setBranchUuid(branch.branchUuid())
.setCreatedAt(new Date())
.setEnabled(true)
.setPrivate(branch.isPrivate());
}
public static BranchDto newBranchDto(@Nullable String projectUuid, BranchType branchType) {
String key = "branch_" + randomAlphanumeric(248);
return new BranchDto()
.setKey(key)
.setUuid(Uuids.createFast())
.setIsMain(false)
.setProjectUuid(projectUuid)
.setBranchType(branchType);
}
public static BranchDto newBranchDto(ComponentDto project) {
return newBranchDto(project.branchUuid(), BranchType.BRANCH);
}
public static BranchDto newBranchDto(ComponentDto branchComponent, BranchType branchType, String projectUuid) {
String key = "branch_" + randomAlphanumeric(248);
return new BranchDto()
.setKey(key)
.setIsMain(false)
.setUuid(branchComponent.uuid())
.setProjectUuid(projectUuid)
.setBranchType(branchType);
}
public static BranchDto newMainBranchDto(ComponentDto branchComponent, String projectUUid) {
return new BranchDto()
.setKey(DEFAULT_MAIN_BRANCH_NAME)
.setIsMain(true)
.setUuid(branchComponent.uuid())
.setProjectUuid(projectUUid)
.setBranchType(BranchType.BRANCH);
}
public static ProjectDto newProjectDto() {
return new ProjectDto()
.setKey("projectKey")
.setUuid("uuid")
.setName("projectName")
.setQualifier(Qualifiers.PROJECT);
}
public static ProjectDto newApplicationDto() {
return new ProjectDto()
.setKey("appKey")
.setUuid("uuid")
.setName("appName")
.setQualifier(Qualifiers.APP);
}
public static ComponentDto newBranchComponent(ProjectDto project, BranchDto branchDto) {
String uuid = branchDto.getUuid();
return new ComponentDto()
.setUuid(uuid)
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid(uuid)
.setKey(project.getKey())
.setName(project.getName())
.setLongName(project.getName())
.setDescription(project.getDescription())
.setScope(Scopes.PROJECT)
.setQualifier(project.getQualifier())
.setPath(null)
.setLanguage(null)
.setEnabled(true)
.setPrivate(project.isPrivate());
}
public static ComponentDto newBranchComponent(ComponentDto project, BranchDto branchDto) {
checkArgument(project.qualifier().equals(Qualifiers.PROJECT) || project.qualifier().equals(Qualifiers.APP));
String uuid = branchDto.getUuid();
return new ComponentDto()
.setUuid(uuid)
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid(uuid)
.setKey(project.getKey())
.setName(project.name())
.setLongName(project.longName())
.setDescription(project.description())
.setScope(project.scope())
.setQualifier(project.qualifier())
.setPath(null)
.setLanguage(null)
.setEnabled(true)
.setPrivate(project.isPrivate());
}
}
| 11,095 | 34.793548 | 146 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/PortfolioData.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import org.sonar.db.portfolio.PortfolioDto;
public class PortfolioData {
private final ComponentDto rootComponent;
private final PortfolioDto portfolioDto;
public PortfolioData(PortfolioDto projectDto, ComponentDto rootComponent) {
this.rootComponent = rootComponent;
this.portfolioDto = projectDto;
}
public ComponentDto getRootComponent() {
return rootComponent;
}
public PortfolioDto getPortfolioDto() {
return portfolioDto;
}
public String portfolioUuid() {
return portfolioDto.getUuid();
}
public String rootComponentUuid() {
return rootComponent.uuid();
}
}
| 1,495 | 28.92 | 77 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectData.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import org.sonar.db.project.ProjectDto;
public class ProjectData {
private final BranchDto mainBranchDto;
private final ComponentDto mainBranchComponent;
private final ProjectDto projectDto;
public ProjectData(ProjectDto projectDto, BranchDto mainBranchDto, ComponentDto mainBranchComponent) {
this.mainBranchDto = mainBranchDto;
this.mainBranchComponent = mainBranchComponent;
this.projectDto = projectDto;
}
public ComponentDto getMainBranchComponent() {
return mainBranchComponent;
}
public ProjectDto getProjectDto() {
return projectDto;
}
public BranchDto getMainBranchDto() {
return mainBranchDto;
}
public String projectUuid() {
return projectDto.getUuid();
}
public String projectKey() {
return projectDto.getKey();
}
public String mainBranchUuid() {
return mainBranchDto.getUuid();
}
}
| 1,750 | 28.183333 | 104 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import java.util.Arrays;
import java.util.function.Consumer;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import static org.sonar.db.component.ProjectLinkTesting.newCustomLinkDto;
import static org.sonar.db.component.ProjectLinkTesting.newProvidedLinkDto;
public class ProjectLinkDbTester {
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public ProjectLinkDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
@SafeVarargs
public final ProjectLinkDto insertProvidedLink(ProjectDto project, Consumer<ProjectLinkDto>... dtoPopulators) {
return insertLink(project, newProvidedLinkDto(), dtoPopulators);
}
@SafeVarargs
public final ProjectLinkDto insertCustomLink(ProjectDto project, Consumer<ProjectLinkDto>... dtoPopulators) {
return insertLink(project, newCustomLinkDto(), dtoPopulators);
}
@SafeVarargs
private final ProjectLinkDto insertLink(ProjectDto project, ProjectLinkDto componentLink, Consumer<ProjectLinkDto>... dtoPopulators) {
Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(componentLink));
dbClient.projectLinkDao().insert(dbSession, componentLink.setProjectUuid(project.getUuid()));
db.commit();
return componentLink;
}
}
| 2,298 | 36.080645 | 136 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import org.apache.commons.lang.math.RandomUtils;
import org.sonar.core.util.Uuids;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
public class ProjectLinkTesting {
public static ProjectLinkDto newProvidedLinkDto() {
return newCommonLinkDto()
.setName(null)
.setType(ProjectLinkDto.PROVIDED_TYPES.get(RandomUtils.nextInt(ProjectLinkDto.PROVIDED_TYPES.size() - 1)));
}
public static ProjectLinkDto newCustomLinkDto() {
String nameAndType = randomAlphabetic(20);
return newCommonLinkDto()
.setName(nameAndType)
.setType(nameAndType);
}
private static ProjectLinkDto newCommonLinkDto() {
return new ProjectLinkDto()
.setUuid(Uuids.createFast())
.setProjectUuid(Uuids.createFast())
.setHref(randomAlphanumeric(128))
.setCreatedAt(System.currentTimeMillis())
.setUpdatedAt(System.currentTimeMillis());
}
}
| 1,867 | 34.245283 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import org.sonar.api.resources.Qualifiers;
import org.sonar.core.util.Uuids;
import org.sonar.db.project.ProjectDto;
public class ProjectTesting {
public static ProjectDto newPrivateProjectDto() {
return newProjectDto(Uuids.createFast(), true);
}
public static ProjectDto newPrivateProjectDto(String uuid) {
return newProjectDto(uuid, true);
}
public static ProjectDto newPublicProjectDto() {
return newProjectDto(Uuids.createFast(), false);
}
public static ProjectDto newPublicProjectDto(String uuid) {
return newProjectDto(uuid, false);
}
private static ProjectDto newProjectDto(String uuid, boolean isPrivate) {
return new ProjectDto()
.setUuid(uuid)
.setKey("KEY_" + uuid)
.setName("NAME_" + uuid)
.setDescription("DESCRIPTION_" + uuid)
.setQualifier(Qualifiers.PROJECT)
.setPrivate(isPrivate);
}
}
| 1,761 | 31.62963 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ResourceTypesRule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypeTree;
import org.sonar.api.resources.ResourceTypes;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
public class ResourceTypesRule extends ResourceTypes {
private Set<ResourceType> allResourceTypes = emptySet();
private Set<ResourceType> rootResourceTypes = emptySet();
private List<String> leavesQualifiers = emptyList();
public ResourceTypesRule() {
super(new ResourceTypeTree[0]);
}
@Override
public Collection<ResourceType> getAll() {
return allResourceTypes;
}
@Override
public Collection<ResourceType> getRoots() {
return rootResourceTypes;
}
public ResourceTypesRule setRootQualifiers(Collection<ResourceType> qualifiers) {
rootResourceTypes = Set.copyOf(qualifiers);
return this;
}
public ResourceTypesRule setRootQualifiers(String... qualifiers) {
Set<ResourceType> resourceTypes = new LinkedHashSet<>();
for (String qualifier : qualifiers) {
resourceTypes.add(ResourceType.builder(qualifier).setProperty("deletable", true).build());
}
rootResourceTypes = Set.copyOf(resourceTypes);
return this;
}
public ResourceTypesRule setLeavesQualifiers(String... qualifiers) {
leavesQualifiers = List.copyOf(Arrays.asList(qualifiers));
return this;
}
public ResourceTypesRule setAllQualifiers(String... qualifiers) {
Set<ResourceType> resourceTypes = new HashSet<>();
for (String qualifier : qualifiers) {
resourceTypes.add(ResourceType.builder(qualifier).setProperty("deletable", true).build());
}
allResourceTypes = Set.copyOf(resourceTypes);
return this;
}
public ResourceTypesRule setAllQualifiers(Collection<ResourceType> qualifiers) {
allResourceTypes = Set.copyOf(qualifiers);
return this;
}
@Override
public ResourceType get(String qualifier) {
return allResourceTypes.stream()
.filter(resourceType -> qualifier.equals(resourceType.getQualifier()))
.findAny().orElse(null);
}
@Override
public boolean isQualifierPresent(String qualifier) {
return rootResourceTypes.stream()
.anyMatch(resourceType -> qualifier.equals(resourceType.getQualifier()));
}
@Override
public List<String> getLeavesQualifiers(String qualifier) {
return this.leavesQualifiers;
}
}
| 3,421 | 30.685185 | 96 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.component;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.RandomStringUtils.randomAscii;
public class SnapshotTesting {
private SnapshotTesting() {
// nothing to do
}
public static SnapshotDto newAnalysis(ComponentDto rootComponent) {
checkNotNull(rootComponent.uuid(), "Project UUID must be set");
checkArgument(rootComponent.uuid().equals(rootComponent.branchUuid()), "Component is not a tree root");
return newAnalysis(rootComponent.uuid());
}
public static SnapshotDto newAnalysis(BranchDto branchDto) {
checkNotNull(branchDto.getUuid(), "Project UUID must be set");
return newAnalysis(branchDto.getUuid());
}
public static SnapshotDto newAnalysis(String uuid) {
return new SnapshotDto()
.setUuid(randomAlphanumeric(40))
.setRootComponentUuid(uuid)
.setStatus(SnapshotDto.STATUS_PROCESSED)
.setCreatedAt(System.currentTimeMillis())
.setBuildDate(System.currentTimeMillis())
.setRevision(randomAlphanumeric(50))
.setLast(true);
}
public static SnapshotDto newSnapshot() {
return new SnapshotDto()
.setUuid(randomAlphanumeric(40))
.setRootComponentUuid(randomAlphanumeric(40))
.setStatus(randomAscii(1))
.setCreatedAt(System.currentTimeMillis())
.setBuildDate(System.currentTimeMillis())
.setLast(true);
}
}
| 2,409 | 36.076923 | 107 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.event;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventComponentChangeDto.ChangeCategory;
public class EventDbTester {
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public EventDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public EventDto insertEvent(EventDto event) {
dbClient.eventDao().insert(dbSession, event);
db.commit();
return event;
}
public EventDto insertEvent(SnapshotDto analysis) {
EventDto event = EventTesting.newEvent(analysis);
dbClient.eventDao().insert(dbSession, event);
db.commit();
return event;
}
public EventComponentChangeDto insertEventComponentChanges(EventDto event, SnapshotDto analysis,
ChangeCategory changeCategory, ComponentDto component, @Nullable BranchDto branch) {
EventComponentChangeDto eventComponentChange = new EventComponentChangeDto()
.setUuid(UuidFactoryFast.getInstance().create())
.setCategory(changeCategory)
.setEventUuid(event.getUuid())
.setComponentUuid(component.uuid())
.setComponentKey(component.getKey())
.setComponentName(component.name())
.setComponentBranchKey(Optional.ofNullable(branch).map(BranchDto::getKey).orElse(null));
EventPurgeData eventPurgeData = new EventPurgeData(analysis.getRootComponentUuid(), analysis.getUuid());
dbClient.eventComponentChangeDao().insert(dbSession, eventComponentChange, eventPurgeData);
db.commit();
return eventComponentChange;
}
}
| 2,756 | 33.898734 | 108 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.event;
import org.sonar.db.component.SnapshotDto;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
public class EventTesting {
public static EventDto newEvent(SnapshotDto analysis) {
requireNonNull(analysis.getUuid());
requireNonNull(analysis.getRootComponentUuid());
return new EventDto()
.setAnalysisUuid(analysis.getUuid())
.setComponentUuid(analysis.getRootComponentUuid())
.setUuid(randomAlphanumeric(40))
.setName(randomAlphanumeric(400))
.setDescription(null)
.setCategory("Other")
.setCreatedAt(System.currentTimeMillis())
.setDate(System.currentTimeMillis());
}
}
| 1,581 | 34.954545 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/favorite/FavoriteDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.favorite;
import java.util.List;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
public class FavoriteDbTester {
private static final String PROP_FAVORITE_KEY = "favourite";
private final DbClient dbClient;
private final DbSession dbSession;
public FavoriteDbTester(DbTester db) {
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public void add(EntityDto entity, String userUuid, String userLogin) {
dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto()
.setKey(PROP_FAVORITE_KEY)
.setUserUuid(userUuid)
.setEntityUuid(entity.getUuid()),
userLogin, entity.getKey(), entity.getName(), entity.getQualifier());
dbSession.commit();
}
public boolean hasFavorite(EntityDto entity, String userUuid) {
List<PropertyDto> result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
.setKey(PROP_FAVORITE_KEY)
.setEntityUuid(entity.getUuid())
.setUserUuid(userUuid)
.build(), dbSession);
return !result.isEmpty();
}
public boolean hasNoFavorite(EntityDto entity) {
List<PropertyDto> result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
.setKey(PROP_FAVORITE_KEY)
.setEntityUuid(entity.getUuid())
.build(), dbSession);
return result.isEmpty();
}
}
| 2,367 | 33.823529 | 93 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/issue/IssueDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.issue;
import java.util.Arrays;
import java.util.Random;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.sonar.api.issue.Issue;
import org.sonar.api.rules.RuleType;
import org.sonar.core.issue.DefaultIssueComment;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Arrays.stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.issue.IssueTesting.newIssue;
public class IssueDbTester {
private static final RuleType[] RULE_TYPES_EXCEPT_HOTSPOTS = Arrays.stream(RuleType.values())
.filter(ruleType -> SECURITY_HOTSPOT != ruleType).toArray(RuleType[]::new);
private final DbTester db;
public IssueDbTester(DbTester db) {
this.db = db;
}
/**
* Inserts an issue or a security hotspot.
*/
@SafeVarargs
public final IssueDto insert(RuleDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
IssueDto issue = newIssue(rule, project, file);
stream(populators).forEach(p -> p.accept(issue));
return insert(issue);
}
/**
* Inserts an issue or a security hotspot.
*/
@SafeVarargs
public final IssueDto insert(Consumer<IssueDto>... populators) {
RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = newIssue(rule, project, file);
stream(populators).forEach(p -> p.accept(issue));
return insert(issue);
}
/**
* Inserts an issue or a security hotspot.
*/
public IssueDto insert(IssueDto issue) {
db.getDbClient().issueDao().insert(db.getSession(), issue);
db.commit();
return issue;
}
/**
* Inserts an issue.
*
* @throws AssertionError if rule is a Security Hotspot
*/
@SafeVarargs
public final IssueDto insertIssue(RuleDto rule, ComponentDto branch, ComponentDto file, Consumer<IssueDto>... populators) {
assertThat(rule.getType())
.describedAs("rule must not be a Security Hotspot type")
.isNotEqualTo(SECURITY_HOTSPOT.getDbConstant());
IssueDto issue = newIssue(rule, branch, file)
.setType(RULE_TYPES_EXCEPT_HOTSPOTS[new Random().nextInt(RULE_TYPES_EXCEPT_HOTSPOTS.length)]);
stream(populators).forEach(p -> p.accept(issue));
return insertIssue(issue);
}
@SafeVarargs
public final IssueDto insert(RuleDto rule, BranchDto branch, ComponentDto file, Consumer<IssueDto>... populators) {
IssueDto issue = newIssue(rule, branch, file);
stream(populators).forEach(p -> p.accept(issue));
return insert(issue);
}
/**
* Inserts an issue.
*
* @throws AssertionError if issueDto is a Security Hotspot
*/
public IssueDto insertIssue(IssueDto issueDto) {
assertThat(issueDto.getType())
.describedAs("Issue must not be a Security Hotspot")
.isNotEqualTo(SECURITY_HOTSPOT.getDbConstant());
return insert(issueDto);
}
/**
* Inserts an issue.
*
* @throws AssertionError if rule is not Security Hotspot
*/
@SafeVarargs
public final IssueDto insertIssue(Consumer<IssueDto>... populators) {
RuleDto rule = db.rules().insertIssueRule();
return insertIssue(rule, populators);
}
/**
* Inserts an issue.
*
* @throws AssertionError if rule is not Security Hotspot
*/
@SafeVarargs
public final IssueDto insertIssue(RuleDto ruleDto, Consumer<IssueDto>... populators) {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = newIssue(ruleDto, project, file)
.setType(RULE_TYPES_EXCEPT_HOTSPOTS[new Random().nextInt(RULE_TYPES_EXCEPT_HOTSPOTS.length)]);
stream(populators).forEach(p -> p.accept(issue));
return insertIssue(issue);
}
/**
* Inserts a Security Hotspot.
*
* @throws AssertionError if rule is not Security Hotspot
*/
@SafeVarargs
public final IssueDto insertHotspot(RuleDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
checkArgument(rule.getType() == RuleType.SECURITY_HOTSPOT.getDbConstant(), "rule must be a hotspot rule");
IssueDto issue = newIssue(rule, project, file)
.setType(SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW)
.setResolution(null);
stream(populators).forEach(p -> p.accept(issue));
return insertHotspot(issue);
}
/**
* Inserts a Security Hotspot.
*/
@SafeVarargs
public final IssueDto insertHotspot(ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
RuleDto rule = db.rules().insertHotspotRule();
IssueDto issue = newIssue(rule, project, file)
.setType(SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW)
.setResolution(null);
stream(populators).forEach(p -> p.accept(issue));
return insertHotspot(issue);
}
public final IssueDto insertHotspot(RuleDto rule, ProjectData project, ComponentDto file, Consumer<IssueDto>... populators) {
return insertHotspot(rule, project.getMainBranchComponent(), file, populators);
}
public final IssueDto insertHotspot(BranchDto branchDto, ComponentDto file, Consumer<IssueDto>... populators) {
RuleDto rule = db.rules().insertHotspotRule();
IssueDto issue = newIssue(rule, branchDto, file)
.setType(SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW)
.setResolution(null);
stream(populators).forEach(p -> p.accept(issue));
return insertHotspot(issue);
}
/**
* Inserts a Security Hotspot.
*
* @throws AssertionError if issueDto is not Security Hotspot
*/
public IssueDto insertHotspot(IssueDto issueDto) {
assertThat(issueDto.getType())
.describedAs("IssueDto must have Security Hotspot type")
.isEqualTo(SECURITY_HOTSPOT.getDbConstant());
return insert(issueDto);
}
/**
* Inserts a Security Hotspot.
*/
@SafeVarargs
public final IssueDto insertHotspot(Consumer<IssueDto>... populators) {
RuleDto rule = db.rules().insertHotspotRule();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = newIssue(rule, project, file)
.setType(SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW)
.setResolution(null);
stream(populators).forEach(p -> p.accept(issue));
return insertHotspot(issue);
}
@SafeVarargs
public final IssueChangeDto insertChange(IssueDto issueDto, Consumer<IssueChangeDto>... populators) {
IssueChangeDto dto = IssueTesting.newIssueChangeDto(issueDto);
stream(populators).forEach(p -> p.accept(dto));
return insertChange(dto);
}
public IssueChangeDto insertChange(IssueChangeDto issueChangeDto) {
db.getDbClient().issueChangeDao().insert(db.getSession(), issueChangeDto);
db.commit();
return issueChangeDto;
}
public IssueChangeDto insertComment(IssueDto issueDto, @Nullable UserDto user, String text) {
IssueChangeDto issueChangeDto = IssueChangeDto.of(DefaultIssueComment.create(issueDto.getKey(), user == null ? null : user.getUuid(), text), issueDto.getProjectUuid());
issueChangeDto.setUuid(Uuids.create());
return insertChange(issueChangeDto);
}
public void insertFieldDiffs(IssueDto issueDto, FieldDiffs... diffs) {
Arrays.stream(diffs).forEach(diff -> db.getDbClient().issueChangeDao().insert(db.getSession(), IssueChangeDto.of(issueDto.getKey(), diff, issueDto.getProjectUuid())
.setUuid(Uuids.createFast())));
db.commit();
}
/**
* Inserts an issue as new code in a branch using reference branch for new code
*/
public void insertNewCodeReferenceIssue(NewCodeReferenceIssueDto dto) {
db.getDbClient().issueDao().insertAsNewCodeOnReferenceBranch(db.getSession(), dto);
db.commit();
}
public void insertNewCodeReferenceIssue(IssueDto issue) {
db.getDbClient().issueDao().insertAsNewCodeOnReferenceBranch(db.getSession(), IssueTesting.newCodeReferenceIssue(issue));
db.commit();
}
}
| 9,495 | 35.523077 | 172 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.measure;
import java.util.Arrays;
import java.util.function.Consumer;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.metric.MetricDto;
import static org.sonar.db.measure.MeasureTesting.newLiveMeasure;
import static org.sonar.db.measure.MeasureTesting.newMeasureDto;
import static org.sonar.db.metric.MetricTesting.newMetricDto;
public class MeasureDbTester {
private final DbClient dbClient;
private final DbSession dbSession;
public MeasureDbTester(DbTester db) {
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
@SafeVarargs
public final MeasureDto insertMeasure(ComponentDto component, SnapshotDto analysis, MetricDto metricDto, Consumer<MeasureDto>... consumers) {
MeasureDto measureDto = newMeasureDto(metricDto, component, analysis);
Arrays.stream(consumers).forEach(c -> c.accept(measureDto));
dbClient.measureDao().insert(dbSession, measureDto);
dbSession.commit();
return measureDto;
}
@SafeVarargs
public final MeasureDto insertMeasure(BranchDto branchDto, SnapshotDto analysis, MetricDto metricDto, Consumer<MeasureDto>... consumers) {
MeasureDto measureDto = newMeasureDto(metricDto, branchDto.getUuid(), analysis);
Arrays.stream(consumers).forEach(c -> c.accept(measureDto));
dbClient.measureDao().insert(dbSession, measureDto);
dbSession.commit();
return measureDto;
}
@SafeVarargs
public final LiveMeasureDto insertLiveMeasure(ComponentDto component, MetricDto metric, Consumer<LiveMeasureDto>... consumers) {
LiveMeasureDto dto = newLiveMeasure(component, metric);
Arrays.stream(consumers).forEach(c -> c.accept(dto));
dbClient.liveMeasureDao().insert(dbSession, dto);
dbSession.commit();
return dto;
}
@SafeVarargs
public final LiveMeasureDto insertLiveMeasure(BranchDto branchDto, MetricDto metric, Consumer<LiveMeasureDto>... consumers) {
LiveMeasureDto dto = newLiveMeasure(branchDto, metric);
Arrays.stream(consumers).forEach(c -> c.accept(dto));
dbClient.liveMeasureDao().insert(dbSession, dto);
dbSession.commit();
return dto;
}
@SafeVarargs
public final LiveMeasureDto insertLiveMeasure(ProjectData projectData, MetricDto metric, Consumer<LiveMeasureDto>... consumers) {
return insertLiveMeasure(projectData.getMainBranchComponent(), metric, consumers);
}
@SafeVarargs
public final MetricDto insertMetric(Consumer<MetricDto>... consumers) {
MetricDto metricDto = newMetricDto();
Arrays.stream(consumers).forEach(c -> c.accept(metricDto));
dbClient.metricDao().insert(dbSession, metricDto);
dbSession.commit();
return metricDto;
}
}
| 3,744 | 37.214286 | 143 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/measure/MeasureTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.measure;
import org.apache.commons.lang.math.RandomUtils;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.metric.MetricDto;
import static com.google.common.base.Preconditions.checkNotNull;
public class MeasureTesting {
private static int cursor = RandomUtils.nextInt(100);
private MeasureTesting() {
// static methods only
}
public static MeasureDto newMeasureDto(MetricDto metricDto, ComponentDto component, SnapshotDto analysis) {
return newMeasureDto(metricDto, component.uuid(), analysis);
}
public static MeasureDto newMeasureDto(MetricDto metricDto, String branchUuid, SnapshotDto analysis) {
checkNotNull(metricDto.getUuid());
checkNotNull(metricDto.getKey());
checkNotNull(branchUuid);
checkNotNull(analysis.getUuid());
return new MeasureDto()
.setMetricUuid(metricDto.getUuid())
.setComponentUuid(branchUuid)
.setAnalysisUuid(analysis.getUuid());
}
public static MeasureDto newMeasure() {
return new MeasureDto()
.setMetricUuid(String.valueOf(cursor++))
.setComponentUuid(String.valueOf(cursor++))
.setAnalysisUuid(String.valueOf(cursor++))
.setData(String.valueOf(cursor++))
.setAlertStatus(String.valueOf(cursor++))
.setAlertText(String.valueOf(cursor++))
.setValue((double) cursor++);
}
public static LiveMeasureDto newLiveMeasure() {
return new LiveMeasureDto()
.setMetricUuid(String.valueOf(cursor++))
.setComponentUuid(String.valueOf(cursor++))
.setProjectUuid(String.valueOf(cursor++))
.setData(String.valueOf(cursor++))
.setValue((double) cursor++);
}
public static LiveMeasureDto newLiveMeasure(ComponentDto component, MetricDto metric) {
return new LiveMeasureDto()
.setMetricUuid(metric.getUuid())
.setComponentUuid(component.uuid())
.setProjectUuid(component.branchUuid())
.setData(String.valueOf(cursor++))
.setValue((double) cursor++);
}
public static LiveMeasureDto newLiveMeasure(BranchDto branchDto, MetricDto metric) {
return new LiveMeasureDto()
.setMetricUuid(metric.getUuid())
.setComponentUuid(branchDto.getUuid())
.setProjectUuid(branchDto.getProjectUuid())
.setData(String.valueOf(cursor++))
.setValue((double) cursor++);
}
}
| 3,258 | 34.813187 | 109 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.metric;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.sonar.api.measures.Metric;
public class MetricTesting {
private MetricTesting() {
// static stuff only
}
public static MetricDto newMetricDto() {
Metric.ValueType[] metricTypes = Metric.ValueType.values();
return new MetricDto()
.setUuid(RandomStringUtils.randomAlphanumeric(40))
.setKey(RandomStringUtils.randomAlphanumeric(64))
.setShortName(RandomStringUtils.randomAlphanumeric(64))
.setValueType(metricTypes[RandomUtils.nextInt(metricTypes.length - 1)].name())
.setDomain(RandomStringUtils.randomAlphanumeric(64))
.setDescription(RandomStringUtils.randomAlphanumeric(250))
.setBestValue(RandomUtils.nextDouble())
.setDeleteHistoricalData(RandomUtils.nextBoolean())
.setDirection(RandomUtils.nextInt())
.setHidden(RandomUtils.nextBoolean())
.setEnabled(true)
.setOptimizedBestValue(RandomUtils.nextBoolean())
.setQualitative(RandomUtils.nextBoolean())
.setWorstValue(RandomUtils.nextDouble());
}
}
| 1,990 | 38.82 | 84 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/newcodeperiod/NewCodePeriodDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.newcodeperiod;
import javax.annotation.Nullable;
import org.sonar.db.DbTester;
public class NewCodePeriodDbTester {
private final DbTester dbTester;
public NewCodePeriodDbTester(DbTester dbTester) {
this.dbTester = dbTester;
}
public NewCodePeriodDto insert(NewCodePeriodDto dto) {
dbTester.getDbClient().newCodePeriodDao().insert(dbTester.getSession(), dto);
dbTester.getSession().commit();
return dto;
}
public NewCodePeriodDto insert(@Nullable String projectUuid, @Nullable String branchUuid, NewCodePeriodType type, @Nullable String value) {
NewCodePeriodDto dto = new NewCodePeriodDto()
.setProjectUuid(projectUuid)
.setBranchUuid(branchUuid)
.setType(type)
.setValue(value);
insert(dto);
return dto;
}
public NewCodePeriodDto insert(@Nullable String projectUuid, NewCodePeriodType type, @Nullable String value) {
NewCodePeriodDto dto = new NewCodePeriodDto()
.setProjectUuid(projectUuid)
.setType(type)
.setValue(value);
insert(dto);
return dto;
}
public NewCodePeriodDto insert(NewCodePeriodType type, @Nullable String value) {
NewCodePeriodDto dto = new NewCodePeriodDto()
.setType(type)
.setValue(value);
insert(dto);
return dto;
}
}
| 2,144 | 31.014925 | 141 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/notification/NotificationDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.notification;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
import static org.assertj.core.api.Assertions.assertThat;
public class NotificationDbTester {
private static final String PROP_NOTIFICATION_PREFIX = "notification";
private final DbClient dbClient;
private final DbSession dbSession;
public NotificationDbTester(DbTester db) {
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public void assertExists(String channel, String dispatcher, String userUuid, @Nullable ProjectDto project) {
List<PropertyDto> result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
.setKey(String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel))
.setEntityUuid(project == null ? null : project.getUuid())
.setUserUuid(userUuid)
.build(), dbSession).stream()
.filter(prop -> project == null ? prop.getEntityUuid() == null : prop.getEntityUuid() != null)
.toList();
assertThat(result).hasSize(1);
assertThat(result.get(0).getValue()).isEqualTo("true");
}
public void assertDoesNotExist(String channel, String dispatcher, String userUuid, @Nullable ProjectDto project) {
List<PropertyDto> result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
.setKey(String.join(".", PROP_NOTIFICATION_PREFIX, dispatcher, channel))
.setEntityUuid(project == null ? null : project.getUuid())
.setUserUuid(userUuid)
.build(), dbSession);
assertThat(result).isEmpty();
}
}
| 2,614 | 39.230769 | 116 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/PermissionsTestHelper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.permission;
import java.util.Set;
import org.sonar.api.web.UserRole;
import static org.sonar.db.permission.GlobalPermission.APPLICATION_CREATOR;
import static org.sonar.db.permission.GlobalPermission.PORTFOLIO_CREATOR;
import static org.sonar.db.permission.GlobalPermission.SCAN;
public class PermissionsTestHelper {
public static final Set<String> ALL_PERMISSIONS = Set.of(UserRole.ADMIN, UserRole.CODEVIEWER, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN,
SCAN.getKey(), UserRole.USER, APPLICATION_CREATOR.getKey(), PORTFOLIO_CREATOR.getKey());
private PermissionsTestHelper() {
}
}
| 1,471 | 38.783784 | 149 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.permission.template;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import static java.util.Optional.ofNullable;
import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateCharacteristicDto;
import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
public class PermissionTemplateDbTester {
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public PermissionTemplateDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public void setDefaultTemplates(String projectDefaultTemplateUuid, @Nullable String applicationDefaultTemplateUuid, @Nullable String portfoliosDefaultTemplateUuid) {
db.getDbClient().internalPropertiesDao().save(dbSession, "defaultTemplate.prj", projectDefaultTemplateUuid);
if (applicationDefaultTemplateUuid != null) {
db.getDbClient().internalPropertiesDao().save(dbSession, "defaultTemplate.app", applicationDefaultTemplateUuid);
}
if (portfoliosDefaultTemplateUuid != null) {
db.getDbClient().internalPropertiesDao().save(dbSession, "defaultTemplate.port", portfoliosDefaultTemplateUuid);
}
dbSession.commit();
}
public void setDefaultTemplates(PermissionTemplateDto projectDefaultTemplate, @Nullable PermissionTemplateDto applicationDefaultTemplate,
@Nullable PermissionTemplateDto portfoliosDefaultTemplate) {
setDefaultTemplates(projectDefaultTemplate.getUuid(),
ofNullable(applicationDefaultTemplate).map(PermissionTemplateDto::getUuid).orElse(null),
ofNullable(portfoliosDefaultTemplate).map(PermissionTemplateDto::getUuid).orElse(null));
}
@SafeVarargs
public final PermissionTemplateDto insertTemplate(Consumer<PermissionTemplateDto>... populators) {
return insertTemplate(newPermissionTemplateDto(populators));
}
public PermissionTemplateDto insertTemplate(PermissionTemplateDto template) {
PermissionTemplateDto templateInDb = dbClient.permissionTemplateDao().insert(dbSession, template);
db.commit();
return templateInDb;
}
public void addGroupToTemplate(PermissionTemplateDto permissionTemplate, GroupDto group, String permission) {
addGroupToTemplate(permissionTemplate.getUuid(), group.getUuid(), permission, permissionTemplate.getName(), group.getName());
}
public void addGroupToTemplate(String templateUuid, @Nullable String groupUuid, String permission, String templateName, @Nullable String groupName) {
dbClient.permissionTemplateDao().insertGroupPermission(dbSession, templateUuid, groupUuid, permission, templateName, groupName);
db.commit();
}
public void addAnyoneToTemplate(PermissionTemplateDto permissionTemplate, String permission) {
addGroupToTemplate(permissionTemplate.getUuid(), null, permission, permissionTemplate.getName(), null);
}
public void addUserToTemplate(PermissionTemplateDto permissionTemplate, UserDto user, String permission) {
addUserToTemplate(permissionTemplate.getUuid(), user.getUuid(), permission, permissionTemplate.getName(), user.getName());
}
public void addUserToTemplate(String templateUuid, String userUuid, String permission, String templateName, String userLogin) {
dbClient.permissionTemplateDao().insertUserPermission(dbSession, templateUuid, userUuid, permission, templateName, userLogin);
db.commit();
}
public void addProjectCreatorToTemplate(PermissionTemplateDto permissionTemplate, String permission) {
addProjectCreatorToTemplate(permissionTemplate.getUuid(), permission, permissionTemplate.getName());
}
public void addProjectCreatorToTemplate(String templateUuid, String permission, String templateName) {
dbClient.permissionTemplateCharacteristicDao().insert(dbSession, newPermissionTemplateCharacteristicDto()
.setWithProjectCreator(true)
.setTemplateUuid(templateUuid)
.setPermission(permission),
templateName);
db.commit();
}
}
| 5,076 | 45.577982 | 167 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.permission.template;
import java.util.Date;
import java.util.function.Consumer;
import org.apache.commons.lang.math.RandomUtils;
import org.sonar.core.util.Uuids;
import org.sonar.db.permission.PermissionsTestHelper;
import static java.util.Arrays.stream;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.RandomStringUtils.randomAscii;
public class PermissionTemplateTesting {
@SafeVarargs
public static PermissionTemplateDto newPermissionTemplateDto(Consumer<PermissionTemplateDto>... populators) {
PermissionTemplateDto dto = new PermissionTemplateDto()
.setName(randomAlphanumeric(60))
.setDescription(randomAscii(500))
.setUuid(Uuids.create())
.setCreatedAt(new Date())
.setUpdatedAt(new Date());
stream(populators).forEach(p -> p.accept(dto));
return dto;
}
public static PermissionTemplateUserDto newPermissionTemplateUserDto() {
return new PermissionTemplateUserDto()
.setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())])
.setCreatedAt(new Date())
.setUpdatedAt(new Date());
}
public static PermissionTemplateGroupDto newPermissionTemplateGroupDto() {
return new PermissionTemplateGroupDto()
.setUuid(Uuids.createFast())
.setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())])
.setCreatedAt(new Date())
.setUpdatedAt(new Date());
}
public static PermissionTemplateCharacteristicDto newPermissionTemplateCharacteristicDto() {
return new PermissionTemplateCharacteristicDto()
.setUuid(Uuids.createFast())
.setPermission(PermissionsTestHelper.ALL_PERMISSIONS.toArray(new String[0])[RandomUtils.nextInt(PermissionsTestHelper.ALL_PERMISSIONS.size())])
.setWithProjectCreator(RandomUtils.nextBoolean())
.setCreatedAt(System.currentTimeMillis())
.setUpdatedAt(System.currentTimeMillis());
}
}
| 2,951 | 41.171429 | 149 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.plugin;
import java.util.Arrays;
import java.util.function.Consumer;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
public class PluginDbTester {
private final DbClient dbClient;
private final DbSession dbSession;
public PluginDbTester(DbTester db) {
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
@SafeVarargs
public final PluginDto insertPlugin(Consumer<PluginDto>... consumers) {
PluginDto pluginDto = PluginTesting.newPluginDto();
Arrays.stream(consumers).forEach(c -> c.accept(pluginDto));
dbClient.pluginDao().insert(dbSession, pluginDto);
dbSession.commit();
return pluginDto;
}
}
| 1,566 | 32.340426 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.plugin;
import org.sonar.core.util.Uuids;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
public class PluginTesting {
private PluginTesting() {
// prevent instantiation
}
/**
* Create an instance of {@link PluginDto} with random field values.
*/
public static PluginDto newPluginDto() {
String uuid = Uuids.createFast();
return new PluginDto()
.setUuid(uuid)
.setKee(uuid)
.setFileHash(randomAlphanumeric(32))
.setCreatedAt(nextLong())
.setUpdatedAt(nextLong());
}
}
| 1,490 | 30.723404 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/InternalComponentPropertyDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.property;
import java.util.Optional;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
public class InternalComponentPropertyDbTester {
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public InternalComponentPropertyDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public void insertProperty(String componentUuid, String key, String value) {
dbClient.internalComponentPropertiesDao().insertOrUpdate(dbSession, componentUuid, key, value);
db.commit();
}
public Optional<InternalComponentPropertyDto> getProperty(String componentUuid, String key) {
return dbClient.internalComponentPropertiesDao().selectByComponentUuidAndKey(dbSession, componentUuid, key);
}
}
| 1,718 | 35.574468 | 112 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.property;
import com.google.common.base.Joiner;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.entity.EntityDto;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto;
import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto;
public class PropertyDbTester {
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public PropertyDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public PropertyDto insertProperty(PropertyDto property, @Nullable String componentKey,
@Nullable String componentName, @Nullable String qualifier, @Nullable String userLogin) {
dbClient.propertiesDao().saveProperty(dbSession, property, userLogin, componentKey, componentName, qualifier);
db.commit();
return property;
}
public void insertProperties(@Nullable String userLogin, @Nullable String projectKey,
@Nullable String projectName, @Nullable String qualifier, PropertyDto... properties) {
insertProperties(asList(properties), userLogin, projectKey, projectName, qualifier);
}
public void insertProperties(List<PropertyDto> properties, @Nullable String userLogin, @Nullable String projectKey,
@Nullable String projectName, @Nullable String qualifier) {
for (PropertyDto propertyDto : properties) {
dbClient.propertiesDao().saveProperty(dbSession, propertyDto, userLogin, projectKey, projectName, qualifier);
}
dbSession.commit();
}
public void insertProperty(String propKey, String propValue, @Nullable String componentUuid) {
insertProperties(singletonList(new PropertyDto()
.setKey(propKey)
.setValue(propValue)
.setEntityUuid(componentUuid)),
null, null, null, null);
}
public void insertPropertySet(String settingBaseKey, @Nullable EntityDto entity, Map<String, String>... fieldValues) {
int index = 1;
List<PropertyDto> propertyDtos = new ArrayList<>();
List<String> ids = new ArrayList<>();
for (Map<String, String> fieldValue : fieldValues) {
for (Map.Entry<String, String> entry : fieldValue.entrySet()) {
String key = settingBaseKey + "." + index + "." + entry.getKey();
if (entity != null) {
propertyDtos.add(newComponentPropertyDto(entity).setKey(key).setValue(entry.getValue()));
} else {
propertyDtos.add(newGlobalPropertyDto().setKey(key).setValue(entry.getValue()));
}
}
ids.add(Integer.toString(index));
index++;
}
String idsValue = Joiner.on(",").join(ids);
if (entity != null) {
propertyDtos.add(newComponentPropertyDto(entity).setKey(settingBaseKey).setValue(idsValue));
} else {
propertyDtos.add(newGlobalPropertyDto().setKey(settingBaseKey).setValue(idsValue));
}
String componentKey = entity == null ? null : entity.getKey();
String componentName = entity == null ? null : entity.getName();
String qualififer = entity == null ? null : entity.getQualifier();
insertProperties(propertyDtos, null, componentKey, componentName, qualififer);
}
public Optional<PropertyDto> findFirstUserProperty(String userUuid, String key) {
PropertyQuery query = new PropertyQuery.Builder()
.setUserUuid(userUuid)
.setKey(key)
.build();
return dbClient.propertiesDao().selectByQuery(query, dbSession).stream().findFirst();
}
}
| 4,602 | 39.026087 | 120 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/property/PropertyTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.property;
import javax.annotation.Nullable;
import org.apache.commons.lang.math.RandomUtils;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Preconditions.checkNotNull;
public class PropertyTesting {
private static int cursor = RandomUtils.nextInt(100);
private PropertyTesting() {
// static methods only
}
public static PropertyDto newGlobalPropertyDto(String key, String value) {
return newPropertyDto(key, value, (String) null, null);
}
public static PropertyDto newGlobalPropertyDto() {
return newPropertyDto((String) null, null);
}
public static PropertyDto newComponentPropertyDto(String key, String value, EntityDto component) {
checkNotNull(component.getUuid());
return newPropertyDto(key, value, component.getUuid(), null);
}
public static PropertyDto newComponentPropertyDto(EntityDto entity) {
checkNotNull(entity.getUuid());
return newPropertyDto(entity.getUuid(), null);
}
public static PropertyDto newUserPropertyDto(String key, String value, UserDto user) {
checkNotNull(user.getUuid());
return newPropertyDto(key, value, null, user.getUuid());
}
public static PropertyDto newUserPropertyDto(UserDto user) {
checkNotNull(user.getUuid());
return newPropertyDto(null, user.getUuid());
}
private static PropertyDto newPropertyDto(@Nullable String componentUuid, @Nullable String userUuid) {
String key = String.valueOf(cursor);
cursor++;
String value = String.valueOf(cursor);
cursor++;
return newPropertyDto(key, value, componentUuid, userUuid);
}
private static PropertyDto newPropertyDto(String key, String value, @Nullable String componentUuid, @Nullable String userUuid) {
PropertyDto propertyDto = new PropertyDto()
.setKey(key)
.setValue(value);
if (componentUuid != null) {
propertyDto.setEntityUuid(componentUuid);
}
if (userUuid != null) {
propertyDto.setUserUuid(userUuid);
}
return propertyDto;
}
}
| 2,912 | 32.482759 | 130 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.qualitygate;
import java.util.Arrays;
import java.util.Date;
import java.util.Optional;
import java.util.function.Consumer;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.RandomStringUtils.randomNumeric;
public class QualityGateDbTester {
private static final String DEFAULT_QUALITY_GATE_PROPERTY_NAME = "qualitygate.default";
private final DbTester db;
private final DbClient dbClient;
private final DbSession dbSession;
public QualityGateDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
this.dbSession = db.getSession();
}
public QualityGateDto insertBuiltInQualityGate() {
QualityGateDto builtin = dbClient.qualityGateDao().insert(dbSession, new QualityGateDto()
.setName("Sonar way")
.setUuid(Uuids.createFast())
.setBuiltIn(true)
.setCreatedAt(new Date()));
dbSession.commit();
return builtin;
}
@SafeVarargs
public final QualityGateDto insertQualityGate(Consumer<QualityGateDto>... dtoPopulators) {
QualityGateDto qualityGate = new QualityGateDto()
.setName(randomAlphanumeric(30))
.setUuid(Uuids.createFast())
.setBuiltIn(false);
Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(qualityGate));
dbClient.qualityGateDao().insert(dbSession, qualityGate);
db.commit();
return dbClient.qualityGateDao().selectByUuid(dbSession, qualityGate.getUuid());
}
public void associateProjectToQualityGate(ProjectDto project, QualityGateDto qualityGate) {
dbClient.projectQgateAssociationDao().insertProjectQGateAssociation(dbSession, project.getUuid(), qualityGate.getUuid());
db.commit();
}
@SafeVarargs
public final QualityGateDto createDefaultQualityGate(Consumer<QualityGateDto>... dtoPopulators) {
QualityGateDto defaultQGate = insertQualityGate(dtoPopulators);
setDefaultQualityGate(defaultQGate);
return defaultQGate;
}
public void setDefaultQualityGate(QualityGateDto qualityGate) {
dbClient.propertiesDao().saveProperty(new PropertyDto().setKey(DEFAULT_QUALITY_GATE_PROPERTY_NAME).setValue(qualityGate.getUuid()));
dbSession.commit();
}
@SafeVarargs
public final QualityGateConditionDto addCondition(QualityGateDto qualityGate, MetricDto metric, Consumer<QualityGateConditionDto>... dtoPopulators) {
QualityGateConditionDto condition = new QualityGateConditionDto().setQualityGateUuid(qualityGate.getUuid())
.setUuid(Uuids.createFast())
.setMetricUuid(metric.getUuid())
.setOperator("GT")
.setErrorThreshold(randomNumeric(10));
Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(condition));
dbClient.gateConditionDao().insert(condition, dbSession);
db.commit();
return condition;
}
public Optional<String> selectQGateUuidByProjectUuid(String projectUuid) {
return dbClient.projectQgateAssociationDao().selectQGateUuidByProjectUuid(dbSession, projectUuid);
}
public void addGroupPermission(QualityGateDto qualityGateDto, GroupDto group) {
dbClient.qualityGateGroupPermissionsDao().insert(dbSession, new QualityGateGroupPermissionsDto()
.setUuid(Uuids.createFast())
.setGroupUuid(group.getUuid())
.setQualityGateUuid(qualityGateDto.getUuid()),
qualityGateDto.getName(),
group.getName()
);
dbSession.commit();
}
public void addUserPermission(QualityGateDto qualityGateDto, UserDto user) {
dbClient.qualityGateUserPermissionDao().insert(dbSession, new QualityGateUserPermissionsDto()
.setUuid(Uuids.createFast())
.setUserUuid(user.getUuid())
.setQualityGateUuid(qualityGateDto.getUuid()),
qualityGateDto.getName(),
user.getLogin());
dbSession.commit();
}
}
| 4,991 | 37.697674 | 151 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.qualityprofile;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
import org.sonar.api.rule.Severity;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.math.RandomUtils.nextInt;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
import static org.sonar.db.qualityprofile.ActiveRuleDto.createFor;
public class QualityProfileDbTester {
private final DbClient dbClient;
private final DbSession dbSession;
public QualityProfileDbTester(DbTester dbTester) {
this.dbClient = dbTester.getDbClient();
this.dbSession = dbTester.getSession();
}
public Optional<QProfileDto> selectByUuid(String uuid) {
return Optional.ofNullable(dbClient.qualityProfileDao().selectByUuid(dbSession, uuid));
}
/**
* Create a profile with random field values.
*/
public QProfileDto insert() {
return insert(c -> {
});
}
/**
* Create a profile with random field values
*/
public QProfileDto insert(Consumer<QProfileDto> consumer) {
QProfileDto profile = QualityProfileTesting.newQualityProfileDto();
consumer.accept(profile);
dbClient.qualityProfileDao().insert(dbSession, profile);
dbSession.commit();
return profile;
}
public QualityProfileDbTester insert(QProfileDto profile, QProfileDto... others) {
dbClient.qualityProfileDao().insert(dbSession, profile);
Arrays.stream(others).forEach(p -> dbClient.qualityProfileDao().insert(dbSession, p));
dbSession.commit();
return this;
}
public QualityProfileDbTester associateWithProject(ProjectDto project, QProfileDto profile, QProfileDto... otherProfiles) {
dbClient.qualityProfileDao().insertProjectProfileAssociation(dbSession, project, profile);
for (QProfileDto p : otherProfiles) {
dbClient.qualityProfileDao().insertProjectProfileAssociation(dbSession, project, p);
}
dbSession.commit();
return this;
}
public ActiveRuleDto activateRule(QProfileDto profile, RuleDto rule) {
return activateRule(profile, rule, ar -> {
});
}
public ActiveRuleDto activateRule(QProfileDto profile, RuleDto rule, Consumer<ActiveRuleDto> consumer) {
ActiveRuleDto activeRule = createFor(profile, rule)
.setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size())))
.setCreatedAt(nextLong())
.setUpdatedAt(nextLong());
consumer.accept(activeRule);
dbClient.activeRuleDao().insert(dbSession, activeRule);
dbSession.commit();
return activeRule;
}
public QualityProfileDbTester setAsDefault(QProfileDto profile, QProfileDto... others) {
dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(profile));
for (QProfileDto other : others) {
dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(other));
}
dbSession.commit();
return this;
}
public void addUserPermission(QProfileDto profile, UserDto user) {
checkArgument(!profile.isBuiltIn(), "Built-In profile cannot be used");
dbClient.qProfileEditUsersDao().insert(dbSession, new QProfileEditUsersDto()
.setUuid(Uuids.createFast())
.setUserUuid(user.getUuid())
.setQProfileUuid(profile.getKee()),
profile.getName(), user.getLogin()
);
dbSession.commit();
}
public void addGroupPermission(QProfileDto profile, GroupDto group) {
checkArgument(!profile.isBuiltIn(), "Built-In profile cannot be used");
dbClient.qProfileEditGroupsDao().insert(dbSession, new QProfileEditGroupsDto()
.setUuid(Uuids.createFast())
.setGroupUuid(group.getUuid())
.setQProfileUuid(profile.getKee()),
profile.getName(), group.getName());
dbSession.commit();
}
}
| 4,894 | 34.992647 | 125 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.qualityprofile;
import java.util.function.Consumer;
import org.sonar.core.util.Uuids;
import static java.util.Arrays.stream;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
public class QualityProfileTesting {
private QualityProfileTesting() {
// prevent instantiation
}
/**
* Create an instance of {@link QProfileDto} with random field values.
*/
public static QProfileDto newQualityProfileDto() {
String uuid = Uuids.createFast();
return new QProfileDto()
.setKee(uuid)
.setRulesProfileUuid(Uuids.createFast())
.setName(uuid)
.setLanguage(randomAlphanumeric(20))
.setLastUsed(nextLong());
}
/**
* Create an instance of {@link QProfileChangeDto} with random field values,
* except changeType which is always {@code "ACTIVATED"}.
*/
public static QProfileChangeDto newQProfileChangeDto() {
return new QProfileChangeDto()
.setUuid(randomAlphanumeric(40))
.setRulesProfileUuid(randomAlphanumeric(40))
.setCreatedAt(nextLong())
.setChangeType("ACTIVATED")
.setUserUuid("userUuid_" + randomAlphanumeric(10));
}
/**
* Create an instance of {@link RulesProfileDto} with most of random field values.
*/
public static RulesProfileDto newRuleProfileDto(Consumer<RulesProfileDto>... populators) {
RulesProfileDto dto = new RulesProfileDto()
.setUuid("uuid" + randomAlphabetic(10))
.setName("name" + randomAlphabetic(10))
.setLanguage("lang" + randomAlphabetic(5))
.setIsBuiltIn(false);
stream(populators).forEach(p -> p.accept(dto));
return dto;
}
}
| 2,636 | 34.16 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.rule;
import java.util.Arrays;
import java.util.Random;
import java.util.function.Consumer;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
import static java.util.Arrays.asList;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.db.rule.RuleTesting.newDeprecatedRuleKey;
import static org.sonar.db.rule.RuleTesting.newRule;
public class RuleDbTester {
private static final RuleType[] RULE_TYPES_EXCEPT_HOTSPOTS = Arrays.stream(RuleType.values())
.filter(ruleType -> SECURITY_HOTSPOT != ruleType).toArray(RuleType[]::new);
private final DbTester db;
public RuleDbTester(DbTester db) {
this.db = db;
}
public RuleDto insert() {
return insert(newRule());
}
public RuleDto insert(RuleKey key) {
return insert(newRule(key));
}
@SafeVarargs
public final RuleDto insert(Consumer<RuleDto>... populaters) {
RuleDto rule = newRule();
asList(populaters).forEach(populater -> populater.accept(rule));
return insert(rule);
}
public RuleDto insert(RuleKey key, Consumer<RuleDto> populater) {
RuleDto rule = newRule(key);
populater.accept(rule);
return insert(rule);
}
public RuleDto insertIssueRule() {
return insert(newIssueRule());
}
public RuleDto insertIssueRule(RuleKey key) {
return insert(newIssueRule(key));
}
@SafeVarargs
public final RuleDto insertIssueRule(Consumer<RuleDto>... populaters) {
RuleDto rule = newIssueRule();
asList(populaters).forEach(populater -> populater.accept(rule));
return insert(rule);
}
public RuleDto insertIssueRule(RuleKey key, Consumer<RuleDto> populater) {
RuleDto rule = newIssueRule(key);
populater.accept(rule);
return insert(rule);
}
private static RuleDto newIssueRule(RuleKey key) {
return newRule(key).setType(RULE_TYPES_EXCEPT_HOTSPOTS[new Random().nextInt(RULE_TYPES_EXCEPT_HOTSPOTS.length)]);
}
private static RuleDto newIssueRule() {
return newRule().setType(RULE_TYPES_EXCEPT_HOTSPOTS[new Random().nextInt(RULE_TYPES_EXCEPT_HOTSPOTS.length)]);
}
public RuleDto insertHotspotRule() {
return insert(newHotspotRule());
}
@SafeVarargs
public final RuleDto insertHotspotRule(Consumer<RuleDto>... populaters) {
RuleDto rule = newHotspotRule();
asList(populaters).forEach(populater -> populater.accept(rule));
return insert(rule);
}
private static RuleDto newHotspotRule() {
return newRule().setType(SECURITY_HOTSPOT);
}
public RuleDto insert(RuleDto rule) {
if (rule.getUuid() == null) {
rule.setUuid(Uuids.createFast());
}
db.getDbClient().ruleDao().insert(db.getSession(), rule);
db.commit();
return rule;
}
public RuleDto update(RuleDto rule) {
db.getDbClient().ruleDao().update(db.getSession(), rule);
db.commit();
return rule;
}
@SafeVarargs
public final RuleParamDto insertRuleParam(RuleDto rule, Consumer<RuleParamDto>... populaters) {
RuleParamDto param = RuleTesting.newRuleParam(rule);
asList(populaters).forEach(populater -> populater.accept(param));
db.getDbClient().ruleDao().insertRuleParam(db.getSession(), rule, param);
db.commit();
return param;
}
/**
* Create and persist a rule with random values.
*/
public RuleDto insertRule() {
return insertRule(rule -> {
});
}
@SafeVarargs
public final RuleDto insertRule(Consumer<RuleDto>... populaters) {
RuleDto ruleDto = RuleTesting.newRule();
asList(populaters).forEach(populater -> populater.accept(ruleDto));
return insert(ruleDto);
}
public RuleDto insertRule(Consumer<RuleDto> populateRuleDto) {
RuleDto ruleDto = RuleTesting.newRule();
populateRuleDto.accept(ruleDto);
if (ruleDto.getUuid() == null) {
ruleDto.setUuid(Uuids.createFast());
}
return insert(ruleDto);
}
@SafeVarargs
public final DeprecatedRuleKeyDto insertDeprecatedKey(Consumer<DeprecatedRuleKeyDto>... deprecatedRuleKeyDtoConsumers) {
DeprecatedRuleKeyDto deprecatedRuleKeyDto = newDeprecatedRuleKey();
asList(deprecatedRuleKeyDtoConsumers).forEach(c -> c.accept(deprecatedRuleKeyDto));
db.getDbClient().ruleDao().insert(db.getSession(), deprecatedRuleKeyDto);
return deprecatedRuleKeyDto;
}
}
| 5,203 | 29.611765 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.rule;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
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.rules.RuleType;
import org.sonar.api.server.rule.RuleParamType;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.rule.RuleDto.Scope;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Arrays.stream;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextInt;
import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX;
import static org.sonar.api.rules.RuleType.CODE_SMELL;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
/**
* Utility class for tests involving rules
*/
public class RuleTesting {
public static final RuleKey EXTERNAL_XOO = RuleKey.of(EXTERNAL_RULE_REPO_PREFIX + "xoo", "x1");
public static final RuleKey XOO_X1 = RuleKey.of("xoo", "x1");
public static final RuleKey XOO_X2 = RuleKey.of("xoo", "x2");
public static final RuleKey XOO_X3 = RuleKey.of("xoo", "x3");
private static final AtomicLong nextRuleId = new AtomicLong(0);
private static final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
private RuleTesting() {
// only static helpers
}
public static RuleDto newRule() {
return newRule(RuleKey.of(randomAlphanumeric(30), randomAlphanumeric(30)));
}
public static RuleDto newRule(RuleDescriptionSectionDto... ruleDescriptionSectionDtos) {
return newRule(randomRuleKey(), ruleDescriptionSectionDtos);
}
public static RuleDto newRule(RuleKey key, RuleDescriptionSectionDto... ruleDescriptionSectionDtos) {
RuleDto ruleDto = newRuleWithoutDescriptionSection(key);
if (ruleDescriptionSectionDtos.length == 0) {
ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + randomAlphabetic(5)));
} else {
stream(ruleDescriptionSectionDtos).forEach(ruleDto::addRuleDescriptionSectionDto);
}
return ruleDto;
}
public static RuleDto newRuleWithoutDescriptionSection() {
return newRuleWithoutDescriptionSection(randomRuleKey());
}
public static RuleDto newRuleWithoutDescriptionSection(RuleKey ruleKey) {
long currentTimeMillis = System.currentTimeMillis();
return new RuleDto()
.setRepositoryKey(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setUuid("rule_uuid_" + randomAlphanumeric(5))
.setName("name_" + randomAlphanumeric(5))
.setDescriptionFormat(RuleDto.Format.HTML)
.setType(CODE_SMELL)
.setStatus(RuleStatus.READY)
.setConfigKey("configKey_" + ruleKey.rule())
.setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size())))
.setIsTemplate(false)
.setIsExternal(false)
.setIsAdHoc(false)
.setSystemTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5)))
.setLanguage("lang_" + randomAlphanumeric(3))
.setGapDescription("gapDescription_" + randomAlphanumeric(5))
.setDefRemediationBaseEffort(nextInt(10) + "h")
//voluntarily offset the remediation to be able to detect issues
.setDefRemediationGapMultiplier((nextInt(10) + 10) + "h")
.setDefRemediationFunction("LINEAR_OFFSET")
.setRemediationBaseEffort(nextInt(10) + "h")
.setRemediationGapMultiplier(nextInt(10) + "h")
.setRemediationFunction("LINEAR_OFFSET")
.setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5)))
.setNoteData("noteData_" + randomAlphanumeric(5))
.setNoteUserUuid("noteUserUuid_" + randomAlphanumeric(5))
.setNoteCreatedAt(System.currentTimeMillis() - 200)
.setNoteUpdatedAt(System.currentTimeMillis() - 150)
.setAdHocName("adHocName_" + randomAlphanumeric(5))
.setAdHocDescription("adHocDescription_" + randomAlphanumeric(5))
.setAdHocSeverity(Severity.ALL.get(nextInt(Severity.ALL.size())))
.setAdHocType(RuleType.values()[nextInt(RuleType.values().length - 1)])
.setCreatedAt(currentTimeMillis)
.setUpdatedAt(currentTimeMillis + 5)
.setScope(Scope.MAIN)
.setEducationPrinciples(Set.of(randomAlphanumeric(5), randomAlphanumeric(5)));
}
public static RuleParamDto newRuleParam(RuleDto rule) {
return new RuleParamDto()
.setRuleUuid(rule.getUuid())
.setName("name_" + randomAlphabetic(5))
.setDefaultValue("default_" + randomAlphabetic(5))
.setDescription("description_" + randomAlphabetic(5))
.setType(RuleParamType.STRING.type());
}
public static DeprecatedRuleKeyDto newDeprecatedRuleKey() {
return new DeprecatedRuleKeyDto()
.setUuid(uuidFactory.create())
.setOldRepositoryKey(randomAlphanumeric(50))
.setOldRuleKey(randomAlphanumeric(50))
.setRuleUuid(randomAlphanumeric(40))
.setCreatedAt(System.currentTimeMillis());
}
public static RuleDto newXooX1() {
return newRule(XOO_X1).setLanguage("xoo");
}
public static RuleDto newXooX2() {
return newRule(XOO_X2).setLanguage("xoo");
}
public static RuleDto newTemplateRule(RuleKey ruleKey) {
return newRule(ruleKey)
.setIsTemplate(true);
}
public static RuleDto newCustomRule(RuleDto templateRule) {
return newCustomRule(templateRule, "description_" + randomAlphabetic(5));
}
public static RuleDto newCustomRule(RuleDto templateRule, String description) {
checkNotNull(templateRule.getUuid(), "The template rule need to be persisted before creating this custom rule.");
RuleDescriptionSectionDto defaultRuleDescriptionSection = createDefaultRuleDescriptionSection(uuidFactory.create(), description);
return newRule(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis()), defaultRuleDescriptionSection)
.setLanguage(templateRule.getLanguage())
.setTemplateUuid(templateRule.getUuid())
.setType(templateRule.getType());
}
public static RuleKey randomRuleKey() {
return RuleKey.of("repo_" + getNextUniqueId(), "rule_" + getNextUniqueId());
}
private static String getNextUniqueId() {
return String.format("%010d", nextRuleId.getAndIncrement());
}
public static Consumer<RuleDto> setRepositoryKey(String repositoryKey) {
return rule -> rule.setRepositoryKey(repositoryKey);
}
public static Consumer<RuleDto> setCreatedAt(long createdAt) {
return rule -> rule.setCreatedAt(createdAt);
}
public static Consumer<RuleDto> setUpdatedAt(long updatedtAt) {
return rule -> rule.setUpdatedAt(updatedtAt);
}
public static Consumer<RuleDto> setRuleKey(String ruleKey) {
return rule -> rule.setRuleKey(ruleKey);
}
public static Consumer<RuleDto> setName(String name) {
return rule -> rule.setName(name);
}
public static Consumer<RuleDto> setLanguage(String language) {
return rule -> rule.setLanguage(language);
}
public static Consumer<RuleDto> setSeverity(String severity) {
return rule -> rule.setSeverity(severity);
}
public static Consumer<RuleDto> setStatus(RuleStatus status) {
return rule -> rule.setStatus(status);
}
public static Consumer<RuleDto> setType(RuleType type) {
return rule -> rule.setType(type);
}
public static Consumer<RuleDto> setIsExternal(boolean isExternal) {
return rule -> rule.setIsExternal(isExternal);
}
public static Consumer<RuleDto> setSecurityStandards(Set<String> securityStandards) {
return rule -> rule.setSecurityStandards(securityStandards);
}
public static Consumer<RuleDto> setIsTemplate(boolean isTemplate) {
return rule -> rule.setIsTemplate(isTemplate);
}
public static Consumer<RuleDto> setTemplateId(@Nullable String templateUuid) {
return rule -> rule.setTemplateUuid(templateUuid);
}
public static Consumer<RuleDto> setSystemTags(String... tags) {
return rule -> rule.setSystemTags(copyOf(tags));
}
public static Consumer<RuleDto> setTags(String... tags) {
return rule -> rule.setTags(copyOf(tags));
}
}
| 9,335 | 37.9 | 156 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.source;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import org.apache.commons.lang.math.RandomUtils;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.protobuf.DbFileSources;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
public class FileSourceTester {
private final DbTester db;
public FileSourceTester(DbTester db) {
this.db = db;
}
@SafeVarargs
public final FileSourceDto insertFileSource(ComponentDto file, Consumer<FileSourceDto>... dtoPopulators) {
FileSourceDto dto = new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(file.branchUuid())
.setFileUuid(file.uuid())
.setSrcHash(randomAlphanumeric(50))
.setDataHash(randomAlphanumeric(50))
.setLineHashes(IntStream.range(0, new Random().nextInt(21)).mapToObj(String::valueOf).toList())
.setRevision(randomAlphanumeric(100))
.setSourceData(newRandomData(3).build())
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
Arrays.stream(dtoPopulators).forEach(c -> c.accept(dto));
db.getDbClient().fileSourceDao().insert(db.getSession(), dto);
db.commit();
dto.setUuid(db.getDbClient().fileSourceDao().selectByFileUuid(db.getSession(), dto.getFileUuid()).getUuid());
return dto;
}
@SafeVarargs
public final FileSourceDto insertFileSource(ComponentDto file, int numLines, Consumer<FileSourceDto>... dtoPopulators) {
FileSourceDto dto = new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(file.branchUuid())
.setFileUuid(file.uuid())
.setSrcHash(randomAlphanumeric(50))
.setDataHash(randomAlphanumeric(50))
.setLineHashes(IntStream.range(0, numLines).mapToObj(String::valueOf).toList())
.setRevision(randomAlphanumeric(100))
.setSourceData(newRandomData(numLines).build())
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
Arrays.stream(dtoPopulators).forEach(c -> c.accept(dto));
db.getDbClient().fileSourceDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
private static DbFileSources.Data.Builder newRandomData(int numberOfLines) {
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
for (int i = 1; i <= numberOfLines; i++) {
dataBuilder.addLinesBuilder()
.setLine(i)
.setScmRevision(randomAlphanumeric(15))
.setScmAuthor(randomAlphanumeric(10))
.setScmDate(RandomUtils.nextLong())
.setSource(randomAlphanumeric(20))
.setLineHits(RandomUtils.nextInt(4))
.setConditions(RandomUtils.nextInt(4))
.setCoveredConditions(RandomUtils.nextInt(4))
.setHighlighting(randomAlphanumeric(40))
.setSymbols(randomAlphanumeric(30))
.addAllDuplication(Arrays.asList(RandomUtils.nextInt(200), RandomUtils.nextInt(200)))
.build();
}
return dataBuilder;
}
}
| 3,982 | 38.04902 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.user;
import java.util.Date;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
public class GroupTesting {
private GroupTesting() {
// only statics
}
public static GroupDto newGroupDto() {
return new GroupDto()
.setUuid(randomAlphanumeric(40))
.setName(randomAlphanumeric(255))
.setDescription(randomAlphanumeric(200))
.setCreatedAt(new Date(nextLong()))
.setUpdatedAt(new Date(nextLong()));
}
}
| 1,402 | 32.404762 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.user;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.security.DefaultGroups;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.ce.CeTaskMessageType;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.permission.GroupPermissionDto;
import org.sonar.db.permission.UserPermissionDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.scim.ScimGroupDto;
import org.sonar.db.scim.ScimUserDto;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Arrays.stream;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.db.user.GroupTesting.newGroupDto;
public class UserDbTester {
private static final Set<String> PUBLIC_PERMISSIONS = Set.of(UserRole.USER, UserRole.CODEVIEWER);
public static final String PERMISSIONS_CANT_BE_GRANTED_ON_BRANCHES = "Permissions can't be granted on branches";
private final DbTester db;
private final DbClient dbClient;
public UserDbTester(DbTester db) {
this.db = db;
this.dbClient = db.getDbClient();
}
// USERS
public UserDto insertUser() {
return insertUser(UserTesting.newUserDto());
}
public UserDto insertUser(String login) {
UserDto dto = UserTesting.newUserDto().setLogin(login).setActive(true);
return insertUser(dto);
}
@SafeVarargs
public final UserDto insertUser(Consumer<UserDto>... populators) {
UserDto dto = UserTesting.newUserDto().setActive(true);
stream(populators).forEach(p -> p.accept(dto));
return insertUser(dto);
}
public ScimUserDto insertScimUser(UserDto userDto) {
ScimUserDto scimUserDto = dbClient.scimUserDao().enableScimForUser(db.getSession(), userDto.getUuid());
db.commit();
return scimUserDto;
}
@SafeVarargs
public final UserDto insertDisabledUser(Consumer<UserDto>... populators) {
UserDto dto = UserTesting.newDisabledUser();
stream(populators).forEach(p -> p.accept(dto));
return insertUser(dto);
}
public UserDto insertUser(UserDto userDto) {
UserDto updatedUser = dbClient.userDao().insert(db.getSession(), userDto);
db.commit();
return updatedUser;
}
public ScimUserDto enableScimForUser(UserDto userDto) {
ScimUserDto scimUSerDto = db.getDbClient().scimUserDao().enableScimForUser(db.getSession(), userDto.getUuid());
db.commit();
return scimUSerDto;
}
public UserDto insertAdminByUserPermission() {
UserDto user = insertUser();
insertGlobalPermissionOnUser(user, ADMINISTER);
return user;
}
public UserDto updateLastConnectionDate(UserDto user, long lastConnectionDate) {
db.getDbClient().userDao().update(db.getSession(), user.setLastConnectionDate(lastConnectionDate));
db.getSession().commit();
return user;
}
public UserDto updateSonarLintLastConnectionDate(UserDto user, long sonarLintLastConnectionDate) {
db.getDbClient().userDao().update(db.getSession(), user.setLastSonarlintConnectionDate(sonarLintLastConnectionDate));
db.getSession().commit();
return user;
}
public Optional<UserDto> selectUserByLogin(String login) {
return Optional.ofNullable(dbClient.userDao().selectByLogin(db.getSession(), login));
}
public Optional<UserDto> selectUserByEmail(String email) {
List<UserDto> users = dbClient.userDao().selectByEmail(db.getSession(), email);
if (users.size() > 1) {
return Optional.empty();
}
return Optional.of(users.get(0));
}
public Optional<UserDto> selectUserByExternalIdAndIdentityProvider(String externalId, String identityProvider) {
return Optional.ofNullable(dbClient.userDao().selectByExternalIdAndIdentityProvider(db.getSession(), externalId, identityProvider));
}
// GROUPS
public GroupDto insertGroup(String name) {
GroupDto group = newGroupDto().setName(name);
return insertGroup(group);
}
@SafeVarargs
public final GroupDto insertGroup(Consumer<GroupDto>... populators) {
GroupDto group = newGroupDto();
stream(populators).forEach(p -> p.accept(group));
return insertGroup(group);
}
public GroupDto insertGroup(GroupDto dto) {
db.getDbClient().groupDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
public void markGroupAsGithubManaged(String groupUuid) {
db.getDbClient().externalGroupDao().insert(db.getSession(), new ExternalGroupDto(groupUuid, randomAlphanumeric(20), "github"));
db.commit();
}
public ExternalGroupDto insertExternalGroup(ExternalGroupDto dto) {
db.getDbClient().externalGroupDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
public ScimGroupDto insertScimGroup(GroupDto dto) {
ScimGroupDto result = db.getDbClient().scimGroupDao().enableScimForGroup(db.getSession(), dto.getUuid());
db.commit();
return result;
}
public GroupDto insertDefaultGroup() {
GroupDto dto = db.getDbClient().groupDao().insert(db.getSession(), newGroupDto().setName(DefaultGroups.USERS).setDescription("Users"));
db.commit();
return dto;
}
@CheckForNull
public GroupDto selectGroupByUuid(String groupUuid) {
return db.getDbClient().groupDao().selectByUuid(db.getSession(), groupUuid);
}
public Optional<GroupDto> selectGroup(String name) {
return db.getDbClient().groupDao().selectByName(db.getSession(), name);
}
public int countAllGroups() {
return db.getDbClient().groupDao().countByQuery(db.getSession(), new GroupQuery(null, null));
}
public Optional<ExternalGroupDto> selectExternalGroupByGroupUuid(String groupUuid) {
return db.getDbClient().externalGroupDao().selectByGroupUuid(db.getSession(), groupUuid);
}
// GROUP MEMBERSHIP
public UserGroupDto insertMember(GroupDto group, UserDto user) {
UserGroupDto dto = new UserGroupDto().setGroupUuid(group.getUuid()).setUserUuid(user.getUuid());
db.getDbClient().userGroupDao().insert(db.getSession(), dto, group.getName(), user.getLogin());
db.commit();
return dto;
}
public void insertMembers(GroupDto group, UserDto... users) {
Arrays.stream(users).forEach(user -> {
UserGroupDto dto = new UserGroupDto().setGroupUuid(group.getUuid()).setUserUuid(user.getUuid());
db.getDbClient().userGroupDao().insert(db.getSession(), dto, group.getName(), user.getLogin());
});
db.commit();
}
public List<UserDto> findMembers(GroupDto group) {
Set<String> userUuidsInGroup = db.getDbClient().userGroupDao().selectUserUuidsInGroup(db.getSession(), group.getUuid());
return db.getDbClient().userDao().selectByUuids(db.getSession(), userUuidsInGroup);
}
public List<String> selectGroupUuidsOfUser(UserDto user) {
return db.getDbClient().groupMembershipDao().selectGroupUuidsByUserUuid(db.getSession(), user.getUuid());
}
// GROUP PERMISSIONS
public GroupPermissionDto insertPermissionOnAnyone(String permission) {
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(Uuids.createFast())
.setGroupUuid(null)
.setRole(permission);
db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, null, null);
db.commit();
return dto;
}
public GroupPermissionDto insertPermissionOnAnyone(GlobalPermission permission) {
return insertPermissionOnAnyone(permission.getKey());
}
public GroupPermissionDto insertPermissionOnGroup(GroupDto group, String permission) {
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(Uuids.createFast())
.setGroupUuid(group.getUuid())
.setRole(permission);
db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, (EntityDto) null, null);
db.commit();
return dto;
}
public GroupPermissionDto insertPermissionOnGroup(GroupDto group, GlobalPermission permission) {
return insertPermissionOnGroup(group, permission.getKey());
}
public GroupPermissionDto insertProjectPermissionOnAnyone(String permission, ComponentDto project) {
checkArgument(!project.isPrivate(), "No permission to group AnyOne can be granted on a private project");
checkArgument(!PUBLIC_PERMISSIONS.contains(permission),
"permission %s can't be granted on a public project", permission);
Optional<BranchDto> branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.branchUuid());
// I don't know if this check is worth it
branchDto.ifPresent(dto -> checkArgument(dto.isMain(), PERMISSIONS_CANT_BE_GRANTED_ON_BRANCHES));
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(Uuids.createFast())
.setGroupUuid(null)
.setRole(permission)
.setEntityUuid(project.uuid())
.setEntityName(project.name());
// TODO, will be removed later
ProjectDto projectDto = new ProjectDto();
projectDto.setQualifier(project.qualifier());
projectDto.setKey(project.getKey());
db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, projectDto, null);
db.commit();
return dto;
}
public GroupPermissionDto insertEntityPermissionOnAnyone(String permission, EntityDto entity) {
checkArgument(!entity.isPrivate(), "No permission to group AnyOne can be granted on a private entity");
checkArgument(!PUBLIC_PERMISSIONS.contains(permission),
"permission %s can't be granted on a public entity", permission);
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(Uuids.createFast())
.setGroupUuid(null)
.setRole(permission)
.setEntityUuid(entity.getUuid())
.setEntityName(entity.getName());
db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, entity, null);
db.commit();
return dto;
}
public void deleteProjectPermissionFromAnyone(EntityDto entity, String permission) {
db.getDbClient().groupPermissionDao().delete(db.getSession(), permission, null, null, entity);
db.commit();
}
public GroupPermissionDto insertProjectPermissionOnGroup(GroupDto group, String permission, ComponentDto project) {
checkArgument(project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission),
"%s can't be granted on a public project", permission);
Optional<BranchDto> branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.branchUuid());
// I don't know if this check is worth it
branchDto.ifPresent(dto -> checkArgument(dto.isMain(), PERMISSIONS_CANT_BE_GRANTED_ON_BRANCHES));
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(Uuids.createFast())
.setGroupUuid(group.getUuid())
.setGroupName(group.getName())
.setRole(permission)
.setEntityUuid(project.uuid())
.setEntityName(project.name());
// TODO, will be removed later
ProjectDto projectDto = new ProjectDto();
projectDto.setQualifier(project.qualifier());
projectDto.setKey(project.getKey());
db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, projectDto, null);
db.commit();
return dto;
}
public GroupPermissionDto insertEntityPermissionOnGroup(GroupDto group, String permission, EntityDto entity) {
checkArgument(entity.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission),
"%s can't be granted on a public entity (project or portfolio)", permission);
Optional<BranchDto> branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), entity.getUuid());
// I don't know if this check is worth it
branchDto.ifPresent(dto -> checkArgument(dto.isMain(), PERMISSIONS_CANT_BE_GRANTED_ON_BRANCHES));
GroupPermissionDto dto = new GroupPermissionDto()
.setUuid(Uuids.createFast())
.setGroupUuid(group.getUuid())
.setGroupName(group.getName())
.setRole(permission)
.setEntityUuid(entity.getUuid())
.setEntityName(entity.getName());
db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, entity, null);
db.commit();
return dto;
}
public List<String> selectGroupPermissions(GroupDto group, @Nullable EntityDto entity) {
if (entity == null) {
return db.getDbClient().groupPermissionDao().selectGlobalPermissionsOfGroup(db.getSession(), group.getUuid());
}
return db.getDbClient().groupPermissionDao().selectEntityPermissionsOfGroup(db.getSession(), group.getUuid(), entity.getUuid());
}
public List<String> selectAnyonePermissions(@Nullable String entityUuid) {
if (entityUuid == null) {
return db.getDbClient().groupPermissionDao().selectGlobalPermissionsOfGroup(db.getSession(), null);
}
return db.getDbClient().groupPermissionDao().selectEntityPermissionsOfGroup(db.getSession(), null, entityUuid);
}
// USER PERMISSIONS
/**
* Grant global permission
*/
public UserPermissionDto insertGlobalPermissionOnUser(UserDto user, GlobalPermission permission) {
return insertPermissionOnUser(user, permission.getKey());
}
/**
* Grant permission
*/
public UserPermissionDto insertPermissionOnUser(UserDto user, String permission) {
UserPermissionDto dto = new UserPermissionDto(Uuids.create(), permission, user.getUuid(), null);
db.getDbClient().userPermissionDao().insert(db.getSession(), dto, (EntityDto) null, user, null);
db.commit();
return dto;
}
public void deletePermissionFromUser(UserDto user, GlobalPermission permission) {
db.getDbClient().userPermissionDao().deleteGlobalPermission(db.getSession(), user, permission.getKey());
db.commit();
}
public void deletePermissionFromUser(EntityDto project, UserDto user, String permission) {
db.getDbClient().userPermissionDao().deleteEntityPermission(db.getSession(), user, permission, project);
db.commit();
}
/**
* Grant permission on given project
*/
public UserPermissionDto insertProjectPermissionOnUser(UserDto user, String permission, ComponentDto project) {
checkArgument(project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission),
"%s can't be granted on a public project", permission);
EntityDto entityDto;
if (project.qualifier().equals(Qualifiers.VIEW) || project.qualifier().equals(Qualifiers.SUBVIEW)) {
entityDto = db.getDbClient().portfolioDao().selectByUuid(db.getSession(), project.uuid())
.orElseThrow();
} else {
BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.branchUuid())
.orElseThrow();
// I don't know if this check is worth it
checkArgument(branchDto.isMain(), PERMISSIONS_CANT_BE_GRANTED_ON_BRANCHES);
entityDto = dbClient.projectDao().selectByBranchUuid(db.getSession(), branchDto.getUuid())
.orElseThrow();
}
UserPermissionDto dto = new UserPermissionDto(Uuids.create(), permission, user.getUuid(), entityDto.getUuid());
db.getDbClient().userPermissionDao().insert(db.getSession(), dto, entityDto, user, null);
db.commit();
return dto;
}
public UserPermissionDto insertProjectPermissionOnUser(UserDto user, String permission, EntityDto project) {
checkArgument(project.isPrivate() || !PUBLIC_PERMISSIONS.contains(permission),
"%s can't be granted on a public project", permission);
UserPermissionDto dto = new UserPermissionDto(Uuids.create(), permission, user.getUuid(), project.getUuid());
db.getDbClient().userPermissionDao().insert(db.getSession(), dto, project, user, null);
db.commit();
return dto;
}
public List<GlobalPermission> selectPermissionsOfUser(UserDto user) {
return toListOfGlobalPermissions(db.getDbClient().userPermissionDao()
.selectGlobalPermissionsOfUser(db.getSession(), user.getUuid()));
}
public List<String> selectEntityPermissionOfUser(UserDto user, String entityUuid) {
return db.getDbClient().userPermissionDao().selectEntityPermissionsOfUser(db.getSession(), user.getUuid(), entityUuid);
}
private static List<GlobalPermission> toListOfGlobalPermissions(List<String> keys) {
return keys
.stream()
.map(GlobalPermission::fromKey)
.toList();
}
// USER TOKEN
@SafeVarargs
public final UserTokenDto insertToken(UserDto user, Consumer<UserTokenDto>... populators) {
UserTokenDto dto = UserTokenTesting.newUserToken().setUserUuid(user.getUuid());
stream(populators).forEach(p -> p.accept(dto));
db.getDbClient().userTokenDao().insert(db.getSession(), dto, user.getLogin());
db.commit();
return dto;
}
// PROJECT ANALYSIS TOKEN
@SafeVarargs
public final UserTokenDto insertProjectAnalysisToken(UserDto user, Consumer<UserTokenDto>... populators) {
UserTokenDto dto = UserTokenTesting.newProjectAnalysisToken().setUserUuid(user.getUuid());
stream(populators).forEach(p -> p.accept(dto));
db.getDbClient().userTokenDao().insert(db.getSession(), dto, user.getLogin());
db.commit();
return dto;
}
// SESSION TOKENS
@SafeVarargs
public final SessionTokenDto insertSessionToken(UserDto user, Consumer<SessionTokenDto>... populators) {
SessionTokenDto dto = new SessionTokenDto()
.setUserUuid(user.getUuid())
.setExpirationDate(nextLong());
stream(populators).forEach(p -> p.accept(dto));
db.getDbClient().sessionTokensDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
public final UserDismissedMessageDto insertUserDismissedMessage(UserDto userDto, ProjectDto projectDto, CeTaskMessageType messageType) {
UserDismissedMessageDto dto = new UserDismissedMessageDto()
.setUuid(Uuids.create())
.setUserUuid(userDto.getUuid())
.setProjectUuid(projectDto.getUuid())
.setCeMessageType(messageType);
db.getDbClient().userDismissedMessagesDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
}
| 19,083 | 38.429752 | 139 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.user;
import java.util.Locale;
import javax.annotation.Nullable;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextBoolean;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
public class UserTesting {
public static UserDto newUserDto() {
return new UserDto()
.setUuid(randomAlphanumeric(40))
.setActive(true)
.setLocal(nextBoolean())
.setLogin(randomAlphanumeric(30))
.setName(randomAlphanumeric(30))
.setEmail(randomAlphanumeric(30))
.setScmAccounts(singletonList(randomAlphanumeric(40).toLowerCase(Locale.ENGLISH)))
.setExternalId(randomAlphanumeric(40))
.setExternalLogin(randomAlphanumeric(40))
.setExternalIdentityProvider(randomAlphanumeric(40))
.setSalt(randomAlphanumeric(40))
.setCryptedPassword(randomAlphanumeric(40))
.setCreatedAt(nextLong())
.setUpdatedAt(nextLong());
}
public static UserDto newUserDto(String login, String name, @Nullable String email) {
return newUserDto()
.setName(name)
.setEmail(email)
.setLogin(login);
}
public static UserDto newLocalUser(String login, String name, @Nullable String email) {
return newUserDto()
.setLocal(true)
.setName(name)
.setEmail(email)
.setLogin(login)
.setExternalId(login)
.setExternalLogin(login)
.setExternalIdentityProvider("sonarqube");
}
public static UserDto newExternalUser(String login, String name, @Nullable String email) {
return newUserDto()
.setLocal(false)
.setName(name)
.setEmail(email)
.setLogin(login)
.setExternalId(randomAlphanumeric(40))
.setExternalLogin(randomAlphanumeric(40))
.setExternalIdentityProvider(randomAlphanumeric(40));
}
public static UserDto newDisabledUser() {
return newUserDto()
.setActive(false)
// All these fields are reset when disabling a user
.setScmAccounts(emptyList())
.setEmail(null)
.setCryptedPassword(null)
.setSalt(null);
}
}
| 3,076 | 33.188889 | 92 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.user;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
public class UserTokenTesting {
private UserTokenTesting() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static UserTokenDto newUserToken() {
return new UserTokenDto()
.setUserUuid("userUuid_" + randomAlphanumeric(40))
.setName("name_" + randomAlphanumeric(20))
.setTokenHash("hash_" + randomAlphanumeric(30))
.setCreatedAt(nextLong())
.setType("USER_TOKEN");
}
public static UserTokenDto newProjectAnalysisToken() {
return new UserTokenDto()
.setUserUuid("userUuid_" + randomAlphanumeric(40))
.setName("name_" + randomAlphanumeric(20))
.setTokenHash("hash_" + randomAlphanumeric(30))
.setProjectUuid("projectUuid_" + randomAlphanumeric(20))
.setProjectKey("projectKey_" + randomAlphanumeric(40))
.setProjectName("Project " + randomAlphanumeric(40))
.setCreatedAt(nextLong())
.setType("PROJECT_ANALYSIS_TOKEN");
}
}
| 1,995 | 36.660377 | 98 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.webhook;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import static org.sonar.db.webhook.WebhookTesting.newGlobalWebhook;
import static org.sonar.db.webhook.WebhookTesting.newWebhook;
public class WebhookDbTester {
private final DbTester dbTester;
public WebhookDbTester(DbTester dbTester) {
this.dbTester = dbTester;
}
public WebhookDto insertGlobalWebhook() {
return insert(newGlobalWebhook(), null, null);
}
public WebhookDto insertWebhook(ProjectDto project) {
return insert(newWebhook(project), project.getKey(), project.getName());
}
public WebhookDto insert(WebhookDto dto, @Nullable String projectKey, @Nullable String projectName) {
DbSession dbSession = dbTester.getSession();
dbTester.getDbClient().webhookDao().insert(dbSession, dto, projectKey, projectName);
dbSession.commit();
return dto;
}
public Optional<WebhookDto> selectWebhook(String uuid) {
DbSession dbSession = dbTester.getSession();
return dbTester.getDbClient().webhookDao().selectByUuid(dbSession, uuid);
}
}
| 2,034 | 33.491525 | 103 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryDbTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.webhook;
import java.util.Objects;
import java.util.function.Consumer;
import org.sonar.db.DbTester;
import static java.util.Arrays.stream;
import static org.sonar.db.webhook.WebhookDeliveryTesting.newDto;
public class WebhookDeliveryDbTester {
private final DbTester dbTester;
public WebhookDeliveryDbTester(DbTester dbTester) {
this.dbTester = dbTester;
}
public WebhookDeliveryLiteDto insert(WebhookDeliveryDto dto) {
dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto);
dbTester.getSession().commit();
return dto;
}
@SafeVarargs
public final WebhookDeliveryLiteDto insert(Consumer<WebhookDeliveryDto>... dtoPopulators) {
WebhookDeliveryDto dto = newDto();
stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto));
dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto);
dbTester.getSession().commit();
return dto;
}
@SafeVarargs
public final WebhookDeliveryLiteDto insert(WebhookDto webhook, Consumer<WebhookDeliveryDto>... dtoPopulators) {
WebhookDeliveryDto dto = newDto();
stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(dto));
String projectUuid = webhook.getProjectUuid();
dto.setProjectUuid(Objects.requireNonNull(projectUuid, "Project uuid of webhook cannot be null"));
dto.setWebhookUuid(webhook.getUuid());
dbTester.getDbClient().webhookDeliveryDao().insert(dbTester.getSession(), dto);
dbTester.getSession().commit();
return dto;
}
}
| 2,395 | 35.861538 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.webhook;
import java.util.List;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextBoolean;
import static org.apache.commons.lang.math.RandomUtils.nextInt;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
public class WebhookDeliveryTesting {
private WebhookDeliveryTesting() {
// only statics
}
/**
* Build a {@link WebhookDeliveryDto} with all mandatory fields.
* Optional fields are kept null.
*/
public static WebhookDeliveryDto newDto(String uuid, String webhookUuid, String projectUuid, String ceTaskUuid) {
return newDto()
.setUuid(uuid)
.setWebhookUuid(webhookUuid)
.setProjectUuid(projectUuid)
.setCeTaskUuid(ceTaskUuid);
}
public static WebhookDeliveryDto newDto() {
return new WebhookDeliveryDto()
.setUuid(Uuids.createFast())
.setWebhookUuid(randomAlphanumeric(40))
.setProjectUuid(randomAlphanumeric(40))
.setCeTaskUuid(randomAlphanumeric(40))
.setAnalysisUuid(randomAlphanumeric(40))
.setName(randomAlphanumeric(10))
.setUrl(randomAlphanumeric(10))
.setDurationMs(nextInt())
.setHttpStatus(nextInt())
.setSuccess(nextBoolean())
.setPayload(randomAlphanumeric(10))
.setCreatedAt(nextLong());
}
public static List<String> selectAllDeliveryUuids(DbTester dbTester, DbSession dbSession) {
return dbTester.select(dbSession, "select uuid as \"uuid\" from webhook_deliveries")
.stream()
.map(columns -> (String) columns.get("uuid"))
.toList();
}
}
| 2,578 | 34.328767 | 115 | java |
sonarqube | sonarqube-master/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.db.webhook;
import java.util.Arrays;
import java.util.Calendar;
import java.util.function.Consumer;
import org.sonar.db.project.ProjectDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
public class WebhookTesting {
private WebhookTesting() {
// only statics
}
public static WebhookDto newWebhook(ProjectDto project) {
return getWebhookDto()
.setProjectUuid(project.getUuid());
}
public static WebhookDto newProjectWebhook(String projectUuid) {
return getWebhookDto()
.setProjectUuid(projectUuid);
}
public static WebhookDto newGlobalWebhook() {
return getWebhookDto();
}
@SafeVarargs
public static WebhookDto newGlobalWebhook(String name, Consumer<WebhookDto>... consumers) {
return getWebhookDto(consumers)
.setName(name);
}
@SafeVarargs
private static WebhookDto getWebhookDto(Consumer<WebhookDto>... consumers) {
WebhookDto res = new WebhookDto()
.setUuid(randomAlphanumeric(40))
.setName(randomAlphanumeric(64))
.setUrl("https://www.random-site/" + randomAlphanumeric(256))
.setSecret(randomAlphanumeric(10))
.setCreatedAt(Calendar.getInstance().getTimeInMillis());
Arrays.stream(consumers).forEach(consumer -> consumer.accept(res));
return res;
}
}
| 2,163 | 31.298507 | 93 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/DatabaseMigration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
public interface DatabaseMigration {
/**
* Starts the migration status and returns immediately.
* <p>
* Migration can not be started twice but calling this method wont raise an error.
* </p>
*/
void startIt();
}
| 1,125 | 33.121212 | 84 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/DatabaseMigrationState.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
import java.util.Date;
import javax.annotation.CheckForNull;
public interface DatabaseMigrationState {
enum Status {
NONE, RUNNING, FAILED, SUCCEEDED
}
/**
* Current status of the migration.
*/
Status getStatus();
/**
* The time and day the last migration was started.
* <p>
* If no migration was ever started, the returned date is {@code null}.
* </p>
*
* @return a {@link Date} or {@code null}
*/
@CheckForNull
Date getStartedAt();
/**
* The error of the last migration if it failed.
*
* @return a {@link Throwable} or {@code null}
*/
@CheckForNull
Throwable getError();
}
| 1,535 | 26.927273 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/DatabaseMigrationStateImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
import java.util.Date;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
/**
* This implementation of {@link MutableDatabaseMigrationState} does not provide any thread safety.
*/
public class DatabaseMigrationStateImpl implements MutableDatabaseMigrationState {
private Status status = Status.NONE;
@Nullable
private Date startedAt;
@Nullable
private Throwable error;
@Override
public Status getStatus() {
return status;
}
@Override
public void setStatus(Status status) {
this.status = status;
}
@Override
@CheckForNull
public Date getStartedAt() {
return startedAt;
}
@Override
public void setStartedAt(@Nullable Date startedAt) {
this.startedAt = startedAt;
}
@Override
@CheckForNull
public Throwable getError() {
return error;
}
@Override
public void setError(@Nullable Throwable error) {
this.error = error;
}
}
| 1,813 | 25.676471 | 99 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/MigrationConfigurationModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
import org.sonar.core.platform.Module;
import org.sonar.server.platform.db.migration.history.MigrationHistoryImpl;
import org.sonar.server.platform.db.migration.history.MigrationHistoryMeddler;
import org.sonar.server.platform.db.migration.history.MigrationHistoryTableImpl;
import org.sonar.server.platform.db.migration.sql.DbPrimaryKeyConstraintFinder;
import org.sonar.server.platform.db.migration.sql.DropPrimaryKeySqlGenerator;
import org.sonar.server.platform.db.migration.step.MigrationStepRegistryImpl;
import org.sonar.server.platform.db.migration.step.MigrationStepsProvider;
import org.sonar.server.platform.db.migration.version.v00.DbVersion00;
import org.sonar.server.platform.db.migration.version.v100.DbVersion100;
import org.sonar.server.platform.db.migration.version.v101.DbVersion101;
import org.sonar.server.platform.db.migration.version.v102.DbVersion102;
public class MigrationConfigurationModule extends Module {
@Override
protected void configureModule() {
add(
MigrationHistoryTableImpl.class,
// DbVersion implementations
DbVersion00.class,
DbVersion100.class,
DbVersion101.class,
DbVersion102.class,
// migration steps
MigrationStepRegistryImpl.class,
new MigrationStepsProvider(),
// history
MigrationHistoryImpl.class,
MigrationHistoryMeddler.class,
// Utility classes
DbPrimaryKeyConstraintFinder.class,
DropPrimaryKeySqlGenerator.class);
}
}
| 2,368 | 39.152542 | 80 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/MigrationEngineModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
import org.sonar.core.platform.Module;
import org.sonar.server.platform.db.migration.engine.MigrationEngineImpl;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl;
/**
* Defines the components for the migration engine.
*/
public class MigrationEngineModule extends Module {
@Override
protected void configureModule() {
add(
MigrationStepsExecutorImpl.class,
MigrationEngineImpl.class);
}
}
| 1,335 | 35.108108 | 78 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/MutableDatabaseMigrationState.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
import java.util.Date;
import javax.annotation.Nullable;
public interface MutableDatabaseMigrationState extends DatabaseMigrationState {
void setStatus(Status status);
void setStartedAt(@Nullable Date startedAt);
void setError(@Nullable Throwable error);
}
| 1,158 | 35.21875 | 79 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/NoopDatabaseMigrationImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
/**
* Implementation of {@link DatabaseMigration} which performs no operation at all.
* It is meant to be used when the platform in NOT in safe mode, which means that the database is up to date
* and migration is neither required nor should be performed.
*/
public class NoopDatabaseMigrationImpl implements DatabaseMigration {
@Override
public void startIt() {
// do nothing
}
}
| 1,288 | 35.828571 | 108 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/SupportsBlueGreen.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Mark an instance of {@link org.sonar.server.platform.db.migration.step.MigrationStep}
* as compatible with blue/green deployment
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SupportsBlueGreen {
}
| 1,349 | 35.486486 | 88 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.platform.db.migration;
import javax.annotation.ParametersAreNonnullByDefault;
| 979 | 38.2 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/CharsetHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
abstract class CharsetHandler {
protected static final String UTF8 = "utf8";
private final SqlExecutor selectExecutor;
protected CharsetHandler(SqlExecutor selectExecutor) {
this.selectExecutor = selectExecutor;
}
abstract void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException;
protected SqlExecutor getSqlExecutor() {
return selectExecutor;
}
}
| 1,370 | 31.642857 | 102 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/ColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.version.SqTables;
/**
* Result of standard SQL command "select * from INFORMATION_SCHEMA" (columns listed in {@link #SELECT_COLUMNS}).
*/
@Immutable
public class ColumnDef {
public static final String SELECT_COLUMNS = "select table_name, column_name, character_set_name, collation_name, data_type, character_maximum_length, is_nullable ";
private final String table;
private final String column;
private final String charset;
private final String collation;
private final String dataType;
private final long size;
private final boolean nullable;
public ColumnDef(String table, String column, String charset, String collation, String dataType, long size, boolean nullable) {
this.table = table;
this.column = column;
this.charset = charset;
this.collation = collation;
this.dataType = dataType;
this.size = size;
this.nullable = nullable;
}
public String getTable() {
return table;
}
public String getColumn() {
return column;
}
public String getCharset() {
return charset;
}
public String getCollation() {
return collation;
}
public String getDataType() {
return dataType;
}
public long getSize() {
return size;
}
public boolean isNullable() {
return nullable;
}
public boolean isInSonarQubeTable() {
String tableName = table.toLowerCase(Locale.ENGLISH);
return SqTables.TABLES.contains(tableName);
}
public enum ColumnDefRowConverter implements SqlExecutor.RowConverter<ColumnDef> {
INSTANCE;
@Override
public ColumnDef convert(ResultSet rs) throws SQLException {
String nullableText = rs.getString(7);
boolean nullable = "FIRST".equalsIgnoreCase(nullableText);
return new ColumnDef(
rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getLong(6), nullable);
}
}
}
| 2,929 | 28.3 | 166 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/DatabaseCharsetChecker.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import com.google.common.annotations.VisibleForTesting;
import java.sql.Connection;
import java.sql.SQLException;
import javax.annotation.CheckForNull;
import javax.inject.Inject;
import org.sonar.db.Database;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
/**
* On fresh installations, checks that all db columns are UTF8. On MSSQL,
* whatever fresh or upgrade, fixes case-insensitive columns by converting them to
* case-sensitive.
* <p>
* See SONAR-6171 and SONAR-7549
*/
public class DatabaseCharsetChecker {
public enum State {
FRESH_INSTALL, UPGRADE, STARTUP
}
private final Database db;
private final SqlExecutor sqlExecutor;
@Inject
public DatabaseCharsetChecker(Database db) {
this(db, new SqlExecutor());
}
@VisibleForTesting
DatabaseCharsetChecker(Database db, SqlExecutor sqlExecutor) {
this.db = db;
this.sqlExecutor = sqlExecutor;
}
public void check(State state) {
try (Connection connection = db.getDataSource().getConnection()) {
CharsetHandler handler = getHandler(db.getDialect());
if (handler != null) {
handler.handle(connection, state);
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
@VisibleForTesting
@CheckForNull
CharsetHandler getHandler(Dialect dialect) {
switch (dialect.getId()) {
case H2.ID:
// nothing to check
return null;
case Oracle.ID:
return new OracleCharsetHandler(sqlExecutor);
case PostgreSql.ID:
return new PostgresCharsetHandler(sqlExecutor, new PostgresMetadataReader(sqlExecutor));
case MsSql.ID:
return new MssqlCharsetHandler(sqlExecutor, new MssqlMetadataReader(sqlExecutor));
default:
throw new IllegalArgumentException("Database not supported: " + dialect.getId());
}
}
}
| 2,869 | 30.538462 | 96 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import com.google.common.annotations.VisibleForTesting;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.containsIgnoreCase;
class MssqlCharsetHandler extends CharsetHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MssqlCharsetHandler.class);
private static final String CASE_SENSITIVE_ACCENT_SENSITIVE = "_CS_AS";
private static final String CASE_INSENSITIVE_ACCENT_INSENSITIVE = "_CI_AI";
private static final String CASE_INSENSITIVE_ACCENT_SENSITIVE = "_CI_AS";
private static final String CASE_SENSITIVE_ACCENT_INSENSITIVE = "_CS_AI";
private static final String BIN = "BIN";
private static final String BIN2 = "BIN2";
private final MssqlMetadataReader metadata;
MssqlCharsetHandler(SqlExecutor selectExecutor, MssqlMetadataReader metadataReader) {
super(selectExecutor);
this.metadata = metadataReader;
}
@Override
void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
expectCaseSensitiveDefaultCollation(connection);
if (state == DatabaseCharsetChecker.State.UPGRADE || state == DatabaseCharsetChecker.State.STARTUP) {
repairColumns(connection);
}
}
private void expectCaseSensitiveDefaultCollation(Connection connection) throws SQLException {
LOGGER.info("Verify that database collation is case-sensitive and accent-sensitive");
String defaultCollation = metadata.getDefaultCollation(connection);
if (!isCollationCorrect(defaultCollation)) {
String fixedCollation = toCaseSensitive(defaultCollation);
throw MessageException.of(format(
"Database collation must be case-sensitive and accent-sensitive. It is %s but should be %s.", defaultCollation, fixedCollation));
}
}
private void repairColumns(Connection connection) throws SQLException {
String defaultCollation = metadata.getDefaultCollation(connection);
// All VARCHAR columns are returned. No need to check database general collation.
// Example of row:
// issues | kee | Latin1_General_CS_AS or Latin1_General_100_CI_AS_KS_WS
List<ColumnDef> columns = metadata.getColumnDefs(connection);
for (ColumnDef column : columns.stream().filter(ColumnDef::isInSonarQubeTable).toList()) {
String collation = column.getCollation();
if (!isCollationCorrect(collation)) {
repairColumnCollation(connection, column, toCaseSensitive(collation));
} else if ("Latin1_General_CS_AS".equals(collation) && !collation.equals(defaultCollation)) {
repairColumnCollation(connection, column, defaultCollation);
}
}
}
/**
* Collation is correct if contains {@link #CASE_SENSITIVE_ACCENT_SENSITIVE} or {@link #BIN} or {@link #BIN2}.
*/
private static boolean isCollationCorrect(String collation) {
return containsIgnoreCase(collation, CASE_SENSITIVE_ACCENT_SENSITIVE)
|| containsIgnoreCase(collation, BIN)
|| containsIgnoreCase(collation, BIN2);
}
private void repairColumnCollation(Connection connection, ColumnDef column, String expectedCollation) throws SQLException {
// 1. select the indices defined on this column
List<ColumnIndex> indices = metadata.getColumnIndices(connection, column);
// 2. drop indices
for (ColumnIndex index : indices) {
getSqlExecutor().executeDdl(connection, format("DROP INDEX %s.%s", column.getTable(), index.name));
}
// 3. alter collation of column
String nullability = column.isNullable() ? "NULL" : "NOT NULL";
String size = column.getSize() >= 0 ? String.valueOf(column.getSize()) : "max";
String alterSql = format("ALTER TABLE %s ALTER COLUMN %s %s(%s) COLLATE %s %s",
column.getTable(), column.getColumn(), column.getDataType(), size, expectedCollation, nullability);
LOGGER.info("Changing collation of column [{}.{}] from {} to {} | sql=", column.getTable(), column.getColumn(), column.getCollation(), expectedCollation, alterSql);
getSqlExecutor().executeDdl(connection, alterSql);
// 4. re-create indices
for (ColumnIndex index : indices) {
String uniqueSql = index.unique ? "UNIQUE" : "";
String createIndexSql = format("CREATE %s INDEX %s ON %s (%s)", uniqueSql, index.name, column.getTable(), index.csvColumns);
getSqlExecutor().executeDdl(connection, createIndexSql);
}
}
@VisibleForTesting
static String toCaseSensitive(String collation) {
// Example: Latin1_General_CI_AI --> Latin1_General_CS_AS or Latin1_General_100_CI_AS_KS_WS --> Latin1_General_100_CS_AS_KS_WS
return collation
.replace(CASE_INSENSITIVE_ACCENT_INSENSITIVE, CASE_SENSITIVE_ACCENT_SENSITIVE)
.replace(CASE_INSENSITIVE_ACCENT_SENSITIVE, CASE_SENSITIVE_ACCENT_SENSITIVE)
.replace(CASE_SENSITIVE_ACCENT_INSENSITIVE, CASE_SENSITIVE_ACCENT_SENSITIVE);
}
@VisibleForTesting
static class ColumnIndex {
private final String name;
private final boolean unique;
private final String csvColumns;
public ColumnIndex(String name, boolean unique, String csvColumns) {
this.name = name;
this.unique = unique;
this.csvColumns = csvColumns;
}
}
@VisibleForTesting
enum ColumnIndexConverter implements SqlExecutor.RowConverter<ColumnIndex> {
INSTANCE;
@Override
public ColumnIndex convert(ResultSet rs) throws SQLException {
return new ColumnIndex(rs.getString(1), rs.getBoolean(2), rs.getString(3));
}
}
}
| 6,561 | 41.888889 | 168 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/MssqlMetadataReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import static java.lang.String.format;
class MssqlMetadataReader {
private final SqlExecutor sqlExecutor;
MssqlMetadataReader(SqlExecutor sqlExecutor) {
this.sqlExecutor = sqlExecutor;
}
String getDefaultCollation(Connection connection) throws SQLException {
return sqlExecutor.selectSingleString(connection, "SELECT CONVERT(VARCHAR(128), DATABASEPROPERTYEX(DB_NAME(), 'Collation'))");
}
List<ColumnDef> getColumnDefs(Connection connection) throws SQLException {
return sqlExecutor.select(connection,
ColumnDef.SELECT_COLUMNS +
"FROM [INFORMATION_SCHEMA].[COLUMNS] " +
"WHERE collation_name is not null " +
"ORDER BY table_name,column_name",
ColumnDef.ColumnDefRowConverter.INSTANCE);
}
List<MssqlCharsetHandler.ColumnIndex> getColumnIndices(Connection connection, ColumnDef column) throws SQLException {
String selectIndicesSql = format("SELECT I.name as index_name, I.is_unique as unik, IndexedColumns " +
" FROM sys.indexes I " +
" JOIN sys.tables T ON T.Object_id = I.Object_id " +
" JOIN (SELECT * FROM ( " +
" SELECT IC2.object_id, IC2.index_id, " +
" STUFF((SELECT ' ,' + C.name " +
" FROM sys.index_columns IC1 " +
" JOIN sys.columns C " +
" ON C.object_id = IC1.object_id " +
" AND C.column_id = IC1.column_id " +
" AND IC1.is_included_column = 0 " +
" WHERE IC1.object_id = IC2.object_id " +
" AND IC1.index_id = IC2.index_id " +
" GROUP BY IC1.object_id,C.name,index_id " +
" ORDER BY MAX(IC1.key_ordinal) " +
" FOR XML PATH('')), 1, 2, '') IndexedColumns " +
" FROM sys.index_columns IC2 " +
" GROUP BY IC2.object_id ,IC2.index_id) tmp1 )tmp2 " +
" ON I.object_id = tmp2.object_id AND I.Index_id = tmp2.index_id " +
" WHERE I.is_primary_key = 0 AND I.is_unique_constraint = 0 " +
" and T.name =('%s') " +
" and CHARINDEX ('%s',IndexedColumns)>0", column.getTable(), column.getColumn());
return sqlExecutor.select(connection, selectIndicesSql, MssqlCharsetHandler.ColumnIndexConverter.INSTANCE);
}
}
| 3,182 | 42.013514 | 130 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/OracleCharsetHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
import org.sonar.api.utils.MessageException;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.containsIgnoreCase;
class OracleCharsetHandler extends CharsetHandler {
OracleCharsetHandler(SqlExecutor selectExecutor) {
super(selectExecutor);
}
@Override
public void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
// Charset is a global setting on Oracle, it can't be set on a specified schema with a
// different value. To not block users who already have a SonarQube schema, charset
// is verified only on fresh installs but not on upgrades. Let's hope they won't face
// any errors related to charset if they didn't follow the UTF8 requirement when creating
// the schema in previous SonarQube versions.
if (state == DatabaseCharsetChecker.State.FRESH_INSTALL) {
LoggerFactory.getLogger(getClass()).info("Verify that database charset is UTF8");
expectUtf8(connection);
}
}
private void expectUtf8(Connection connection) throws SQLException {
// Oracle does not allow to override character set on tables. Only global charset is verified.
String charset = getSqlExecutor().selectSingleString(connection, "select value from nls_database_parameters where parameter='NLS_CHARACTERSET'");
if (!containsIgnoreCase(charset, UTF8)) {
throw MessageException.of(format("Oracle NLS_CHARACTERSET does not support UTF8: %s", charset));
}
}
}
| 2,484 | 42.596491 | 149 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/PostgresCharsetHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.utils.MessageException;
import org.slf4j.LoggerFactory;
import org.sonar.db.version.SqTables;
import static java.lang.String.format;
import static java.util.Optional.ofNullable;
import static org.apache.commons.lang.StringUtils.containsIgnoreCase;
import static org.apache.commons.lang.StringUtils.isBlank;
class PostgresCharsetHandler extends CharsetHandler {
private final PostgresMetadataReader metadata;
PostgresCharsetHandler(SqlExecutor selectExecutor, PostgresMetadataReader metadata) {
super(selectExecutor);
this.metadata = metadata;
}
@Override
void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
// PostgreSQL does not have concept of case-sensitive collation. Only charset ("encoding" in postgresql terminology)
// must be verified.
expectUtf8AsDefault(connection);
if (state == DatabaseCharsetChecker.State.UPGRADE || state == DatabaseCharsetChecker.State.STARTUP) {
// no need to check columns on fresh installs... as they are not supposed to exist!
expectUtf8Columns(connection);
}
}
private void expectUtf8AsDefault(Connection connection) throws SQLException {
LoggerFactory.getLogger(getClass()).info("Verify that database charset supports UTF8");
String collation = metadata.getDefaultCharset(connection);
if (!containsIgnoreCase(collation, UTF8)) {
throw MessageException.of(format("Database charset is %s. It must support UTF8.", collation));
}
}
private void expectUtf8Columns(Connection connection) throws SQLException {
// Charset is defined globally and can be overridden on each column.
// This request returns all VARCHAR columns. Charset may be empty.
// Examples:
// issues | key | ''
// projects | name | utf8
var sqTables = getSqTables();
var schema = getSchema(connection);
List<String[]> rows = getSqlExecutor().select(connection, String.format("select table_name, column_name, collation_name " +
"from information_schema.columns " +
"where table_schema='%s' " +
"and table_name in (%s) " +
"and udt_name='varchar' " +
"order by table_name, column_name", schema, sqTables), new SqlExecutor.StringsConverter(3 /* columns returned by SELECT */));
Set<String> errors = new LinkedHashSet<>();
for (String[] row : rows) {
if (!isBlank(row[2]) && !containsIgnoreCase(row[2], UTF8)) {
errors.add(format("%s.%s", row[0], row[1]));
}
}
if (!errors.isEmpty()) {
throw MessageException.of(format("Database columns [%s] must have UTF8 charset.", Joiner.on(", ").join(errors)));
}
}
private static String getSchema(Connection connection) throws SQLException {
return ofNullable(connection.getSchema()).orElse("public");
}
private static String getSqTables() {
return SqTables.TABLES.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
}
@VisibleForTesting
PostgresMetadataReader getMetadata() {
return metadata;
}
}
| 4,206 | 37.953704 | 131 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/PostgresMetadataReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.SQLException;
public class PostgresMetadataReader {
private final SqlExecutor sqlExecutor;
public PostgresMetadataReader(SqlExecutor sqlExecutor) {
this.sqlExecutor = sqlExecutor;
}
public String getDefaultCharset(Connection connection) throws SQLException {
return sqlExecutor.selectSingleString(connection, "select pg_encoding_to_char(encoding) from pg_database where datname = current_database()");
}
}
| 1,372 | 36.108108 | 146 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/SqlExecutor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.CheckForNull;
import org.sonar.db.DatabaseUtils;
public class SqlExecutor {
public <T> List<T> select(Connection connection, String sql, RowConverter<T> rowConverter) throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();
List<T> result = new ArrayList<>();
while (rs.next()) {
result.add(rowConverter.convert(rs));
}
return result;
} finally {
DatabaseUtils.closeQuietly(rs);
DatabaseUtils.closeQuietly(stmt);
}
}
public void executeDdl(Connection connection, String sql) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.execute(sql);
}
}
@CheckForNull
public final String selectSingleString(Connection connection, String sql) throws SQLException {
String[] cols = selectSingleRow(connection, sql, new SqlExecutor.StringsConverter(1));
return cols == null ? null : cols[0];
}
@CheckForNull
public final <T> T selectSingleRow(Connection connection, String sql, SqlExecutor.RowConverter<T> rowConverter) throws SQLException {
List<T> rows = select(connection, sql, rowConverter);
if (rows.isEmpty()) {
return null;
}
if (rows.size() == 1) {
return rows.get(0);
}
throw new IllegalStateException("Expecting only one result for [" + sql + "]");
}
@FunctionalInterface
public interface RowConverter<T> {
T convert(ResultSet rs) throws SQLException;
}
public static class StringsConverter implements RowConverter<String[]> {
private final int nbColumns;
public StringsConverter(int nbColumns) {
this.nbColumns = nbColumns;
}
@Override
public String[] convert(ResultSet rs) throws SQLException {
String[] row = new String[nbColumns];
for (int i = 0; i < nbColumns; i++) {
row[i] = DatabaseUtils.getString(rs, i + 1);
}
return row;
}
}
}
| 3,117 | 30.816327 | 135 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.platform.db.migration.charset;
import javax.annotation.ParametersAreNonnullByDefault;
| 986 | 40.125 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/AbstractColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
public abstract class AbstractColumnDef implements ColumnDef {
private final String columnName;
private final boolean isNullable;
@CheckForNull
private final Object defaultValue;
public AbstractColumnDef(String columnName, boolean isNullable, @Nullable Object defaultValue) {
this.columnName = columnName;
this.isNullable = isNullable;
this.defaultValue = defaultValue;
}
@Override
public String getName() {
return columnName;
}
@Override
public boolean isNullable() {
return isNullable;
}
@Override
public Object getDefaultValue() {
return defaultValue;
}
}
| 1,586 | 29.519231 | 98 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/BigIntegerColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.Oracle;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
@Immutable
public class BigIntegerColumnDef extends AbstractColumnDef {
private BigIntegerColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, null);
}
public static Builder newBigIntegerColumnDefBuilder() {
return new Builder();
}
@Override
public String generateSqlType(Dialect dialect) {
return dialect.getId().equals(Oracle.ID) ? "NUMBER (38)" : "BIGINT";
}
public static class Builder {
@CheckForNull
private String columnName;
private boolean isNullable = true;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public BigIntegerColumnDef build() {
validateColumnName(columnName);
return new BigIntegerColumnDef(this);
}
}
}
| 2,069 | 29.441176 | 88 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/BlobColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
@Immutable
public class BlobColumnDef extends AbstractColumnDef {
public BlobColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, null);
}
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case MsSql.ID -> "VARBINARY(MAX)";
case Oracle.ID, H2.ID -> "BLOB";
case PostgreSql.ID -> "BYTEA";
default -> throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
};
}
public static Builder newBlobColumnDefBuilder() {
return new Builder();
}
public static class Builder {
@CheckForNull
private String columnName;
private boolean isNullable = true;
private Builder() {
// prevents instantiation outside
}
public BlobColumnDef.Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public BlobColumnDef.Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public BlobColumnDef build() {
validateColumnName(columnName);
return new BlobColumnDef(this);
}
}
}
| 2,428 | 30.545455 | 97 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/BooleanColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
/**
* Used to define VARCHAR column
*/
@Immutable
public class BooleanColumnDef extends AbstractColumnDef {
private BooleanColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, builder.defaultValue);
}
public static Builder newBooleanColumnDefBuilder() {
return new Builder();
}
public static Builder newBooleanColumnDefBuilder(String column) {
return newBooleanColumnDefBuilder().setColumnName(column);
}
@Override
public String generateSqlType(Dialect dialect) {
switch (dialect.getId()) {
case PostgreSql.ID, H2.ID:
return "BOOLEAN";
case Oracle.ID:
return "NUMBER(1)";
case MsSql.ID:
return "BIT";
default:
throw new UnsupportedOperationException(String.format("Unknown dialect '%s'", dialect.getId()));
}
}
public static class Builder {
private String columnName;
private Boolean defaultValue = null;
private boolean isNullable = true;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public Builder setDefaultValue(@Nullable Boolean b) {
this.defaultValue = b;
return this;
}
public BooleanColumnDef build() {
validateColumnName(columnName);
return new BooleanColumnDef(this);
}
}
}
| 2,721 | 28.912088 | 104 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/ClobColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
/**
* Used to define CLOB columns
*/
@Immutable
public class ClobColumnDef extends AbstractColumnDef {
private ClobColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, null);
}
public static Builder newClobColumnDefBuilder() {
return new Builder();
}
@Override
public String generateSqlType(Dialect dialect) {
switch (dialect.getId()) {
case MsSql.ID:
return "NVARCHAR (MAX)";
case Oracle.ID, H2.ID:
return "CLOB";
case PostgreSql.ID:
return "TEXT";
default:
throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
}
}
public static class Builder {
private String columnName;
private boolean isNullable = true;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public ClobColumnDef build() {
validateColumnName(columnName);
return new ClobColumnDef(this);
}
}
}
| 2,351 | 28.4 | 88 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/ColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import org.sonar.db.dialect.Dialect;
public interface ColumnDef {
boolean isNullable();
String getName();
String generateSqlType(Dialect dialect);
@CheckForNull
Object getDefaultValue();
}
| 1,138 | 30.638889 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/DecimalColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
@Immutable
public class DecimalColumnDef extends AbstractColumnDef {
public static final int DEFAULT_PRECISION = 38;
public static final int DEFAULT_SCALE = 20;
private final int precision;
private final int scale;
private DecimalColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, null);
this.precision = builder.precision;
this.scale = builder.scale;
}
public static Builder newDecimalColumnDefBuilder() {
return new Builder();
}
public int getPrecision() {
return precision;
}
public int getScale() {
return scale;
}
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case PostgreSql.ID, Oracle.ID -> String.format("NUMERIC (%s,%s)", precision, scale);
case MsSql.ID -> String.format("DECIMAL (%s,%s)", precision, scale);
case H2.ID -> "DOUBLE";
default -> throw new UnsupportedOperationException(String.format("Unknown dialect '%s'", dialect.getId()));
};
}
public static class Builder {
@CheckForNull
private String columnName;
private int precision = DEFAULT_PRECISION;
private int scale = DEFAULT_SCALE;
private boolean isNullable = true;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public Builder setPrecision(int precision) {
this.precision = precision;
return this;
}
public Builder setScale(int scale) {
this.scale = scale;
return this;
}
public DecimalColumnDef build() {
validateColumnName(columnName);
return new DecimalColumnDef(this);
}
}
}
| 3,064 | 28.757282 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/IntegerColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
@Immutable
public class IntegerColumnDef extends AbstractColumnDef {
private IntegerColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, builder.defaultValue);
}
public static Builder newIntegerColumnDefBuilder() {
return new Builder();
}
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case PostgreSql.ID, H2.ID -> "INTEGER";
case MsSql.ID -> "INT";
case Oracle.ID -> "NUMBER(38,0)";
default -> throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
};
}
public static class Builder {
@CheckForNull
private String columnName;
private boolean isNullable = true;
@CheckForNull
private Integer defaultValue = null;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public Builder setDefaultValue(@Nullable Integer i) {
this.defaultValue = i;
return this;
}
public IntegerColumnDef build() {
validateColumnName(columnName);
return new IntegerColumnDef(this);
}
}
}
| 2,568 | 29.951807 | 97 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/TimestampColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
/**
* Used to define TIMESTAMP columns.
*
* @deprecated implemented for compatibility with old tables, but {@link BigIntegerColumnDef}
* must be used for storing datetimes as bigints (no problems regarding timezone).
*/
@Immutable
@Deprecated
public class TimestampColumnDef extends AbstractColumnDef {
private TimestampColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, null);
}
public static Builder newTimestampColumnDefBuilder() {
return new Builder();
}
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case MsSql.ID -> "DATETIME";
case Oracle.ID -> "TIMESTAMP (6)";
case H2.ID, PostgreSql.ID -> "TIMESTAMP";
default -> throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
};
}
public static class Builder {
private String columnName;
private boolean isNullable = true;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setIsNullable(boolean b) {
this.isNullable = b;
return this;
}
public TimestampColumnDef build() {
validateColumnName(columnName);
return new TimestampColumnDef(this);
}
}
}
| 2,527 | 30.6 | 97 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
/**
* Integer that supports at least range [0..128]. Full range depends on database vendor.
*/
@Immutable
public class TinyIntColumnDef extends AbstractColumnDef {
private TinyIntColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, null);
}
public static Builder newTinyIntColumnDefBuilder() {
return new Builder();
}
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case PostgreSql.ID -> "SMALLINT";
case Oracle.ID -> "NUMBER(3)";
case MsSql.ID, H2.ID -> "TINYINT";
default -> throw new UnsupportedOperationException(String.format("Unknown dialect '%s'", dialect.getId()));
};
}
public static class Builder {
@CheckForNull
private String columnName;
private boolean isNullable = true;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public TinyIntColumnDef build() {
validateColumnName(columnName);
return new TinyIntColumnDef(this);
}
}
}
| 2,461 | 30.564103 | 113 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/Validations.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import com.google.common.base.CharMatcher;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import static com.google.common.base.CharMatcher.anyOf;
import static com.google.common.base.CharMatcher.inRange;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
public class Validations {
private static final int TABLE_NAME_MAX_SIZE = 25;
private static final int CONSTRAINT_NAME_MAX_SIZE = 30;
private static final int INDEX_NAME_MAX_SIZE = 30;
private static final CharMatcher DIGIT_CHAR_MATCHER = inRange('0', '9');
private static final CharMatcher LOWER_CASE_ASCII_LETTERS_CHAR_MATCHER = inRange('a', 'z');
private static final CharMatcher UPPER_CASE_ASCII_LETTERS_CHAR_MATCHER = inRange('A', 'Z');
private static final CharMatcher UNDERSCORE_CHAR_MATCHER = anyOf("_");
// TODO: Refactor all existing identifiers that match SQL reserved keywords,
// the list below is used as a workaround for validating existing non-complaint identifiers
private static final String VALUE_COLUMN_NAME = "value";
private static final String GROUPS_TABLE_NAME = "groups";
private static final List<String> ALLOWED_IDENTIFIERS = List.of(VALUE_COLUMN_NAME, GROUPS_TABLE_NAME);
// MS SQL keywords retrieved from: com.microsoft.sqlserver.jdbc.SQLServerDatabaseMetaData#createSqlKeyWords
protected static final Set<String> MSSQL_KEYWORDS = Set.of(
"ADD", "ALL", "ALTER", "AND", "ANY", "AS", "ASC", "AUTHORIZATION",
"BACKUP", "BEGIN", "BETWEEN", "BREAK", "BROWSE", "BULK", "BY",
"CASCADE", "CASE", "CHECK", "CHECKPOINT", "CLOSE", "CLUSTERED", "COALESCE", "COLLATE", "COLUMN", "COMMIT", "COMPUTE", "CONSTRAINT", "CONTAINS",
"CONTAINSTABLE", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER,CURSOR",
"DATABASE", "DBCC", "DEALLOCATE", "DECLARE", "DEFAULT", "DELETE", "DENY", "DESC", "DISK", "DISTINCT", "DISTRIBUTED", "DOUBLE", "DROP", "DUMP",
"ELSE", "END", "ERRLVL", "ESCAPE", "EXCEPT", "EXEC", "EXECUTE", "EXISTS", "EXIT", "EXTERNAL",
"FETCH", "FILE", "FILLFACTOR", "FOR", "FOREIGN", "FREETEXT", "FREETEXTTABLE", "FROM", "FULL", "FUNCTION",
"GOTO", "GRANT", "GROUP",
"HAVING", "HOLDLOCK",
"IDENTITY", "IDENTITY_INSERT", "IDENTITYCOL", "IF", "IN", "INDEX", "INNER", "INSERT", "INTERSECT", "INTO", "IS",
"JOIN",
"KEY", "KILL",
"LEFT", "LIKE",
"LINENO", "LOAD",
"MERGE",
"NATIONAL", "NOCHECK", "NONCLUSTERED", "NOT", "NULL", "NULLIF",
"OF", "OFF", "OFFSETS", "ON", "OPEN", "OPENDATASOURCE", "OPENQUERY", "OPENROWSET", "OPENXML", "OPTION", "OR", "ORDER", "OUTER", "OVER",
"PERCENT", "PIVOT", "PLAN", "PRECISION", "PRIMARY", "PRINT", "PROC", "PROCEDURE", "PUBLIC",
"RAISERROR", "READ", "READTEXT", "RECONFIGURE", "REFERENCES", "REPLICATION", "RESTORE", "RESTRICT",
"RETURN", "REVERT", "REVOKE", "RIGHT", "ROLLBACK", "ROWCOUNT", "ROWGUIDCOL", "RULE",
"SAVE", "SCHEMA", "SECURITYAUDIT", "SELECT", "SEMANTICKEYPHRASETABLE", "SEMANTICSIMILARITYDETAILSTABLE",
"SEMANTICSIMILARITYTABLE", "SESSION_USER", "SET", "SETUSER", "SHUTDOWN", "SOME", "STATISTICS", "SYSTEM_USER",
"TABLE", "TABLESAMPLE", "TEXTSIZE", "THEN", "TO", "TOP", "TRAN", "TRANSACTION", "TRIGGER", "TRUNCATE", "TRY_CONVERT", "TSEQUAL",
"UNION", "UNIQUE", "UNPIVOT", "UPDATE", "UPDATETEXT", "USE", "USER",
"VALUES", "VARYING", "VIEW",
"WAITFOR", "WHEN", "WHERE", "WHILE", "WITH", "WITHIN GROUP", "WRITETEXT");
// H2 SQL keywords retrieved from: http://www.h2database.com/html/advanced.html
protected static final Set<String> H2_KEYWORDS = Set.of(
"ALL", "AND", "ANY", "ARRAY", "AS", "ASYMMETRIC", "AUTHORIZATION",
"BETWEEN", "BOTH",
"CASE", "CAST", "CHECK", "CONSTRAINT", "CROSS", "CURRENT_CATALOG", "CURRENT_DATE", "CURRENT_PATH",
"CURRENT_ROLE", "CURRENT_SCHEMA", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER",
"DAY", "DEFAULT", "DISTINCT",
"ELSE", "END", "EXISTS",
"FALSE", "FETCH", "FILTER", "FOR", "FOREIGN", "FROM", "FULL",
"GROUP", "GROUPS",
"HAVING", "HOUR",
"IF", "ILIKE", "IN", "INNER", "INTERSECT", "INTERVAL", "IS",
"JOIN",
"KEY",
"LEADING", "LEFT", "LIKE", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP",
"MINUS", "MINUTE", "MONTH",
"NATURAL", "NOT", "NULL",
"OFFSET", "ON", "OR", "ORDER", "OVER",
"PARTITION", "PRIMARY",
"QUALIFY",
"RANGE", "REGEXP", "RIGHT", "ROW", "ROWNUM", "ROWS",
"SECOND", "SELECT", "SESSION_USER", "SET", "SOME", "SYMMETRIC", "SYSTEM_USER",
"TABLE", "TO", "TOP", "TRAILING", "TRUE",
"UESCAPE", "UNION", "UNIQUE", "UNKNOWN", "USER", "USING",
"VALUE", "VALUES",
"WHEN", "WHERE", "WINDOW", "WITH",
"YEAR",
"_ROWID_");
// PostgreSQL keywords retrieved from: https://www.postgresql.org/docs/current/sql-keywords-appendix.html
protected static final Set<String> POSTGRESQL_KEYWORDS = Set.of(
"ALL", "AND", "ANY", "ARRAY", "AS", "ASYMMETRIC",
"BIGINT", "BINARY", "BIT", "BOOLEAN", "BOTH",
"CASE", "CAST", "CHAR", "CHARACTER", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "CONCURRENTLY", "CREATE",
"CURRENT_CATALOG", "CURRENT_ROLE", "CURRENT_SCHEMA", "CURRENT_USER",
"DEC", "DECIMAL", "DEFERRABLE", "DESC",
"ELSE", "END", "EXCEPT",
"FALSE", "FOR", "FREEZE", "FROM", "FULL",
"GRANT", "GREATEST", "GROUPING",
"ILIKE", "IN", "INITIALLY", "INTO", "IS", "ISNULL",
"JOIN",
"LATERAL", "LEADING", "LEFT", "LIKE", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP",
"NATIONAL", "NATURAL", "NCHAR", "NOT", "NOTNULL", "NULL",
"OFFSET", "ON", "ONLY", "OR", "OUTER", "OVERLAPS",
"PLACING",
"REFERENCES", "RETURNING",
"SETOF", "SIMILAR", "SMALLINT", "SOME", "SUBSTRING", "SYMMETRIC",
"TABLESAMPLE", "THEN", "TIME", "TIMESTAMP", "TO", "TRAILING", "TREAT", "TRIM", "TRUE",
"USER", "USING",
"VARCHAR", "VARIADIC", "VERBOSE",
"WHEN", "WINDOW", "WITH",
"XMLCONCAT", "XMLELEMENT", "XMLEXISTS", "XMLFOREST", "XMLNAMESPACES", "XMLPARSE", "XMLPI", "XMLROOT", "XMLSERIALIZE", "XMLTABLE",
"YEAR");
protected static final Set<String> ALL_KEYWORDS = Stream.of(MSSQL_KEYWORDS, H2_KEYWORDS, POSTGRESQL_KEYWORDS)
.flatMap(Set::stream)
.collect(Collectors.toSet());
private Validations() {
// Only static stuff here
}
/**
* Ensure {@code columnName} is a valid name for a column.
* @throws NullPointerException if {@code columnName} is {@code null}
* @throws IllegalArgumentException if {@code columnName} is not valid
* @return the same {@code columnName}
* @see #checkDbIdentifier(String, String, int)
*/
public static String validateColumnName(@Nullable String columnName) {
String name = requireNonNull(columnName, "Column name cannot be null");
checkDbIdentifierCharacters(columnName, "Column name");
return name;
}
/**
* Ensure {@code tableName} is a valid name for a table.
* @throws NullPointerException if {@code tableName} is {@code null}
* @throws IllegalArgumentException if {@code tableName} is not valid
* @return the same {@code tableName}
* @see #checkDbIdentifier(String, String, int)
*/
public static String validateTableName(@Nullable String tableName) {
checkDbIdentifier(tableName, "Table name", TABLE_NAME_MAX_SIZE);
return tableName;
}
/**
* Ensure {@code constraintName} is a valid name for a constraint.
* @throws NullPointerException if {@code constraintName} is {@code null}
* @throws IllegalArgumentException if {@code constraintName} is not valid
* @return the same {@code constraintName}
* @see #checkDbIdentifier(String, String, int)
*/
public static String validateConstraintName(@Nullable String constraintName) {
checkDbIdentifier(constraintName, "Constraint name", CONSTRAINT_NAME_MAX_SIZE);
return constraintName;
}
/**
* Ensure {@code indexName} is a valid name for an index.
* @throws NullPointerException if {@code indexName} is {@code null}
* @throws IllegalArgumentException if {@code indexName} is not valid
* @return the same {@code indexName}
* @see #checkDbIdentifier(String, String, int)
*/
public static String validateIndexName(@Nullable String indexName) {
checkDbIdentifier(indexName, "Index name", INDEX_NAME_MAX_SIZE);
return indexName;
}
public static String validateIndexNameIgnoreCase(@Nullable String indexName) {
checkDbIdentifier(indexName, "Index name", INDEX_NAME_MAX_SIZE, true);
return indexName;
}
/**
* Ensure {@code identifier} is a valid DB identifier.
*
* @throws NullPointerException if {@code identifier} is {@code null}
* @throws IllegalArgumentException if {@code identifier} is empty
* @throws IllegalArgumentException if {@code identifier} is longer than {@code maxSize}
* @throws IllegalArgumentException if {@code identifier} is not lowercase
* @throws IllegalArgumentException if {@code identifier} contains characters others than ASCII letters, ASCII numbers or {@code _}
* @throws IllegalArgumentException if {@code identifier} starts with {@code _} or a number
*/
static String checkDbIdentifier(@Nullable String identifier, String identifierDesc, int maxSize) {
return checkDbIdentifier(identifier, identifierDesc, maxSize, false);
}
static String checkDbIdentifier(@Nullable String identifier, String identifierDesc, int maxSize, boolean ignoreCase) {
String res = checkNotNull(identifier, "%s can't be null", identifierDesc);
checkArgument(!res.isEmpty(), "%s, can't be empty", identifierDesc);
checkArgument(
identifier.length() <= maxSize,
"%s length can't be more than %s", identifierDesc, maxSize);
if (ignoreCase) {
checkDbIdentifierCharactersIgnoreCase(identifier, identifierDesc);
} else {
checkDbIdentifierCharacters(identifier, identifierDesc);
}
return res;
}
private static boolean isSqlKeyword(String identifier) {
return ALL_KEYWORDS.contains(identifier);
}
private static boolean isSqlKeywordIgnoreCase(String identifier) {
return isSqlKeyword(identifier.toUpperCase(Locale.ENGLISH));
}
private static void checkDbIdentifierCharacters(String identifier, String identifierDesc) {
checkArgument(identifier.length() > 0, "Identifier must not be empty");
checkArgument(
LOWER_CASE_ASCII_LETTERS_CHAR_MATCHER.or(DIGIT_CHAR_MATCHER).or(anyOf("_")).matchesAllOf(identifier),
"%s must be lower case and contain only alphanumeric chars or '_', got '%s'", identifierDesc, identifier);
checkArgument(
DIGIT_CHAR_MATCHER.or(UNDERSCORE_CHAR_MATCHER).matchesNoneOf(identifier.subSequence(0, 1)),
"%s must not start by a number or '_', got '%s'", identifierDesc, identifier);
checkArgument(!isSqlKeyword(identifier.toUpperCase(Locale.ENGLISH)) || ALLOWED_IDENTIFIERS.contains(identifier),
"%s must not be an SQL reserved keyword, got '%s'",
identifierDesc,
identifier);
}
private static void checkDbIdentifierCharactersIgnoreCase(String identifier, String identifierDesc) {
checkArgument(identifier.length() > 0, "Identifier must not be empty");
checkArgument(LOWER_CASE_ASCII_LETTERS_CHAR_MATCHER.or(DIGIT_CHAR_MATCHER).or(UPPER_CASE_ASCII_LETTERS_CHAR_MATCHER).or(anyOf("_")).matchesAllOf(identifier),
"%s must contain only alphanumeric chars or '_', got '%s'", identifierDesc, identifier);
checkArgument(
DIGIT_CHAR_MATCHER.or(UNDERSCORE_CHAR_MATCHER).matchesNoneOf(identifier.subSequence(0, 1)),
"%s must not start by a number or '_', got '%s'", identifierDesc, identifier);
checkArgument(!isSqlKeywordIgnoreCase(identifier) || ALLOWED_IDENTIFIERS.contains(identifier.toLowerCase(Locale.ENGLISH)),
"%s must not be an SQL reserved keyword, got '%s'",
identifierDesc,
identifier);
}
}
| 13,401 | 50.348659 | 161 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/VarcharColumnDef.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.def;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
/**
* Used to define VARCHAR column
*/
@Immutable
public class VarcharColumnDef extends AbstractColumnDef {
public static final int MAX_SIZE = 4_000;
public static final int UUID_SIZE = 40;
public static final int DESCRIPTION_SECTION_KEY_SIZE = 50;
/**
* UUID length of the USERS table is not using the standard UUID length.
* The reason of this is because when the UUID column was introduced in the USERS table, existing rows were fed with the login, which has a length of 255.
* @see <a https://jira.sonarsource.com/browse/SONAR-10597>SONAR-10597</a>
*/
public static final int USER_UUID_SIZE = 255;
private final int columnSize;
private final boolean ignoreOracleUnit;
private VarcharColumnDef(Builder builder) {
super(builder.columnName, builder.isNullable, builder.defaultValue);
this.columnSize = builder.columnSize;
this.ignoreOracleUnit = builder.ignoreOracleUnit;
}
public static Builder newVarcharColumnDefBuilder() {
return new Builder();
}
public static Builder newVarcharColumnDefBuilder(String column) {
return newVarcharColumnDefBuilder().setColumnName(column);
}
public int getColumnSize() {
return columnSize;
}
@Override
public String generateSqlType(Dialect dialect) {
switch (dialect.getId()) {
case MsSql.ID:
return format("NVARCHAR (%d)", columnSize);
case Oracle.ID:
return format("VARCHAR2 (%d%s)", columnSize, ignoreOracleUnit ? "" : " CHAR");
default:
return format("VARCHAR (%d)", columnSize);
}
}
public static class Builder {
@CheckForNull
private Integer columnSize;
@CheckForNull
private String columnName;
@CheckForNull
private String defaultValue = null;
private boolean isNullable = true;
private boolean ignoreOracleUnit = false;
public Builder setColumnName(String columnName) {
this.columnName = validateColumnName(columnName);
return this;
}
public Builder setLimit(int limit) {
this.columnSize = limit;
return this;
}
public Builder setIsNullable(boolean isNullable) {
this.isNullable = isNullable;
return this;
}
public Builder setDefaultValue(@Nullable String s) {
this.defaultValue = s;
return this;
}
/**
* In order to not depend on value of runtime variable NLS_LENGTH_SEMANTICS, unit of length
* is enforced to CHAR so that we're sure that type can't be BYTE.
* Unit is ignored for the columns created before SonarQube 6.3 (except for issues.message which
* has been fixed in migration 1151 of SonarQube 5.6. See SONAR-7493).
*
* In most cases this method should not be called with parameter {@code true} after
* version 6.3.
*
* @param b whether unit of length is hardcoded to CHAR.
*/
public Builder setIgnoreOracleUnit(boolean b) {
this.ignoreOracleUnit = b;
return this;
}
public VarcharColumnDef build() {
validateColumnName(columnName);
requireNonNull(columnSize, "Limit cannot be null");
return new VarcharColumnDef(this);
}
}
}
| 4,436 | 31.625 | 156 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/def/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.platform.db.migration.def;
import javax.annotation.ParametersAreNonnullByDefault;
| 983 | 38.36 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/engine/MigrationContainer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.engine;
import org.sonar.core.platform.Container;
/**
* A dedicated container used to run DB migrations where all components are lazily instantiated.
* <p>
* As a new container will be created for each run of DB migrations, components in this container can safely be
* stateful.
* </p>
* <p>
* Lazy instantiation is convenient to instantiate {@link org.sonar.server.platform.db.migration.step.MigrationStep}
* classes only they really are to be executed.
* </p>
*/
public interface MigrationContainer extends Container {
/**
* Cleans up resources after migration has run.
* <strong>This method must never fail.</strong>
*/
void cleanup();
}
| 1,565 | 35.418605 | 118 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/engine/MigrationContainerImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.engine;
import java.util.HashSet;
import java.util.Set;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.core.platform.LazyStrategy;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor;
import static java.util.Collections.emptyList;
public class MigrationContainerImpl extends SpringComponentContainer implements MigrationContainer {
public MigrationContainerImpl(SpringComponentContainer parent, Class<? extends MigrationStepsExecutor> executor) {
super(parent, parent.getComponentByType(PropertyDefinitions.class), emptyList(), new LazyStrategy());
add(executor);
addSteps(parent.getComponentByType(MigrationSteps.class));
startComponents();
}
private void addSteps(MigrationSteps migrationSteps) {
Set<Class<? extends MigrationStep>> classes = new HashSet<>();
migrationSteps.readAll().forEach(step -> {
Class<? extends MigrationStep> stepClass = step.getStepClass();
if (!classes.contains(stepClass)) {
add(stepClass);
classes.add(stepClass);
}
});
}
@Override
public void cleanup() {
stopComponents();
}
@Override
public String toString() {
return "MigrationContainerImpl";
}
}
| 2,299 | 35.507937 | 116 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/engine/MigrationContainerPopulator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.engine;
import org.sonar.core.platform.ContainerPopulator;
public interface MigrationContainerPopulator extends ContainerPopulator<MigrationContainer> {
}
| 1,047 | 39.307692 | 93 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/engine/MigrationContainerPopulatorImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.engine;
import java.util.HashSet;
import java.util.Set;
import org.sonar.server.platform.db.migration.step.MigrationStep;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl;
/**
* Responsible for:
* <ul>
* <li>adding all the {@link MigrationStep} classes to the container after building it</li>
* <li>adding the {@link MigrationStepsExecutorImpl} to the container</li>
* </ul>
*/
public class MigrationContainerPopulatorImpl implements MigrationContainerPopulator {
private final Class<? extends MigrationStepsExecutor> executorType;
public MigrationContainerPopulatorImpl() {
this(MigrationStepsExecutorImpl.class);
}
protected MigrationContainerPopulatorImpl(Class<? extends MigrationStepsExecutor> executorType) {
this.executorType = executorType;
}
@Override
public void populateContainer(MigrationContainer container) {
container.add(executorType);
populateFromMigrationSteps(container);
}
private static void populateFromMigrationSteps(MigrationContainer container) {
MigrationSteps migrationSteps = container.getComponentByType(MigrationSteps.class);
Set<Class<? extends MigrationStep>> classes = new HashSet<>();
migrationSteps.readAll().forEach(step -> {
Class<? extends MigrationStep> stepClass = step.getStepClass();
if (!classes.contains(stepClass)) {
container.add(stepClass);
classes.add(stepClass);
}
});
}
}
| 2,485 | 37.246154 | 99 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/engine/MigrationEngine.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.engine;
/**
* This class is responsible for:
* <ul>
* <li>creating a dedicate container to run the migrations, populating it and starting it</li>
* <li>resolving the migration starting point</li>
* <li>starting the db migration execution</li>
* <li>stop the container and dispose of it</li>
* </ul>
*/
public interface MigrationEngine {
void execute();
}
| 1,264 | 36.205882 | 96 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/engine/MigrationEngineImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.engine;
import java.util.List;
import java.util.Optional;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.server.platform.db.migration.history.MigrationHistory;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutor;
import org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
public class MigrationEngineImpl implements MigrationEngine {
private final MigrationHistory migrationHistory;
private final SpringComponentContainer serverContainer;
private final MigrationSteps migrationSteps;
public MigrationEngineImpl(MigrationHistory migrationHistory, SpringComponentContainer serverContainer, MigrationSteps migrationSteps) {
this.migrationHistory = migrationHistory;
this.serverContainer = serverContainer;
this.migrationSteps = migrationSteps;
}
@Override
public void execute() {
MigrationContainer migrationContainer = new MigrationContainerImpl(serverContainer, MigrationStepsExecutorImpl.class);
try {
MigrationStepsExecutor stepsExecutor = migrationContainer.getComponentByType(MigrationStepsExecutor.class);
Optional<Long> lastMigrationNumber = migrationHistory.getLastMigrationNumber();
List<RegisteredMigrationStep> steps = lastMigrationNumber
.map(i -> migrationSteps.readFrom(i + 1))
.orElse(migrationSteps.readAll());
stepsExecutor.execute(steps);
} finally {
migrationContainer.cleanup();
}
}
}
| 2,503 | 40.04918 | 138 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/engine/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.platform.db.migration.engine;
import javax.annotation.ParametersAreNonnullByDefault;
| 986 | 38.48 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/history/MigrationHistory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.history;
import java.util.Optional;
import org.sonar.api.Startable;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
/**
* This class is responsible for providing methods to read and write information from the persisted
* history.
* <p>
* This class assumes the Migration History table exists (see {@link MigrationHistoryTable}) and will
* fail at startup (see {@link #start()}) if it doesn't.
* </p>
*/
public interface MigrationHistory extends Startable {
/**
* @throws IllegalStateException if the Migration History table does not exist.
*/
@Override
void start();
/**
* Returns the last execute migration number according to the persistence information.
*
* @return a long >= 0 or empty if the migration history is empty.
*/
Optional<Long> getLastMigrationNumber();
/**
* Saves in persisted migration history the fact that the specified {@link RegisteredMigrationStep} has
* been successfully executed.
*
* @throws RuntimeException if the information can not be persisted (and committed).
*/
void done(RegisteredMigrationStep dbMigration);
}
| 2,026 | 34.561404 | 105 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/history/MigrationHistoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.history;
import com.google.common.base.Throwables;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import org.sonar.db.Database;
import org.sonar.db.DatabaseUtils;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static com.google.common.base.Preconditions.checkState;
public class MigrationHistoryImpl implements MigrationHistory {
private static final String SCHEMA_MIGRATIONS_TABLE = "schema_migrations";
private final Database database;
private final MigrationHistoryMeddler migrationHistoryMeddler;
public MigrationHistoryImpl(Database database, MigrationHistoryMeddler migrationHistoryMeddler) {
this.database = database;
this.migrationHistoryMeddler = migrationHistoryMeddler;
}
@Override
public void start() {
try (Connection connection = database.getDataSource().getConnection()) {
checkState(DatabaseUtils.tableExists(MigrationHistoryTable.NAME, connection), "Migration history table is missing");
migrationHistoryMeddler.meddle(this);
} catch (SQLException e) {
Throwables.propagate(e);
}
}
@Override
public void stop() {
// nothing to do
}
@Override
public Optional<Long> getLastMigrationNumber() {
try (Connection connection = database.getDataSource().getConnection()) {
List<Long> versions = selectVersions(connection);
if (!versions.isEmpty()) {
return Optional.of(versions.get(versions.size() - 1));
}
return Optional.empty();
} catch (SQLException e) {
throw new IllegalStateException("Failed to read content of table " + SCHEMA_MIGRATIONS_TABLE, e);
}
}
@Override
public void done(RegisteredMigrationStep dbMigration) {
long migrationNumber = dbMigration.getMigrationNumber();
try (Connection connection = database.getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("insert into schema_migrations(version) values (?)")) {
statement.setString(1, String.valueOf(migrationNumber));
statement.execute();
if (!connection.getAutoCommit()) {
connection.commit();
}
} catch (SQLException e) {
throw new IllegalStateException(String.format("Failed to insert row with value %s in table %s", migrationNumber, SCHEMA_MIGRATIONS_TABLE), e);
}
}
private static List<Long> selectVersions(Connection connection) throws SQLException {
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select version from " + SCHEMA_MIGRATIONS_TABLE)) {
List<Long> res = new ArrayList<>();
while (resultSet.next()) {
res.add(resultSet.getLong(1));
}
return res.stream()
.sorted(Comparator.naturalOrder())
.toList();
}
}
}
| 3,893 | 35.392523 | 148 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/history/MigrationHistoryMeddler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.history;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.sonar.server.platform.db.migration.step.MigrationSteps;
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
/**
* Under some conditions, the migration history must be manipulated. This is the role of this class
* which is called by {@link MigrationHistory#start()}.
*/
public class MigrationHistoryMeddler {
private final Map<Long, Long> meddledSteps = ImmutableMap.of(
// SONAR-12127 several DB migration were added in 7.9 to migrate to from 6.7 to 7.0
// If already on 7.0, we don't want any of these DB migrations ran
// => we change last migration number of those 7.0 instance to the new max migration number for 7.0
1_923L, 1_959L);
private final MigrationSteps migrationSteps;
public MigrationHistoryMeddler(MigrationSteps migrationSteps) {
this.migrationSteps = migrationSteps;
}
public void meddle(MigrationHistory migrationHistory) {
// change last migration number on specific cases
migrationHistory.getLastMigrationNumber()
.ifPresent(migrationNumber -> {
Long newMigrationNumber = meddledSteps.get(migrationNumber);
if (newMigrationNumber != null) {
RegisteredMigrationStep registeredMigrationStep = migrationSteps.readFrom(newMigrationNumber).get(0);
migrationHistory.done(registeredMigrationStep);
}
});
}
}
| 2,328 | 41.345455 | 111 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/history/MigrationHistoryTable.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.history;
import org.sonar.api.Startable;
/**
* This class is responsible for ensuring at startup that the persistence of migration history is possible.
* <p>
* Therefor, it will create the migration history table if it does not exist yet, update it if necessary and fail
* if any of the two previous operations fails.
* </p>
* <p>
* This class is intended to be present only in the WebServer and only the web server is the startup leader.
* </p>
*/
public interface MigrationHistoryTable extends Startable {
String NAME = "schema_migrations";
/**
* Ensures that the history of db migrations can be persisted to database:
* <ul>
* <li>underlying table {@code SCHEMA_MIGRATIONS} is created if it does not exist</li>
* <li>underlying table {@code SCHEMA_MIGRATIONS} is updated if needed</li>
* </ul>
*
* @throws IllegalStateException if we can not ensure that table {@code SCHEMA_MIGRATIONS} can be accessed correctly
*/
@Override
void start();
}
| 1,888 | 37.55102 | 118 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/history/MigrationHistoryTableImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.history;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.slf4j.LoggerFactory;
import org.sonar.db.Database;
import org.sonar.db.DatabaseUtils;
import org.sonar.server.platform.db.migration.def.VarcharColumnDef;
import org.sonar.server.platform.db.migration.sql.CreateTableBuilder;
public class MigrationHistoryTableImpl implements MigrationHistoryTable {
private static final String VERSION_COLUMN_NAME = "version";
private final Database database;
public MigrationHistoryTableImpl(Database database) {
this.database = database;
}
@Override
public void start() {
try (Connection connection = createDdlConnection(database)) {
if (!DatabaseUtils.tableExists(NAME, connection)) {
createTable(connection);
}
} catch (SQLException e) {
throw new IllegalStateException("Failed to create table " + NAME, e);
}
}
private void createTable(Connection connection) throws SQLException {
List<String> sqls = new CreateTableBuilder(database.getDialect(), NAME)
.addColumn(VarcharColumnDef.newVarcharColumnDefBuilder().setColumnName(VERSION_COLUMN_NAME).setIsNullable(false).setLimit(255).build())
.build();
LoggerFactory.getLogger(MigrationHistoryTableImpl.class).info("Creating table " + NAME);
for (String sql : sqls) {
execute(connection, sql);
}
}
private static Connection createDdlConnection(Database database) throws SQLException {
Connection res = database.getDataSource().getConnection();
res.setAutoCommit(false);
return res;
}
private static void execute(Connection connection, String sql) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.execute(sql);
connection.commit();
}
}
@Override
public void stop() {
// nothing to do
}
}
| 2,774 | 33.259259 | 141 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/history/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.platform.db.migration.history;
import javax.annotation.ParametersAreNonnullByDefault;
| 987 | 38.52 | 75 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/AddColumnsBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.List;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
/**
* Generate a SQL query to add multiple columns on a table
*/
public class AddColumnsBuilder {
private final Dialect dialect;
private final String tableName;
private List<ColumnDef> columnDefs = newArrayList();
public AddColumnsBuilder(Dialect dialect, String tableName) {
this.tableName = validateTableName(tableName);
this.dialect = dialect;
}
public AddColumnsBuilder addColumn(ColumnDef columnDef) {
columnDefs.add(columnDef);
return this;
}
public String build() {
if (columnDefs.isEmpty()) {
throw new IllegalStateException("No column has been defined");
}
StringBuilder sql = new StringBuilder().append("ALTER TABLE ").append(tableName).append(" ");
switch (dialect.getId()) {
case PostgreSql.ID:
addColumns(sql, "ADD COLUMN ");
break;
case MsSql.ID:
sql.append("ADD ");
addColumns(sql, "");
break;
default:
sql.append("ADD (");
addColumns(sql, "");
sql.append(")");
}
return sql.toString();
}
private void addColumns(StringBuilder sql, String columnPrefix) {
for (int i = 0; i < columnDefs.size(); i++) {
sql.append(columnPrefix);
addColumn(sql, columnDefs.get(i));
if (i < columnDefs.size() - 1) {
sql.append(", ");
}
}
}
private void addColumn(StringBuilder sql, ColumnDef columnDef) {
sql.append(columnDef.getName()).append(" ").append(columnDef.generateSqlType(dialect));
Object defaultValue = columnDef.getDefaultValue();
if (defaultValue != null) {
sql.append(" DEFAULT ");
// TODO remove duplication with CreateTableBuilder
if (defaultValue instanceof String) {
sql.append(format("'%s'", defaultValue));
} else if (defaultValue instanceof Boolean) {
sql.append((boolean) defaultValue ? dialect.getTrueSqlValue() : dialect.getFalseSqlValue());
} else {
sql.append(defaultValue);
}
}
sql.append(columnDef.isNullable() ? " NULL" : " NOT NULL");
}
}
| 3,329 | 31.970297 | 100 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/AddPrimaryKeyBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
import static org.sonar.server.platform.db.migration.sql.CreateTableBuilder.PRIMARY_KEY_PREFIX;
public class AddPrimaryKeyBuilder {
private final String tableName;
private final List<String> primaryKey;
public AddPrimaryKeyBuilder(String tableName, String column, String... moreColumns) {
this.tableName = validateTableName(tableName);
this.primaryKey = Lists.asList(column, moreColumns).stream().filter(Objects::nonNull).toList();
}
public String build() {
checkState(!primaryKey.isEmpty(), "Primary key is missing");
return format("ALTER TABLE %s ADD CONSTRAINT %s%s PRIMARY KEY (%s)", tableName, PRIMARY_KEY_PREFIX, tableName,
String.join(",", this.primaryKey));
}
}
| 1,885 | 38.291667 | 114 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/AlterColumnsBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayList;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
/**
* Generate SQL queries to update multiple columns of a single table.
*
* Note that this operation will not be re-entrant on:
* <ul>
* <li>Oracle 11G (may raise {@code ORA-01442: column to be modified to NOT NULL is already NOT NULL} or
* {@code ORA-01451: column to be modified to NULL cannot be modified to NULL})</li>
* </ul>
*/
public class AlterColumnsBuilder {
private static final String ALTER_TABLE = "ALTER TABLE ";
private static final String ALTER_COLUMN = "ALTER COLUMN ";
private final Dialect dialect;
private final String tableName;
private final List<ColumnDef> columnDefs = newArrayList();
public AlterColumnsBuilder(Dialect dialect, String tableName) {
this.dialect = dialect;
this.tableName = validateTableName(tableName);
}
public AlterColumnsBuilder updateColumn(ColumnDef columnDef) {
// limitation of Oracle, only attribute changes must be defined in ALTER.
checkArgument(columnDef.getDefaultValue()==null, "Default value is not supported on alter of column '%s'", columnDef.getName());
columnDefs.add(columnDef);
return this;
}
public List<String> build() {
if (columnDefs.isEmpty()) {
throw new IllegalStateException("No column has been defined");
}
switch (dialect.getId()) {
case PostgreSql.ID:
return createPostgresQuery();
case Oracle.ID:
return createOracleQuery();
default:
return createMsSqlAndH2Queries();
}
}
private List<String> createPostgresQuery() {
StringBuilder sql = new StringBuilder(ALTER_TABLE + tableName + " ");
for (Iterator<ColumnDef> columnDefIterator = columnDefs.iterator(); columnDefIterator.hasNext();) {
ColumnDef columnDef = columnDefIterator.next();
sql.append(ALTER_COLUMN);
addColumn(sql, columnDef, "TYPE ", false);
sql.append(", ");
sql.append(ALTER_COLUMN);
sql.append(columnDef.getName());
sql.append(' ').append(columnDef.isNullable() ? "DROP" : "SET").append(" NOT NULL");
if (columnDefIterator.hasNext()) {
sql.append(", ");
}
}
return Collections.singletonList(sql.toString());
}
private List<String> createOracleQuery() {
List<String> sqls = new ArrayList<>();
for (ColumnDef columnDef : columnDefs) {
StringBuilder sql = new StringBuilder(ALTER_TABLE + tableName + " ").append("MODIFY (");
addColumn(sql, columnDef, "", true);
sql.append(")");
sqls.add(sql.toString());
}
return sqls;
}
private List<String> createMsSqlAndH2Queries() {
List<String> sqls = new ArrayList<>();
for (ColumnDef columnDef : columnDefs) {
StringBuilder defaultQuery = new StringBuilder(ALTER_TABLE + tableName + " ");
defaultQuery.append(ALTER_COLUMN);
addColumn(defaultQuery, columnDef, "", true);
sqls.add(defaultQuery.toString());
}
return sqls;
}
private void addColumn(StringBuilder sql, ColumnDef columnDef, String typePrefix, boolean addNotNullableProperty) {
sql.append(columnDef.getName())
.append(" ")
.append(typePrefix)
.append(columnDef.generateSqlType(dialect));
if (addNotNullableProperty) {
sql.append(columnDef.isNullable() ? " NULL" : " NOT NULL");
}
}
}
| 4,656 | 35.382813 | 132 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/CreateIndexBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.ArrayList;
import java.util.List;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.platform.db.migration.def.Validations.validateIndexName;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
public class CreateIndexBuilder {
private final List<String> columns = new ArrayList<>();
private String tableName;
private String indexName;
private boolean unique = false;
/**
* Required name of table on which index is created
*/
public CreateIndexBuilder setTable(String s) {
this.tableName = s;
return this;
}
/**
* Required name of index. Name must be unique among all the tables
* of the schema.
*/
public CreateIndexBuilder setName(String s) {
this.indexName = s;
return this;
}
/**
* By default index is NOT UNIQUE (value {@code false}).
*/
public CreateIndexBuilder setUnique(boolean b) {
this.unique = b;
return this;
}
/**
* Add a column to the scope of index. Order of calls to this
* method is important and is kept as-is when creating the index.
* The attribute used from {@link ColumnDef} is the name.
* Other attributes are ignored.
*/
public CreateIndexBuilder addColumn(ColumnDef column) {
columns.add(requireNonNull(column, "Column cannot be null").getName());
return this;
}
/**
* Add a column to the scope of index. Order of calls to this
* method is important and is kept as-is when creating the index.
*/
public CreateIndexBuilder addColumn(String column) {
columns.add(requireNonNull(column, "Column cannot be null"));
return this;
}
public List<String> build() {
validateTableName(tableName);
validateIndexName(indexName);
checkArgument(!columns.isEmpty(), "at least one column must be specified");
return singletonList(createSqlStatement());
}
private String createSqlStatement() {
StringBuilder sql = new StringBuilder("CREATE ");
if (unique) {
sql.append("UNIQUE ");
}
sql.append("INDEX ");
sql.append(indexName);
sql.append(" ON ");
sql.append(tableName);
sql.append(" (");
sql.append(String.join(", ", columns));
sql.append(")");
return sql.toString();
}
}
| 3,343 | 30.54717 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/CreateTableAsBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.MsSql;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
/**
* Creates a new table based on an existing table.
* With Oracle, H2 and PSQL it uses the 'CREATE TABLE [...] AS' statement. This is not supported in SQL Server, so we use 'SELECT [...] INTO [new_table] FROM [old_table]'.
* Note that indexes are not kept. Constraints are also not kept except for 'NOT NULL' in some dbs and under certain conditions. Some dbs also allow to specify 'NOT NULL'
* constraint or even data type when specifying the new table.
* For simplicity, we explicitly add NOT NULL constrains with separate statements for all DBs, since it's a fast operation.
*/
public class CreateTableAsBuilder {
private final Dialect dialect;
private final String tableName;
private final String fromTableName;
private final List<Column> columns = new ArrayList<>();
public CreateTableAsBuilder(Dialect dialect, String tableName, String fromTableName) {
this.dialect = requireNonNull(dialect, "dialect can't be null");
this.tableName = validateTableName(tableName);
this.fromTableName = validateTableName(fromTableName);
checkArgument(!tableName.equals(fromTableName), "Table names must be different");
}
public CreateTableAsBuilder addColumn(ColumnDef column) {
columns.add(new Column(column, null));
return this;
}
public CreateTableAsBuilder addColumnWithCast(ColumnDef column, String castFrom) {
columns.add(new Column(column, castFrom));
return this;
}
public List<String> build() {
checkState(!columns.isEmpty(), "Columns need to be specified");
List<String> sql = new ArrayList<>();
String select = columns.stream().map(this::toSelect).collect(Collectors.joining(", "));
if (dialect.getId().equals(MsSql.ID)) {
sql.add("SELECT " + select + " INTO " + tableName + " FROM " + fromTableName);
} else {
StringBuilder sb = new StringBuilder("CREATE TABLE " + tableName + " (");
appendColumnNames(sb);
sb.append(") AS (SELECT ").append(select).append(" FROM ").append(fromTableName).append(")");
sql.add(sb.toString());
}
List<Column> notNullColumns = columns.stream().filter(c -> !c.definition().isNullable()).toList();
for (Column c : notNullColumns) {
sql.addAll(new AlterColumnsBuilder(dialect, tableName).updateColumn(c.definition()).build());
}
return sql;
}
private String toSelect(Column column) {
if (column.castFrom() == null) {
return column.definition().getName();
}
// Example: CAST (metric_id AS VARCHAR(40)) AS metric_uuid
return "CAST (" + column.castFrom() + " AS " + column.definition().generateSqlType(dialect) + ") AS " + column.definition().getName();
}
private void appendColumnNames(StringBuilder res) {
res.append(columns.stream().map(c -> c.definition().getName()).collect(Collectors.joining(", ")));
}
private static class Column {
private final ColumnDef columnDef;
private final String castFrom;
public Column(ColumnDef columnDef, @Nullable String castFrom) {
this.columnDef = columnDef;
this.castFrom = castFrom;
}
private ColumnDef definition() {
return columnDef;
}
private String castFrom() {
return castFrom;
}
}
}
| 4,620 | 37.831933 | 171 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/CreateTableBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.BigIntegerColumnDef;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import org.sonar.server.platform.db.migration.def.IntegerColumnDef;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Stream.of;
import static org.sonar.server.platform.db.migration.def.Validations.validateConstraintName;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
public class CreateTableBuilder {
public static final String PRIMARY_KEY_PREFIX = "pk_";
private final Dialect dialect;
private final String tableName;
private final List<ColumnDef> columnDefs = new ArrayList<>();
private final List<ColumnDef> pkColumnDefs = new ArrayList<>(2);
private final Multimap<ColumnDef, ColumnFlag> flagsByColumn = HashMultimap.create(1, 1);
@CheckForNull
private String pkConstraintName;
public CreateTableBuilder(Dialect dialect, String tableName) {
this.dialect = requireNonNull(dialect, "dialect can't be null");
this.tableName = validateTableName(tableName);
}
public List<String> build() {
checkState(!columnDefs.isEmpty() || !pkColumnDefs.isEmpty(), "at least one column must be specified");
return Stream.concat(of(createTableStatement()), createOracleAutoIncrementStatements())
.toList();
}
public CreateTableBuilder addColumn(ColumnDef columnDef) {
columnDefs.add(requireNonNull(columnDef, "column def can't be null"));
return this;
}
public CreateTableBuilder addPkColumn(ColumnDef columnDef, ColumnFlag... flags) {
pkColumnDefs.add(requireNonNull(columnDef, "column def can't be null"));
addFlags(columnDef, flags);
return this;
}
private void addFlags(ColumnDef columnDef, ColumnFlag[] flags) {
Arrays.stream(flags)
.forEach(flag -> {
requireNonNull(flag, "flag can't be null");
if (flag == ColumnFlag.AUTO_INCREMENT) {
validateColumnDefForAutoIncrement(columnDef);
}
flagsByColumn.put(columnDef, flag);
});
}
private void validateColumnDefForAutoIncrement(ColumnDef columnDef) {
checkArgument("id".equals(columnDef.getName()),
"Auto increment column name must be id");
checkArgument(columnDef instanceof BigIntegerColumnDef
|| columnDef instanceof IntegerColumnDef,
"Auto increment column must either be BigInteger or Integer");
checkArgument(!columnDef.isNullable(),
"Auto increment column can't be nullable");
checkState(pkColumnDefs.stream().noneMatch(this::isAutoIncrement),
"There can't be more than one auto increment column");
}
public CreateTableBuilder withPkConstraintName(String pkConstraintName) {
this.pkConstraintName = validateConstraintName(pkConstraintName);
return this;
}
private String createTableStatement() {
StringBuilder res = new StringBuilder("CREATE TABLE ");
res.append(tableName);
res.append(" (");
appendPkColumns(res);
appendColumns(res, dialect, columnDefs);
appendPkConstraint(res);
res.append(')');
return res.toString();
}
private void appendPkColumns(StringBuilder res) {
appendColumns(res, dialect, pkColumnDefs);
if (!pkColumnDefs.isEmpty() && !columnDefs.isEmpty()) {
res.append(',');
}
}
private void appendColumns(StringBuilder res, Dialect dialect, List<ColumnDef> columnDefs) {
if (columnDefs.isEmpty()) {
return;
}
Iterator<ColumnDef> columnDefIterator = columnDefs.iterator();
while (columnDefIterator.hasNext()) {
ColumnDef columnDef = columnDefIterator.next();
res.append(columnDef.getName());
res.append(' ');
appendDataType(res, dialect, columnDef);
appendDefaultValue(res, columnDef);
appendNullConstraint(res, columnDef);
appendColumnFlags(res, dialect, columnDef);
if (columnDefIterator.hasNext()) {
res.append(',');
}
}
}
private void appendDataType(StringBuilder res, Dialect dialect, ColumnDef columnDef) {
if (PostgreSql.ID.equals(dialect.getId()) && isAutoIncrement(columnDef)) {
if (columnDef instanceof BigIntegerColumnDef) {
res.append("BIGSERIAL");
} else if (columnDef instanceof IntegerColumnDef) {
res.append("SERIAL");
} else {
throw new IllegalStateException("Column with autoincrement is neither BigInteger nor Integer");
}
} else {
res.append(columnDef.generateSqlType(dialect));
}
}
private boolean isAutoIncrement(ColumnDef columnDef) {
Collection<ColumnFlag> columnFlags = this.flagsByColumn.get(columnDef);
return columnFlags != null && columnFlags.contains(ColumnFlag.AUTO_INCREMENT);
}
private static void appendNullConstraint(StringBuilder res, ColumnDef columnDef) {
if (columnDef.isNullable()) {
res.append(" NULL");
} else {
res.append(" NOT NULL");
}
}
private void appendDefaultValue(StringBuilder sql, ColumnDef columnDef) {
Object defaultValue = columnDef.getDefaultValue();
if (defaultValue != null) {
sql.append(" DEFAULT ");
if (defaultValue instanceof String) {
sql.append(format("'%s'", defaultValue));
} else if (defaultValue instanceof Boolean) {
sql.append((boolean) defaultValue ? dialect.getTrueSqlValue() : dialect.getFalseSqlValue());
} else {
sql.append(defaultValue);
}
}
}
private void appendColumnFlags(StringBuilder res, Dialect dialect, ColumnDef columnDef) {
Collection<ColumnFlag> columnFlags = this.flagsByColumn.get(columnDef);
if (columnFlags != null && columnFlags.contains(ColumnFlag.AUTO_INCREMENT)) {
switch (dialect.getId()) {
case Oracle.ID:
// no auto increment on Oracle, must use a sequence
break;
case PostgreSql.ID:
// no specific clause on PostgreSQL but a specific type
break;
case MsSql.ID:
res.append(" IDENTITY (1,1)");
break;
case H2.ID:
res.append(" AUTO_INCREMENT (1,1)");
break;
default:
throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
}
}
}
private void appendPkConstraint(StringBuilder res) {
if (pkColumnDefs.isEmpty()) {
return;
}
res.append(", ");
res.append("CONSTRAINT ");
appendPkConstraintName(res);
res.append(" PRIMARY KEY ");
res.append('(');
appendColumnNames(res, pkColumnDefs);
res.append(')');
}
private void appendPkConstraintName(StringBuilder res) {
if (pkConstraintName == null) {
res.append(PRIMARY_KEY_PREFIX).append(tableName);
} else {
res.append(pkConstraintName.toLowerCase(Locale.ENGLISH));
}
}
private static void appendColumnNames(StringBuilder res, List<ColumnDef> columnDefs) {
Iterator<ColumnDef> columnDefIterator = columnDefs.iterator();
while (columnDefIterator.hasNext()) {
res.append(columnDefIterator.next().getName());
if (columnDefIterator.hasNext()) {
res.append(',');
}
}
}
private Stream<String> createOracleAutoIncrementStatements() {
if (!Oracle.ID.equals(dialect.getId())) {
return Stream.empty();
}
return pkColumnDefs.stream()
.filter(this::isAutoIncrement)
.flatMap(columnDef -> of(createSequenceFor(tableName), createOracleTriggerForTable(tableName)));
}
private static String createSequenceFor(String tableName) {
return "CREATE SEQUENCE " + tableName + "_seq START WITH 1 INCREMENT BY 1";
}
static String createOracleTriggerForTable(String tableName) {
return "CREATE OR REPLACE TRIGGER " + tableName + "_idt" +
" BEFORE INSERT ON " + tableName +
" FOR EACH ROW" +
" BEGIN" +
" IF :new.id IS null THEN" +
" SELECT " + tableName + "_seq.nextval INTO :new.id FROM dual;" +
" END IF;" +
" END;";
}
public enum ColumnFlag {
AUTO_INCREMENT
}
}
| 9,552 | 33.992674 | 106 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/DbPrimaryKeyConstraintFinder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Optional;
import org.sonar.db.Database;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static java.lang.String.format;
public class DbPrimaryKeyConstraintFinder {
private final Database db;
public DbPrimaryKeyConstraintFinder(Database db) {
this.db = db;
}
public Optional<String> findConstraintName(String tableName) throws SQLException {
String constraintQuery = getDbVendorSpecificQuery(tableName);
return executeQuery(constraintQuery);
}
String getDbVendorSpecificQuery(String tableName) {
Dialect dialect = db.getDialect();
String constraintQuery;
switch (dialect.getId()) {
case PostgreSql.ID:
constraintQuery = getPostgresSqlConstraintQuery(tableName);
break;
case MsSql.ID:
constraintQuery = getMssqlConstraintQuery(tableName);
break;
case Oracle.ID:
constraintQuery = getOracleConstraintQuery(tableName);
break;
case H2.ID:
constraintQuery = getH2ConstraintQuery(tableName);
break;
default:
throw new IllegalStateException(format("Unsupported database '%s'", dialect.getId()));
}
return constraintQuery;
}
private Optional<String> executeQuery(String query) throws SQLException {
try (Connection connection = db.getDataSource().getConnection();
PreparedStatement pstmt = connection
.prepareStatement(query);
ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
return Optional.ofNullable(rs.getString(1));
}
return Optional.empty();
}
}
private String getPostgresSqlConstraintQuery(String tableName) {
try (Connection connection = db.getDataSource().getConnection()) {
return format("SELECT conname " +
"FROM pg_constraint c " +
"JOIN pg_namespace n on c.connamespace = n.oid " +
"JOIN pg_class cls on c.conrelid = cls.oid " +
"WHERE cls.relname = '%s' AND n.nspname = '%s'", tableName, connection.getSchema());
} catch (SQLException throwables) {
throw new IllegalStateException("Can not get database connection");
}
}
private static String getMssqlConstraintQuery(String tableName) {
return format("SELECT name " +
"FROM sys.key_constraints " +
"WHERE type = 'PK' " +
"AND OBJECT_NAME(parent_object_id) = '%s'", tableName);
}
private static String getOracleConstraintQuery(String tableName) {
return format("SELECT constraint_name " +
"FROM user_constraints " +
"WHERE table_name = UPPER('%s') " +
"AND constraint_type='P'", tableName);
}
private static String getH2ConstraintQuery(String tableName) {
return format("SELECT constraint_name "
+ "FROM information_schema.table_constraints "
+ "WHERE table_name = '%s' and constraint_type = 'PRIMARY KEY'", tableName.toUpperCase(Locale.ENGLISH));
}
// FIXME:: this method should be moved somewhere else
String getPostgresSqlSequence(String tableName, String columnName) throws SQLException {
try (Connection connection = db.getDataSource().getConnection();
PreparedStatement pstmt = connection.prepareStatement(format("SELECT pg_get_serial_sequence('%s', '%s')", tableName, columnName));
ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
return rs.getString(1);
}
throw new IllegalStateException(format("Cannot find sequence for table '%s' on column '%s'", tableName, columnName));
}
}
}
| 4,656 | 35.100775 | 136 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/DropColumnsBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
/**
* Generate a SQL query to drop multiple columns from a table
*/
public class DropColumnsBuilder {
private static final String ALTER_TABLE = "ALTER TABLE ";
private final Dialect dialect;
private final String tableName;
private final String[] columns;
public DropColumnsBuilder(Dialect dialect, String tableName, String... columns) {
this.tableName = tableName;
this.dialect = dialect;
this.columns = columns;
}
public List<String> build() {
switch (dialect.getId()) {
case PostgreSql.ID:
StringBuilder sql = new StringBuilder().append(ALTER_TABLE).append(tableName).append(" ");
dropColumns(sql, "DROP COLUMN ", columns);
return Collections.singletonList(sql.toString());
case MsSql.ID:
return Collections.singletonList(getMsSQLStatement(columns));
case Oracle.ID:
return Collections.singletonList(getOracleStatement());
case H2.ID:
return Arrays.stream(columns).map(this::getMsSQLStatement).toList();
default:
throw new IllegalStateException(String.format("Unsupported database '%s'", dialect.getId()));
}
}
private String getOracleStatement() {
StringBuilder sql = new StringBuilder().append(ALTER_TABLE).append(tableName).append(" ");
sql.append("SET UNUSED (");
dropColumns(sql, "", columns);
sql.append(")");
return sql.toString();
}
private String getMsSQLStatement(String... columnNames) {
StringBuilder sql = new StringBuilder().append(ALTER_TABLE).append(tableName).append(" ");
sql.append("DROP COLUMN ");
dropColumns(sql, "", columnNames);
return sql.toString();
}
private static void dropColumns(StringBuilder sql, String columnPrefix, String... columnNames) {
Iterator<String> columnNamesIterator = Arrays.stream(columnNames).iterator();
while (columnNamesIterator.hasNext()) {
sql.append(columnPrefix);
sql.append(columnNamesIterator.next());
if (columnNamesIterator.hasNext()) {
sql.append(", ");
}
}
}
}
| 3,230 | 33.741935 | 101 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/DropConstraintBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.List;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static java.util.Collections.singletonList;
import static org.sonar.server.platform.db.migration.def.Validations.validateIndexName;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
/**
* This builder have the main goal to drop constraint of a column.
* <p>
* It shouldn't be used to drop primary keys constraint, use {@link DropPrimaryKeySqlGenerator}
*/
public class DropConstraintBuilder {
private final Dialect dialect;
private String tableName;
private String constraintName;
public DropConstraintBuilder(Dialect dialect) {
this.dialect = dialect;
}
public DropConstraintBuilder setTable(String s) {
this.tableName = s;
return this;
}
public DropConstraintBuilder setName(String s) {
if (s.startsWith("pk_")) {
throw new IllegalArgumentException("This builder should not be used with primary keys");
}
this.constraintName = s;
return this;
}
public List<String> build() {
validateTableName(tableName);
validateIndexName(constraintName);
return singletonList(createSqlStatement());
}
private String createSqlStatement() {
return switch (dialect.getId()) {
case MsSql.ID, Oracle.ID, PostgreSql.ID, H2.ID -> "ALTER TABLE " + tableName + " DROP CONSTRAINT " + constraintName;
default -> throw new IllegalStateException("Unsupported dialect for drop of constraint: " + dialect);
};
}
}
| 2,534 | 33.256757 | 122 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/DropMsSQLDefaultConstraintsBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import com.google.common.base.Preconditions;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.db.Database;
import org.sonar.db.dialect.MsSql;
import static java.lang.String.format;
/**
* See SONAR-13948. Some columns created in SQ < 5.6 were created with the default command which generated constraints on MS SQL server.
*/
public class DropMsSQLDefaultConstraintsBuilder {
private final Database db;
private String tableName;
private String[] columns;
public DropMsSQLDefaultConstraintsBuilder(Database db) {
this.db = db;
}
public DropMsSQLDefaultConstraintsBuilder setTable(String s) {
this.tableName = s;
return this;
}
public DropMsSQLDefaultConstraintsBuilder setColumns(String... columns) {
this.columns = columns;
return this;
}
public List<String> build() throws SQLException {
Preconditions.checkArgument(columns.length > 0, "At least one column expected.");
Preconditions.checkArgument(MsSql.ID.equals(db.getDialect().getId()), "Expected MsSql dialect was: " + db.getDialect().getId());
return getMsSqlDropDefaultConstraintQueries();
}
private List<String> getMsSqlDropDefaultConstraintQueries() throws SQLException {
List<String> dropQueries = new LinkedList<>();
if (MsSql.ID.equals(db.getDialect().getId())) {
List<String> defaultConstraints = getMssqlDefaultConstraints();
for (String defaultConstraintName : defaultConstraints) {
dropQueries.add("ALTER TABLE " + tableName + " DROP CONSTRAINT " + defaultConstraintName);
}
}
return dropQueries;
}
private List<String> getMssqlDefaultConstraints() throws SQLException {
List<String> defaultConstrainNames = new LinkedList<>();
String commaSeparatedListOfColumns = Arrays.stream(columns).map(s -> "'" + s + "'")
.collect(Collectors.joining(","));
try (Connection connection = db.getDataSource().getConnection();
PreparedStatement pstmt = connection
.prepareStatement(format("SELECT d.name FROM sys.tables t "
+ "JOIN sys.default_constraints d ON d.parent_object_id = t.object_id "
+ "JOIN sys.columns c ON c.object_id = t.object_id AND c.column_id = d.parent_column_id "
+ "JOIN sys.schemas s ON s.schema_id = t.schema_id "
+ "WHERE t.name = '%s' AND c.name in (%s) AND s.name = '%s'", tableName, commaSeparatedListOfColumns, connection.getSchema()));
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
defaultConstrainNames.add(rs.getString(1));
}
}
return defaultConstrainNames;
}
}
| 3,675 | 37.694737 | 137 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/DropPrimaryKeySqlGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.sonar.db.Database;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static java.lang.String.format;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
public class DropPrimaryKeySqlGenerator {
private static final String GENERIC_DROP_CONSTRAINT_STATEMENT = "ALTER TABLE %s DROP CONSTRAINT %s";
private final Database db;
private final DbPrimaryKeyConstraintFinder dbConstraintFinder;
public DropPrimaryKeySqlGenerator(Database db, DbPrimaryKeyConstraintFinder dbConstraintFinder) {
this.db = db;
this.dbConstraintFinder = dbConstraintFinder;
}
public List<String> generate(String tableName, String columnName, boolean isAutoGenerated) throws SQLException {
return generate(tableName, singleton(columnName), isAutoGenerated);
}
public List<String> generate(String tableName, Collection<String> columnNames, boolean isAutoGenerated) throws SQLException {
Dialect dialect = db.getDialect();
Optional<String> constraintName = dbConstraintFinder.findConstraintName(tableName);
if (!constraintName.isPresent()) {
return Collections.emptyList();
}
switch (dialect.getId()) {
case PostgreSql.ID:
return generateForPostgresSql(tableName, columnNames, constraintName.get());
case MsSql.ID:
return generateForMsSql(tableName, constraintName.get());
case Oracle.ID:
return generateForOracle(tableName, constraintName.get(), isAutoGenerated);
case H2.ID:
return generateForH2(tableName, constraintName.get());
default:
throw new IllegalStateException(format("Unsupported database '%s'", dialect.getId()));
}
}
private List<String> generateForPostgresSql(String tableName, Collection<String> columns, String constraintName) throws SQLException {
List<String> statements = new ArrayList<>();
for (String column : columns) {
statements.add(format("ALTER TABLE %s ALTER COLUMN %s DROP DEFAULT", tableName, column));
String sequence = dbConstraintFinder.getPostgresSqlSequence(tableName, column);
if (sequence != null) {
statements.add(format("DROP SEQUENCE %s", sequence));
}
}
statements.add(format(GENERIC_DROP_CONSTRAINT_STATEMENT, tableName, constraintName));
return statements;
}
private static List<String> generateForOracle(String tableName, String constraintName, boolean isAutoGenerated) {
List<String> statements = new ArrayList<>();
if (isAutoGenerated) {
statements.add(format("DROP TRIGGER %s_IDT", tableName));
statements.add(format("DROP SEQUENCE %s_SEQ", tableName));
}
// 'drop index' at the end ensures that associated index with primary key will be deleted
statements.add(format(GENERIC_DROP_CONSTRAINT_STATEMENT + " DROP INDEX", tableName, constraintName));
return statements;
}
private static List<String> generateForMsSql(String tableName, String constraintName) {
return singletonList(format(GENERIC_DROP_CONSTRAINT_STATEMENT, tableName, constraintName));
}
private static List<String> generateForH2(String tableName, String constraintName) {
return singletonList(format(GENERIC_DROP_CONSTRAINT_STATEMENT, tableName, constraintName));
}
}
| 4,459 | 39.917431 | 136 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/DropTableBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.List;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
public class DropTableBuilder {
private final Dialect dialect;
private final String tableName;
public DropTableBuilder(Dialect dialect, String tableName) {
this.dialect = requireNonNull(dialect, "dialect can't be null");
this.tableName = validateTableName(tableName);
}
public List<String> build() {
return switch (dialect.getId()) {
case Oracle.ID -> forOracle(tableName);
case H2.ID, PostgreSql.ID -> singletonList("drop table if exists " + tableName);
case MsSql.ID ->
// "if exists" is supported only since MSSQL 2016.
singletonList("drop table " + tableName);
default -> throw new IllegalStateException("Unsupported DB: " + dialect.getId());
};
}
private static List<String> forOracle(String tableName) {
return asList(
dropIfExistsOnOracle("DROP SEQUENCE " + tableName + "_seq", -2289),
dropIfExistsOnOracle("DROP TRIGGER " + tableName + "_idt", -4080),
dropIfExistsOnOracle("DROP TABLE " + tableName, -942));
}
private static String dropIfExistsOnOracle(String command, int codeIfNotExists) {
return "BEGIN\n" +
"EXECUTE IMMEDIATE '" + command + "';\n" +
"EXCEPTION\n" +
"WHEN OTHERS THEN\n" +
" IF SQLCODE != " + codeIfNotExists + " THEN\n" +
" RAISE;\n" +
" END IF;\n" +
"END;";
}
}
| 2,671 | 35.60274 | 87 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.CheckForNull;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.platform.db.migration.def.ColumnDef;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
/**
* This builder have the main goal to change the name column.
* <p>
* In case of renaming and changing a column, this must be done in two separate steps,
* first rename the column then update the types of this column with @see {@link AlterColumnsBuilder}
*/
public class RenameColumnsBuilder {
private final Dialect dialect;
private final String tableName;
private final List<Renaming> renamings = new ArrayList<>();
public RenameColumnsBuilder(Dialect dialect, String tableName) {
this.dialect = dialect;
this.tableName = tableName;
}
public RenameColumnsBuilder renameColumn(String oldColumnName, ColumnDef columnDef) {
renamings.add(new Renaming(oldColumnName, columnDef));
return this;
}
public List<String> build() {
validateTableName(tableName);
renamings.forEach(
r -> {
validateColumnName(r.getOldColumnName());
validateColumnName(r.getNewColumnName());
checkArgument(!r.getNewColumnName().equals(r.getOldColumnName()), "Column names must be different");
});
return createSqlStatement();
}
private List<String> createSqlStatement() {
return renamings.stream().map(
r -> {
switch (dialect.getId()) {
case H2.ID:
return "ALTER TABLE " + tableName + " ALTER COLUMN " + r.getOldColumnName() + " RENAME TO " + r.getNewColumnName();
case Oracle.ID, PostgreSql.ID:
return "ALTER TABLE " + tableName + " RENAME COLUMN " + r.getOldColumnName() + " TO " + r.getNewColumnName();
case MsSql.ID:
return "EXEC sp_rename '" + tableName + "." + r.getOldColumnName() + "', '" + r.getNewColumnName() + "', 'COLUMN'";
default:
throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
}
}).toList();
}
private static class Renaming implements ColumnDef {
private final ColumnDef columnDef;
private final String oldColumnName;
private Renaming(String oldColumnName, ColumnDef columnDef) {
this.columnDef = columnDef;
this.oldColumnName = oldColumnName;
}
public String getOldColumnName() {
return oldColumnName;
}
public String getNewColumnName() {
return columnDef.getName();
}
@Override
public boolean isNullable() {
return columnDef.isNullable();
}
@Override
public String getName() {
return columnDef.getName();
}
@Override
public String generateSqlType(Dialect dialect) {
return columnDef.generateSqlType(dialect);
}
@CheckForNull
@Override
public Object getDefaultValue() {
return columnDef.getDefaultValue();
}
}
}
| 4,167 | 32.612903 | 127 | java |
sonarqube | sonarqube-master/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/sql/RenameTableBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* 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.platform.db.migration.sql;
import java.util.List;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.sonar.server.platform.db.migration.def.Validations.validateTableName;
public class RenameTableBuilder {
private final Dialect dialect;
private String name;
private String newName;
private boolean autoGeneratedId = true;
public RenameTableBuilder(Dialect dialect) {
this.dialect = dialect;
}
public RenameTableBuilder setName(String s) {
this.name = s;
return this;
}
public RenameTableBuilder setNewName(String s) {
this.newName = s;
return this;
}
/**
* When a table has no auto generated id, this parameter has to be set to false.
* On Oracle, it will allow to not try to drop and recreate the trigger.
* On other databases, this method is useless.
*
* Default value is true.
*/
public RenameTableBuilder setAutoGeneratedId(boolean autoGeneratedId) {
this.autoGeneratedId = autoGeneratedId;
return this;
}
public List<String> build() {
validateTableName(name);
validateTableName(newName);
checkArgument(!name.equals(newName), "Names must be different");
return createSqlStatement();
}
private List<String> createSqlStatement() {
switch (dialect.getId()) {
case H2.ID, PostgreSql.ID:
return singletonList("ALTER TABLE " + name + " RENAME TO " + newName);
case MsSql.ID:
return singletonList("EXEC sp_rename '" + name + "', '" + newName + "'");
case Oracle.ID:
String renameSqlCommand = "RENAME " + name + " TO " + newName;
return autoGeneratedId ? asList(
"DROP TRIGGER " + name + "_idt", renameSqlCommand,
"RENAME " + name + "_seq TO " + newName + "_seq",
CreateTableBuilder.createOracleTriggerForTable(newName))
: singletonList(renameSqlCommand);
default:
throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
}
}
}
| 3,138 | 33.119565 | 88 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.