You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ComponentDao.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2023 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.db.component;
  21. import com.google.common.collect.Ordering;
  22. import java.util.Arrays;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.HashSet;
  26. import java.util.LinkedList;
  27. import java.util.List;
  28. import java.util.Optional;
  29. import java.util.Set;
  30. import java.util.stream.Collectors;
  31. import java.util.stream.Stream;
  32. import javax.annotation.Nullable;
  33. import org.apache.ibatis.session.ResultHandler;
  34. import org.apache.ibatis.session.RowBounds;
  35. import org.sonar.api.resources.Qualifiers;
  36. import org.sonar.api.resources.Scopes;
  37. import org.sonar.db.Dao;
  38. import org.sonar.db.DbSession;
  39. import org.sonar.db.RowNotFoundException;
  40. import org.sonar.db.audit.AuditPersister;
  41. import org.sonar.db.audit.model.ComponentNewValue;
  42. import static com.google.common.base.Preconditions.checkArgument;
  43. import static com.google.common.base.Preconditions.checkState;
  44. import static java.util.Collections.emptyList;
  45. import static org.sonar.db.DatabaseUtils.checkThatNotTooManyConditions;
  46. import static org.sonar.db.DatabaseUtils.executeLargeInputs;
  47. import static org.sonar.db.DatabaseUtils.executeLargeInputsIntoSet;
  48. import static org.sonar.db.DatabaseUtils.executeLargeUpdates;
  49. public class ComponentDao implements Dao {
  50. private final AuditPersister auditPersister;
  51. public ComponentDao(AuditPersister auditPersister) {
  52. this.auditPersister = auditPersister;
  53. }
  54. /*
  55. * SELECT BY UUID
  56. */
  57. public Optional<ComponentDto> selectByUuid(DbSession session, String uuid) {
  58. return Optional.ofNullable(mapper(session).selectByUuid(uuid));
  59. }
  60. public ComponentDto selectOrFailByUuid(DbSession session, String uuid) {
  61. return selectByUuid(session, uuid).orElseThrow(() -> new RowNotFoundException(String.format("Component with uuid '%s' not found", uuid)));
  62. }
  63. public List<ComponentDto> selectByUuids(DbSession session, Collection<String> uuids) {
  64. return executeLargeInputs(uuids, mapper(session)::selectByUuids);
  65. }
  66. public List<String> selectExistingUuids(DbSession session, Collection<String> uuids) {
  67. return executeLargeInputs(uuids, mapper(session)::selectExistingUuids);
  68. }
  69. public List<ComponentDto> selectSubProjectsByComponentUuids(DbSession session, Collection<String> uuids) {
  70. if (uuids.isEmpty()) {
  71. return emptyList();
  72. }
  73. return mapper(session).selectSubProjectsByComponentUuids(uuids);
  74. }
  75. public List<ComponentDto> selectDescendantModules(DbSession session, String rootComponentUuid) {
  76. return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, false);
  77. }
  78. public List<ComponentDto> selectEnabledDescendantModules(DbSession session, String rootComponentUuid) {
  79. return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, true);
  80. }
  81. public List<FilePathWithHashDto> selectEnabledDescendantFiles(DbSession session, String rootComponentUuid) {
  82. return mapper(session).selectDescendantFiles(rootComponentUuid, Scopes.FILE, true);
  83. }
  84. public List<FilePathWithHashDto> selectEnabledFilesFromProject(DbSession session, String rootComponentUuid) {
  85. return mapper(session).selectEnabledFilesFromProject(rootComponentUuid);
  86. }
  87. /**
  88. * Retrieves all components with a specific branch UUID, no other filtering is done by this method.
  89. */
  90. public List<ComponentDto> selectByBranchUuid(String branchUuid, DbSession dbSession) {
  91. return mapper(dbSession).selectByBranchUuid(branchUuid);
  92. }
  93. /*
  94. SELECT BY QUERY
  95. */
  96. /**
  97. * @throws IllegalArgumentException if parameter query#getComponentIds() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  98. * @throws IllegalArgumentException if parameter query#getComponentKeys() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  99. * @throws IllegalArgumentException if parameter query#getMainComponentUuids() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  100. */
  101. public List<ComponentDto> selectByQuery(DbSession dbSession, ComponentQuery query, int offset, int limit) {
  102. return selectByQueryImpl(dbSession, query, offset, limit);
  103. }
  104. /**
  105. * @throws IllegalArgumentException if parameter query#getComponentIds() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  106. * @throws IllegalArgumentException if parameter query#getComponentKeys() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  107. * @throws IllegalArgumentException if parameter query#getMainComponentUuids() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  108. */
  109. public int countByQuery(DbSession session, ComponentQuery query) {
  110. return countByQueryImpl(session, query);
  111. }
  112. private static List<ComponentDto> selectByQueryImpl(DbSession session, ComponentQuery query, int offset, int limit) {
  113. if (query.hasEmptySetOfComponents()) {
  114. return emptyList();
  115. }
  116. checkThatNotTooManyComponents(query);
  117. return mapper(session).selectByQuery(query, new RowBounds(offset, limit));
  118. }
  119. private static int countByQueryImpl(DbSession session, ComponentQuery query) {
  120. if (query.hasEmptySetOfComponents()) {
  121. return 0;
  122. }
  123. checkThatNotTooManyComponents(query);
  124. return mapper(session).countByQuery(query);
  125. }
  126. /*
  127. SELECT BY KEY
  128. */
  129. /**
  130. * Return all components of a project (including disable ones)
  131. */
  132. public List<KeyWithUuidDto> selectUuidsByKeyFromProjectKey(DbSession session, String projectKey) {
  133. return mapper(session).selectUuidsByKeyFromProjectKeyAndBranchOrPr(projectKey, null, null);
  134. }
  135. public List<KeyWithUuidDto> selectUuidsByKeyFromProjectKeyAndBranch(DbSession session, String projectKey, String branch) {
  136. return mapper(session).selectUuidsByKeyFromProjectKeyAndBranchOrPr(projectKey, branch, null);
  137. }
  138. public List<KeyWithUuidDto> selectUuidsByKeyFromProjectKeyAndPullRequest(DbSession session, String projectKey, String pullrequest) {
  139. return mapper(session).selectUuidsByKeyFromProjectKeyAndBranchOrPr(projectKey, null, pullrequest);
  140. }
  141. /**
  142. * If no branch or pull request is provided, returns components in the main branch
  143. */
  144. public List<ComponentDto> selectProjectAndModulesFromProjectKey(DbSession session, String projectKey, boolean excludeDisabled,
  145. @Nullable String branch, @Nullable String pullRequest) {
  146. checkState(branch == null || pullRequest == null, "Can't set both branch and pull request");
  147. return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, Scopes.PROJECT, excludeDisabled, branch, pullRequest);
  148. }
  149. public List<ComponentDto> selectByKeys(DbSession session, Collection<String> keys) {
  150. return selectByKeys(session, keys, null, null);
  151. }
  152. /**
  153. * If no branch or pull request is provided, returns components in the main branch
  154. */
  155. public List<ComponentDto> selectByKeys(DbSession session, Collection<String> keys, @Nullable String branch, @Nullable String pullRequest) {
  156. checkState(branch == null || pullRequest == null, "Can't set both branch and pull request");
  157. return executeLargeInputs(keys, subKeys -> mapper(session).selectByKeysAndBranchOrPr(subKeys, branch, pullRequest));
  158. }
  159. /**
  160. * Returns components in the main branch
  161. */
  162. public Optional<ComponentDto> selectByKey(DbSession session, String key) {
  163. return Optional.ofNullable(mapper(session).selectByKeyAndBranchOrPr(key, null, null));
  164. }
  165. public Optional<ComponentDto> selectByKeyAndBranch(DbSession session, String key, String branch) {
  166. return Optional.ofNullable(mapper(session).selectByKeyAndBranchOrPr(key, branch, null));
  167. }
  168. public Optional<ComponentDto> selectByKeyAndPullRequest(DbSession session, String key, String pullRequestId) {
  169. return Optional.ofNullable(mapper(session).selectByKeyAndBranchOrPr(key, null, pullRequestId));
  170. }
  171. public Optional<ComponentDto> selectByKeyCaseInsensitive(DbSession session, String key) {
  172. return Optional.ofNullable(mapper(session).selectByKeyCaseInsensitive(key));
  173. }
  174. /**
  175. * List of ancestors, ordered from root to parent. The list is empty
  176. * if the component is a tree root. Disabled components are excluded by design
  177. * as tree represents the more recent analysis.
  178. */
  179. public List<ComponentDto> selectAncestors(DbSession dbSession, ComponentDto component) {
  180. if (component.isRoot()) {
  181. return Collections.emptyList();
  182. }
  183. List<String> ancestorUuids = component.getUuidPathAsList();
  184. List<ComponentDto> ancestors = selectByUuids(dbSession, ancestorUuids);
  185. return Ordering.explicit(ancestorUuids).onResultOf(ComponentDto::uuid).immutableSortedCopy(ancestors);
  186. }
  187. /**
  188. * Select the children or the leaves of a base component, given by its UUID. The components that are not present in last
  189. * analysis are ignored.
  190. * <p>
  191. * An empty list is returned if the base component does not exist or if the base component is a leaf.
  192. */
  193. public List<ComponentDto> selectDescendants(DbSession dbSession, ComponentTreeQuery query) {
  194. Optional<ComponentDto> componentOpt = selectByUuid(dbSession, query.getBaseUuid());
  195. if (!componentOpt.isPresent()) {
  196. return emptyList();
  197. }
  198. ComponentDto component = componentOpt.get();
  199. return mapper(dbSession).selectDescendants(query, componentOpt.get().uuid(), query.getUuidPath(component));
  200. }
  201. public List<ComponentDto> selectChildren(DbSession dbSession, String branchUuid, Collection<ComponentDto> components) {
  202. Set<String> uuidPaths = components.stream().map(c -> c.getUuidPath() + c.uuid() + ".").collect(Collectors.toSet());
  203. return mapper(dbSession).selectChildren(branchUuid, uuidPaths);
  204. }
  205. /*
  206. SELECT ALL
  207. */
  208. public List<UuidWithBranchUuidDto> selectAllViewsAndSubViews(DbSession session) {
  209. return mapper(session).selectUuidsForQualifiers(Qualifiers.APP, Qualifiers.VIEW, Qualifiers.SUBVIEW);
  210. }
  211. /**
  212. * Returns all projects (Scope {@link Scopes#PROJECT} and qualifier
  213. * {@link Qualifiers#PROJECT}) which are enabled.
  214. * <p>
  215. * Branches are not returned.
  216. * <p>
  217. * Used by Views.
  218. */
  219. public List<ComponentDto> selectProjects(DbSession session) {
  220. return mapper(session).selectProjects();
  221. }
  222. /**
  223. * Used by Governance
  224. */
  225. public Set<String> selectViewKeysWithEnabledCopyOfProject(DbSession session, Set<String> projectUuids) {
  226. return executeLargeInputsIntoSet(projectUuids,
  227. partition -> mapper(session).selectViewKeysWithEnabledCopyOfProject(partition),
  228. i -> i);
  229. }
  230. public List<String> selectProjectsFromView(DbSession session, String viewUuid, String projectViewUuid) {
  231. var escapedViewUuid = viewUuid.replace("_", "\\_").replace("%", "\\%");
  232. return mapper(session).selectProjectsFromView("%." + escapedViewUuid + ".%", projectViewUuid);
  233. }
  234. /**
  235. * Selects all components that are relevant for indexing. The result is not returned (since it is usually too big), but handed over to the <code>handler</code>
  236. *
  237. * @param session the database session
  238. * @param projectUuid the project uuid, which is selected with all of its children
  239. * @param handler the action to be applied to every result
  240. */
  241. public void scrollForIndexing(DbSession session, @Nullable String projectUuid, ResultHandler<ComponentDto> handler) {
  242. mapper(session).scrollForIndexing(projectUuid, handler);
  243. }
  244. /**
  245. * Retrieve enabled components keys with given qualifiers
  246. * <p>
  247. * Used by Views plugin
  248. */
  249. public Set<ComponentDto> selectComponentsByQualifiers(DbSession dbSession, Set<String> qualifiers) {
  250. checkArgument(!qualifiers.isEmpty(), "Qualifiers cannot be empty");
  251. return new HashSet<>(mapper(dbSession).selectComponentsByQualifiers(qualifiers));
  252. }
  253. /**
  254. * Returns components with open issues from P/Rs that use a certain branch as reference (reference branch).
  255. * Excludes components from the current branch.
  256. */
  257. public List<KeyWithUuidDto> selectComponentsFromPullRequestsTargetingCurrentBranchThatHaveOpenIssues(DbSession dbSession, String referenceBranchUuid, String currentBranchUuid) {
  258. return mapper(dbSession).selectComponentsFromPullRequestsTargetingCurrentBranchThatHaveOpenIssues(referenceBranchUuid, currentBranchUuid);
  259. }
  260. /**
  261. * Returns components with open issues from the given branches
  262. */
  263. public List<KeyWithUuidDto> selectComponentsFromBranchesThatHaveOpenIssues(DbSession dbSession, Set<String> branchUuids) {
  264. if (branchUuids.isEmpty()) {
  265. return emptyList();
  266. }
  267. return executeLargeInputs(branchUuids, input -> mapper(dbSession).selectComponentsFromBranchesThatHaveOpenIssues(input));
  268. }
  269. /**
  270. * Scroll all <strong>enabled</strong> files of the specified project (same project_uuid) in no specific order with
  271. * 'SOURCE' source and a non null path.
  272. */
  273. public void scrollAllFilesForFileMove(DbSession session, String branchUuid, ResultHandler<FileMoveRowDto> handler) {
  274. mapper(session).scrollAllFilesForFileMove(branchUuid, handler);
  275. }
  276. public List<ProjectNclocDistributionDto> selectPrivateProjectsWithNcloc(DbSession dbSession) {
  277. return mapper(dbSession).selectPrivateProjectsWithNcloc();
  278. }
  279. public boolean existAnyOfComponentsWithQualifiers(DbSession session, Collection<String> componentKeys, Set<String> qualifiers) {
  280. if (!componentKeys.isEmpty()) {
  281. List<Boolean> result = new LinkedList<>();
  282. return executeLargeInputs(componentKeys, input -> {
  283. boolean groupNeedIssueSync = mapper(session).checkIfAnyOfComponentsWithQualifiers(input, qualifiers) > 0;
  284. result.add(groupNeedIssueSync);
  285. return result;
  286. }).stream().anyMatch(b -> b);
  287. }
  288. return false;
  289. }
  290. /*
  291. INSERT / UPDATE
  292. */
  293. public void insert(DbSession session, ComponentDto item) {
  294. mapper(session).insert(item);
  295. if (!isBranchOrPullRequest(item)) {
  296. auditPersister.addComponent(session, new ComponentNewValue(item));
  297. }
  298. }
  299. public void insert(DbSession session, Collection<ComponentDto> items) {
  300. insert(session, items.stream());
  301. }
  302. private void insert(DbSession session, Stream<ComponentDto> items) {
  303. items.forEach(item -> insert(session, item));
  304. }
  305. public void insert(DbSession session, ComponentDto item, ComponentDto... others) {
  306. insert(session, Stream.concat(Stream.of(item), Arrays.stream(others)));
  307. }
  308. public void update(DbSession session, ComponentUpdateDto component, String qualifier) {
  309. auditPersister.updateComponent(session, new ComponentNewValue(component.getUuid(), component.getBName(),
  310. component.getBKey(), component.isBEnabled(), component.getBPath(), qualifier));
  311. mapper(session).update(component);
  312. }
  313. public void updateBEnabledToFalse(DbSession session, Collection<String> uuids) {
  314. executeLargeUpdates(uuids, mapper(session)::updateBEnabledToFalse);
  315. }
  316. public void applyBChangesForRootComponentUuid(DbSession session, String branchUuid) {
  317. mapper(session).applyBChangesForRootComponentUuid(branchUuid);
  318. }
  319. public void resetBChangedForRootComponentUuid(DbSession session, String branchUuid) {
  320. mapper(session).resetBChangedForRootComponentUuid(branchUuid);
  321. }
  322. public void setPrivateForRootComponentUuidWithoutAudit(DbSession session, String branchUuid, boolean isPrivate) {
  323. mapper(session).setPrivateForRootComponentUuid(branchUuid, isPrivate);
  324. }
  325. public void setPrivateForRootComponentUuid(DbSession session, String branchUuid, boolean isPrivate, String qualifier, String componentKey, String componentName) {
  326. ComponentNewValue componentNewValue = new ComponentNewValue(branchUuid, componentName, componentKey, isPrivate, qualifier);
  327. auditPersister.updateComponentVisibility(session, componentNewValue);
  328. mapper(session).setPrivateForRootComponentUuid(branchUuid, isPrivate);
  329. }
  330. /*
  331. UTIL
  332. */
  333. private static ComponentMapper mapper(DbSession session) {
  334. return session.getMapper(ComponentMapper.class);
  335. }
  336. private static void checkThatNotTooManyComponents(ComponentQuery query) {
  337. checkThatNotTooManyConditions(query.getComponentKeys(), "Too many component keys in query");
  338. checkThatNotTooManyConditions(query.getComponentUuids(), "Too many component UUIDs in query");
  339. }
  340. private static boolean isBranchOrPullRequest(ComponentDto item) {
  341. return item.getMainBranchProjectUuid() != null;
  342. }
  343. }