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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 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.Map;
  29. import java.util.Optional;
  30. import java.util.Set;
  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 static com.google.common.base.Preconditions.checkArgument;
  41. import static java.util.Collections.emptyList;
  42. import static org.sonar.core.util.stream.MoreCollectors.toList;
  43. import static org.sonar.core.util.stream.MoreCollectors.toSet;
  44. import static org.sonar.db.DatabaseUtils.checkThatNotTooManyConditions;
  45. import static org.sonar.db.DatabaseUtils.executeLargeInputs;
  46. import static org.sonar.db.DatabaseUtils.executeLargeInputsIntoSet;
  47. import static org.sonar.db.DatabaseUtils.executeLargeUpdates;
  48. import static org.sonar.db.component.ComponentDto.generateBranchKey;
  49. import static org.sonar.db.component.ComponentDto.generatePullRequestKey;
  50. public class ComponentDao implements Dao {
  51. private static List<ComponentDto> selectByQueryImpl(DbSession session, ComponentQuery query, int offset, int limit) {
  52. if (query.hasEmptySetOfComponents()) {
  53. return emptyList();
  54. }
  55. checkThatNotTooManyComponents(query);
  56. return mapper(session).selectByQuery(query, new RowBounds(offset, limit));
  57. }
  58. private static int countByQueryImpl(DbSession session, ComponentQuery query) {
  59. if (query.hasEmptySetOfComponents()) {
  60. return 0;
  61. }
  62. checkThatNotTooManyComponents(query);
  63. return mapper(session).countByQuery(query);
  64. }
  65. private static ComponentMapper mapper(DbSession session) {
  66. return session.getMapper(ComponentMapper.class);
  67. }
  68. public Optional<ComponentDto> selectByUuid(DbSession session, String uuid) {
  69. return Optional.ofNullable(mapper(session).selectByUuid(uuid));
  70. }
  71. public ComponentDto selectOrFailByUuid(DbSession session, String uuid) {
  72. Optional<ComponentDto> componentDto = selectByUuid(session, uuid);
  73. if (!componentDto.isPresent()) {
  74. throw new RowNotFoundException(String.format("Component with uuid '%s' not found", uuid));
  75. }
  76. return componentDto.get();
  77. }
  78. /**
  79. * @throws IllegalArgumentException if parameter query#getComponentIds() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  80. * @throws IllegalArgumentException if parameter query#getComponentKeys() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  81. * @throws IllegalArgumentException if parameter query#getMainComponentUuids() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  82. */
  83. public List<ComponentDto> selectByQuery(DbSession dbSession, ComponentQuery query, int offset, int limit) {
  84. return selectByQueryImpl(dbSession, query, offset, limit);
  85. }
  86. /**
  87. * @throws IllegalArgumentException if parameter query#getComponentIds() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  88. * @throws IllegalArgumentException if parameter query#getComponentKeys() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  89. * @throws IllegalArgumentException if parameter query#getMainComponentUuids() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  90. */
  91. public int countByQuery(DbSession session, ComponentQuery query) {
  92. return countByQueryImpl(session, query);
  93. }
  94. public List<ComponentDto> selectSubProjectsByComponentUuids(DbSession session, Collection<String> uuids) {
  95. if (uuids.isEmpty()) {
  96. return emptyList();
  97. }
  98. return mapper(session).selectSubProjectsByComponentUuids(uuids);
  99. }
  100. public List<ComponentDto> selectDescendantModules(DbSession session, String rootComponentUuid) {
  101. return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, false);
  102. }
  103. public List<ComponentDto> selectEnabledDescendantModules(DbSession session, String rootComponentUuid) {
  104. return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, true);
  105. }
  106. public List<FilePathWithHashDto> selectEnabledDescendantFiles(DbSession session, String rootComponentUuid) {
  107. return mapper(session).selectDescendantFiles(rootComponentUuid, Scopes.FILE, true);
  108. }
  109. public List<FilePathWithHashDto> selectEnabledFilesFromProject(DbSession session, String rootComponentUuid) {
  110. return mapper(session).selectEnabledFilesFromProject(rootComponentUuid);
  111. }
  112. public List<ComponentDto> selectByUuids(DbSession session, Collection<String> uuids) {
  113. return executeLargeInputs(uuids, mapper(session)::selectByUuids);
  114. }
  115. public List<String> selectExistingUuids(DbSession session, Collection<String> uuids) {
  116. return executeLargeInputs(uuids, mapper(session)::selectExistingUuids);
  117. }
  118. /**
  119. * Return all components of a project (including disable ones)
  120. */
  121. public List<ComponentDto> selectAllComponentsFromProjectKey(DbSession session, String projectKey) {
  122. return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, null, false);
  123. }
  124. public List<KeyWithUuidDto> selectUuidsByKeyFromProjectKey(DbSession session, String projectKey) {
  125. return mapper(session).selectUuidsByKeyFromProjectKey(projectKey);
  126. }
  127. public List<ComponentDto> selectProjectAndModulesFromProjectKey(DbSession session, String projectKey, boolean excludeDisabled) {
  128. return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, Scopes.PROJECT, excludeDisabled);
  129. }
  130. public int countEnabledModulesByProjectUuid(DbSession session, String projectUuid) {
  131. return mapper(session).countEnabledModulesByProjectUuid(projectUuid);
  132. }
  133. public List<ComponentDto> selectEnabledModulesFromProjectKey(DbSession session, String projectKey) {
  134. return selectProjectAndModulesFromProjectKey(session, projectKey, true);
  135. }
  136. public List<ComponentDto> selectByKeys(DbSession session, Collection<String> keys) {
  137. return executeLargeInputs(keys, mapper(session)::selectByKeys);
  138. }
  139. public List<ComponentDto> selectByKeysAndBranch(DbSession session, Collection<String> keys, String branch) {
  140. List<String> dbKeys = keys.stream().map(k -> generateBranchKey(k, branch)).collect(toList());
  141. List<String> allKeys = Stream.of(keys, dbKeys).flatMap(Collection::stream).collect(toList());
  142. return executeLargeInputs(allKeys, subKeys -> mapper(session).selectByKeysAndBranch(subKeys, branch));
  143. }
  144. /**
  145. * Return list of components that will will mix main and branch components.
  146. * Please note that a project can only appear once in the list, it's not possible to ask for many branches on same project with this method.
  147. */
  148. public List<ComponentDto> selectByKeysAndBranches(DbSession session, Map<String, String> branchesByKey) {
  149. Set<String> dbKeys = branchesByKey.entrySet().stream()
  150. .map(entry -> generateBranchKey(entry.getKey(), entry.getValue()))
  151. .collect(toSet());
  152. return selectByDbKeys(session, dbKeys);
  153. }
  154. public List<ComponentDto> selectByDbKeys(DbSession session, Set<String> dbKeys) {
  155. return executeLargeInputs(dbKeys, subKeys -> mapper(session).selectByDbKeys(subKeys));
  156. }
  157. public List<ComponentDto> selectByKeysAndPullRequest(DbSession session, Collection<String> keys, String pullRequestId) {
  158. List<String> dbKeys = keys.stream().map(k -> generatePullRequestKey(k, pullRequestId)).collect(toList());
  159. List<String> allKeys = Stream.of(keys, dbKeys).flatMap(Collection::stream).collect(toList());
  160. return executeLargeInputs(allKeys, subKeys -> mapper(session).selectByKeysAndBranch(subKeys, pullRequestId));
  161. }
  162. /**
  163. * List of ancestors, ordered from root to parent. The list is empty
  164. * if the component is a tree root. Disabled components are excluded by design
  165. * as tree represents the more recent analysis.
  166. */
  167. public List<ComponentDto> selectAncestors(DbSession dbSession, ComponentDto component) {
  168. if (component.isRoot()) {
  169. return Collections.emptyList();
  170. }
  171. List<String> ancestorUuids = component.getUuidPathAsList();
  172. List<ComponentDto> ancestors = selectByUuids(dbSession, ancestorUuids);
  173. return Ordering.explicit(ancestorUuids).onResultOf(ComponentDto::uuid).immutableSortedCopy(ancestors);
  174. }
  175. /**
  176. * Select the children or the leaves of a base component, given by its UUID. The components that are not present in last
  177. * analysis are ignored.
  178. * <p>
  179. * An empty list is returned if the base component does not exist or if the base component is a leaf.
  180. */
  181. public List<ComponentDto> selectDescendants(DbSession dbSession, ComponentTreeQuery query) {
  182. Optional<ComponentDto> componentOpt = selectByUuid(dbSession, query.getBaseUuid());
  183. if (!componentOpt.isPresent()) {
  184. return emptyList();
  185. }
  186. ComponentDto component = componentOpt.get();
  187. return mapper(dbSession).selectDescendants(query, componentOpt.get().uuid(), query.getUuidPath(component));
  188. }
  189. public ComponentDto selectOrFailByKey(DbSession session, String key) {
  190. Optional<ComponentDto> component = selectByKey(session, key);
  191. if (!component.isPresent()) {
  192. throw new RowNotFoundException(String.format("Component key '%s' not found", key));
  193. }
  194. return component.get();
  195. }
  196. public Optional<ComponentDto> selectByKey(DbSession session, String key) {
  197. return Optional.ofNullable(mapper(session).selectByKey(key));
  198. }
  199. public Optional<ComponentDto> selectByKeyAndBranch(DbSession session, String key, String branch) {
  200. return Optional.ofNullable(mapper(session).selectBranchByKeyAndBranchKey(key, generateBranchKey(key, branch), branch));
  201. }
  202. public Optional<ComponentDto> selectByKeyAndPullRequest(DbSession session, String key, String pullRequestId) {
  203. return Optional.ofNullable(mapper(session).selectPrByKeyAndBranchKey(key, generatePullRequestKey(key, pullRequestId), pullRequestId));
  204. }
  205. public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) {
  206. return mapper(session).selectUuidsForQualifiers(Qualifiers.APP, Qualifiers.VIEW, Qualifiers.SUBVIEW);
  207. }
  208. /**
  209. * Used by Governance
  210. */
  211. public Set<String> selectViewKeysWithEnabledCopyOfProject(DbSession session, Set<String> projectUuids) {
  212. return executeLargeInputsIntoSet(projectUuids,
  213. partition -> mapper(session).selectViewKeysWithEnabledCopyOfProject(partition),
  214. i -> i);
  215. }
  216. public List<String> selectProjectsFromView(DbSession session, String viewUuid, String projectViewUuid) {
  217. return mapper(session).selectProjectsFromView("%." + viewUuid + ".%", projectViewUuid);
  218. }
  219. /**
  220. * Returns all projects (Scope {@link Scopes#PROJECT} and qualifier
  221. * {@link Qualifiers#PROJECT}) which are enabled.
  222. * <p>
  223. * Branches are not returned.
  224. * <p>
  225. * Used by Views.
  226. */
  227. public List<ComponentDto> selectProjects(DbSession session) {
  228. return mapper(session).selectProjects();
  229. }
  230. /**
  231. * 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>
  232. *
  233. * @param session the database session
  234. * @param projectUuid the project uuid, which is selected with all of its children
  235. * @param handler the action to be applied to every result
  236. */
  237. public void scrollForIndexing(DbSession session, @Nullable String projectUuid, ResultHandler<ComponentDto> handler) {
  238. mapper(session).scrollForIndexing(projectUuid, handler);
  239. }
  240. /**
  241. * Retrieves all components with a specific root project Uuid, no other filtering is done by this method.
  242. * <p>
  243. * Used by Views plugin
  244. */
  245. public List<ComponentDto> selectByProjectUuid(String projectUuid, DbSession dbSession) {
  246. return mapper(dbSession).selectByProjectUuid(projectUuid);
  247. }
  248. /**
  249. * Retrieve enabled components keys with given qualifiers
  250. * <p>
  251. * Used by Views plugin
  252. */
  253. public Set<ComponentDto> selectComponentsByQualifiers(DbSession dbSession, Set<String> qualifiers) {
  254. checkArgument(!qualifiers.isEmpty(), "Qualifiers cannot be empty");
  255. return new HashSet<>(mapper(dbSession).selectComponentsByQualifiers(qualifiers));
  256. }
  257. public List<ComponentWithModuleUuidDto> selectEnabledComponentsWithModuleUuidFromProjectKey(DbSession dbSession, String projectKey) {
  258. return mapper(dbSession).selectEnabledComponentsWithModuleUuidFromProjectKey(projectKey);
  259. }
  260. /**
  261. * Returns components with open issues from P/Rs that use a certain branch as reference (reference branch).
  262. * Excludes components from the current branch.
  263. */
  264. public List<KeyWithUuidDto> selectAllSiblingComponentKeysHavingOpenIssues(DbSession dbSession, String referenceBranchUuid, String currentBranchUuid) {
  265. return mapper(dbSession).selectAllSiblingComponentKeysHavingOpenIssues(referenceBranchUuid, currentBranchUuid);
  266. }
  267. /**
  268. * Scroll all <strong>enabled</strong> files of the specified project (same project_uuid) in no specific order with
  269. * 'SOURCE' source and a non null path.
  270. */
  271. public void scrollAllFilesForFileMove(DbSession session, String projectUuid, ResultHandler<FileMoveRowDto> handler) {
  272. mapper(session).scrollAllFilesForFileMove(projectUuid, handler);
  273. }
  274. public void insert(DbSession session, ComponentDto item) {
  275. mapper(session).insert(item);
  276. }
  277. public void insert(DbSession session, Collection<ComponentDto> items) {
  278. insert(session, items.stream());
  279. }
  280. private void insert(DbSession session, Stream<ComponentDto> items) {
  281. items.forEach(item -> insert(session, item));
  282. }
  283. public void insert(DbSession session, ComponentDto item, ComponentDto... others) {
  284. insert(session, Stream.concat(Stream.of(item), Arrays.stream(others)));
  285. }
  286. public void update(DbSession session, ComponentUpdateDto component) {
  287. mapper(session).update(component);
  288. }
  289. public void updateBEnabledToFalse(DbSession session, Collection<String> uuids) {
  290. executeLargeUpdates(uuids, mapper(session)::updateBEnabledToFalse);
  291. }
  292. public void applyBChangesForRootComponentUuid(DbSession session, String projectUuid) {
  293. mapper(session).applyBChangesForRootComponentUuid(projectUuid);
  294. }
  295. public void resetBChangedForRootComponentUuid(DbSession session, String projectUuid) {
  296. mapper(session).resetBChangedForRootComponentUuid(projectUuid);
  297. }
  298. public void setPrivateForRootComponentUuid(DbSession session, String projectUuid, boolean isPrivate) {
  299. mapper(session).setPrivateForRootComponentUuid(projectUuid, isPrivate);
  300. }
  301. public void delete(DbSession session, String componentUuid) {
  302. mapper(session).delete(componentUuid);
  303. }
  304. private static void checkThatNotTooManyComponents(ComponentQuery query) {
  305. checkThatNotTooManyConditions(query.getComponentKeys(), "Too many component keys in query");
  306. checkThatNotTooManyConditions(query.getComponentUuids(), "Too many component UUIDs in query");
  307. }
  308. public List<ProjectNclocDistributionDto> selectPrivateProjectsWithNcloc(DbSession dbSession) {
  309. return mapper(dbSession).selectPrivateProjectsWithNcloc();
  310. }
  311. public boolean existAnyOfComponentsWithQualifiers(DbSession session, Collection<String> componentKeys, Set<String> qualifiers) {
  312. if (!componentKeys.isEmpty()) {
  313. List<Boolean> result = new LinkedList<>();
  314. return executeLargeInputs(componentKeys, input -> {
  315. boolean groupNeedIssueSync = mapper(session).checkIfAnyOfComponentsWithQualifiers(input, qualifiers) > 0;
  316. result.add(groupNeedIssueSync);
  317. return result;
  318. }).stream().anyMatch(b -> b);
  319. }
  320. return false;
  321. }
  322. }