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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2018 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.base.Optional;
  22. import com.google.common.collect.Lists;
  23. import com.google.common.collect.Ordering;
  24. import java.util.Collection;
  25. import java.util.Collections;
  26. import java.util.HashSet;
  27. import java.util.List;
  28. import java.util.Locale;
  29. import java.util.Set;
  30. import java.util.stream.Stream;
  31. import javax.annotation.CheckForNull;
  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 java.util.Objects.requireNonNull;
  43. import static org.apache.commons.lang.StringUtils.isBlank;
  44. import static org.sonar.core.util.stream.MoreCollectors.toList;
  45. import static org.sonar.db.DaoDatabaseUtils.buildLikeValue;
  46. import static org.sonar.db.DatabaseUtils.checkThatNotTooManyConditions;
  47. import static org.sonar.db.DatabaseUtils.executeLargeInputs;
  48. import static org.sonar.db.DatabaseUtils.executeLargeUpdates;
  49. import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER;
  50. import static org.sonar.db.component.ComponentDto.generateBranchKey;
  51. import static org.sonar.db.component.ComponentDto.generatePullRequestKey;
  52. public class ComponentDao implements Dao {
  53. private static List<ComponentDto> selectByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query, int offset, int limit) {
  54. if (query.hasEmptySetOfComponents()) {
  55. return emptyList();
  56. }
  57. checkThatNotTooManyComponents(query);
  58. return mapper(session).selectByQuery(organizationUuid, query, new RowBounds(offset, limit));
  59. }
  60. private static int countByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query) {
  61. if (query.hasEmptySetOfComponents()) {
  62. return 0;
  63. }
  64. checkThatNotTooManyComponents(query);
  65. return mapper(session).countByQuery(organizationUuid, query);
  66. }
  67. @CheckForNull
  68. private static String buildUpperLikeSql(@Nullable String textQuery) {
  69. if (isBlank(textQuery)) {
  70. return null;
  71. }
  72. return buildLikeValue(textQuery.toUpperCase(Locale.ENGLISH), BEFORE_AND_AFTER);
  73. }
  74. private static ComponentMapper mapper(DbSession session) {
  75. return session.getMapper(ComponentMapper.class);
  76. }
  77. public ComponentDto selectOrFailById(DbSession session, long id) {
  78. Optional<ComponentDto> componentDto = selectById(session, id);
  79. if (!componentDto.isPresent()) {
  80. throw new RowNotFoundException(String.format("Component id does not exist: %d", id));
  81. }
  82. return componentDto.get();
  83. }
  84. public Optional<ComponentDto> selectById(DbSession session, long id) {
  85. return Optional.fromNullable(mapper(session).selectById(id));
  86. }
  87. public Optional<ComponentDto> selectByUuid(DbSession session, String uuid) {
  88. return Optional.fromNullable(mapper(session).selectByUuid(uuid));
  89. }
  90. public ComponentDto selectOrFailByUuid(DbSession session, String uuid) {
  91. Optional<ComponentDto> componentDto = selectByUuid(session, uuid);
  92. if (!componentDto.isPresent()) {
  93. throw new RowNotFoundException(String.format("Component with uuid '%s' not found", uuid));
  94. }
  95. return componentDto.get();
  96. }
  97. /**
  98. * Same as {@link #selectByQuery(DbSession, String, ComponentQuery, int, int)} except
  99. * that the filter on organization is disabled.
  100. */
  101. public List<ComponentDto> selectByQuery(DbSession session, ComponentQuery query, int offset, int limit) {
  102. return selectByQueryImpl(session, null, 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#getComponentUuids() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  108. */
  109. public List<ComponentDto> selectByQuery(DbSession dbSession, String organizationUuid, ComponentQuery query, int offset, int limit) {
  110. requireNonNull(organizationUuid, "organizationUuid can't be null");
  111. return selectByQueryImpl(dbSession, organizationUuid, query, offset, limit);
  112. }
  113. /**
  114. * Same as {@link #countByQuery(DbSession, String, ComponentQuery)} except
  115. * that the filter on organization is disabled.
  116. */
  117. public int countByQuery(DbSession session, ComponentQuery query) {
  118. return countByQueryImpl(session, null, query);
  119. }
  120. /**
  121. * @throws IllegalArgumentException if parameter query#getComponentIds() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  122. * @throws IllegalArgumentException if parameter query#getComponentKeys() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  123. * @throws IllegalArgumentException if parameter query#getComponentUuids() has more than {@link org.sonar.db.DatabaseUtils#PARTITION_SIZE_FOR_ORACLE} values
  124. */
  125. public int countByQuery(DbSession session, String organizationUuid, ComponentQuery query) {
  126. requireNonNull(organizationUuid, "organizationUuid can't be null");
  127. return countByQueryImpl(session, organizationUuid, query);
  128. }
  129. public List<ComponentDto> selectSubProjectsByComponentUuids(DbSession session, Collection<String> uuids) {
  130. if (uuids.isEmpty()) {
  131. return emptyList();
  132. }
  133. return mapper(session).selectSubProjectsByComponentUuids(uuids);
  134. }
  135. public List<ComponentDto> selectDescendantModules(DbSession session, String rootComponentUuid) {
  136. return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, false);
  137. }
  138. public List<ComponentDto> selectEnabledDescendantModules(DbSession session, String rootComponentUuid) {
  139. return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, true);
  140. }
  141. public List<FilePathWithHashDto> selectEnabledDescendantFiles(DbSession session, String rootComponentUuid) {
  142. return mapper(session).selectDescendantFiles(rootComponentUuid, Scopes.FILE, true);
  143. }
  144. public List<FilePathWithHashDto> selectEnabledFilesFromProject(DbSession session, String rootComponentUuid) {
  145. return mapper(session).selectEnabledFilesFromProject(rootComponentUuid);
  146. }
  147. public List<ComponentDto> selectByIds(DbSession session, Collection<Long> ids) {
  148. return executeLargeInputs(ids, mapper(session)::selectByIds);
  149. }
  150. public List<ComponentDto> selectByUuids(DbSession session, Collection<String> uuids) {
  151. return executeLargeInputs(uuids, mapper(session)::selectByUuids);
  152. }
  153. public List<String> selectExistingUuids(DbSession session, Collection<String> uuids) {
  154. return executeLargeInputs(uuids, mapper(session)::selectExistingUuids);
  155. }
  156. /**
  157. * Return all components of a project (including disable ones)
  158. */
  159. public List<ComponentDto> selectAllComponentsFromProjectKey(DbSession session, String projectKey) {
  160. return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, null, false);
  161. }
  162. public List<KeyWithUuidDto> selectUuidsByKeyFromProjectKey(DbSession session, String projectKey) {
  163. return mapper(session).selectUuidsByKeyFromProjectKey(projectKey);
  164. }
  165. public List<ComponentDto> selectEnabledModulesFromProjectKey(DbSession session, String projectKey) {
  166. return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, Scopes.PROJECT, true);
  167. }
  168. public List<ComponentDto> selectByKeys(DbSession session, Collection<String> keys) {
  169. return executeLargeInputs(keys, mapper(session)::selectByKeys);
  170. }
  171. public List<ComponentDto> selectByKeysAndBranch(DbSession session, Collection<String> keys, String branch) {
  172. List<String> dbKeys = keys.stream().map(k -> generateBranchKey(k, branch)).collect(toList());
  173. List<String> allKeys = Stream.of(keys, dbKeys).flatMap(Collection::stream).collect(toList());
  174. return executeLargeInputs(allKeys, subKeys -> mapper(session).selectByKeysAndBranch(subKeys, branch));
  175. }
  176. public List<ComponentDto> selectByKeysAndPullRequest(DbSession session, Collection<String> keys, String pullRequestId) {
  177. List<String> dbKeys = keys.stream().map(k -> generatePullRequestKey(k, pullRequestId)).collect(toList());
  178. List<String> allKeys = Stream.of(keys, dbKeys).flatMap(Collection::stream).collect(toList());
  179. return executeLargeInputs(allKeys, subKeys -> mapper(session).selectByKeysAndBranch(subKeys, pullRequestId));
  180. }
  181. public List<ComponentDto> selectComponentsHavingSameKeyOrderedById(DbSession session, String key) {
  182. return mapper(session).selectComponentsHavingSameKeyOrderedById(key);
  183. }
  184. /**
  185. * List of ancestors, ordered from root to parent. The list is empty
  186. * if the component is a tree root. Disabled components are excluded by design
  187. * as tree represents the more recent analysis.
  188. */
  189. public List<ComponentDto> selectAncestors(DbSession dbSession, ComponentDto component) {
  190. if (component.isRoot()) {
  191. return Collections.emptyList();
  192. }
  193. List<String> ancestorUuids = component.getUuidPathAsList();
  194. List<ComponentDto> ancestors = selectByUuids(dbSession, ancestorUuids);
  195. return Ordering.explicit(ancestorUuids).onResultOf(ComponentDto::uuid).immutableSortedCopy(ancestors);
  196. }
  197. /**
  198. * Select the children or the leaves of a base component, given by its UUID. The components that are not present in last
  199. * analysis are ignored.
  200. *
  201. * An empty list is returned if the base component does not exist or if the base component is a leaf.
  202. */
  203. public List<ComponentDto> selectDescendants(DbSession dbSession, ComponentTreeQuery query) {
  204. Optional<ComponentDto> componentOpt = selectByUuid(dbSession, query.getBaseUuid());
  205. if (!componentOpt.isPresent()) {
  206. return emptyList();
  207. }
  208. ComponentDto component = componentOpt.get();
  209. return mapper(dbSession).selectDescendants(query, componentOpt.get().uuid(), query.getUuidPath(component));
  210. }
  211. public ComponentDto selectOrFailByKey(DbSession session, String key) {
  212. Optional<ComponentDto> component = selectByKey(session, key);
  213. if (!component.isPresent()) {
  214. throw new RowNotFoundException(String.format("Component key '%s' not found", key));
  215. }
  216. return component.get();
  217. }
  218. public Optional<ComponentDto> selectByKey(DbSession session, String key) {
  219. return Optional.fromNullable(mapper(session).selectByKey(key));
  220. }
  221. public java.util.Optional<ComponentDto> selectByKeyAndBranch(DbSession session, String key, String branch) {
  222. return java.util.Optional.ofNullable(mapper(session).selectByKeyAndBranchKey(key, generateBranchKey(key, branch), branch));
  223. }
  224. public java.util.Optional<ComponentDto> selectByKeyAndPullRequest(DbSession session, String key, String pullRequestId) {
  225. return java.util.Optional.ofNullable(mapper(session).selectByKeyAndBranchKey(key, generatePullRequestKey(key, pullRequestId), pullRequestId));
  226. }
  227. public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) {
  228. return mapper(session).selectUuidsForQualifiers(Qualifiers.APP, Qualifiers.VIEW, Qualifiers.SUBVIEW);
  229. }
  230. public List<String> selectProjectsFromView(DbSession session, String viewUuid, String projectViewUuid) {
  231. return mapper(session).selectProjectsFromView("%." + viewUuid + ".%", projectViewUuid);
  232. }
  233. /**
  234. * Returns all projects (Scope {@link Scopes#PROJECT} and qualifier
  235. * {@link Qualifiers#PROJECT}) which are enabled.
  236. *
  237. * Branches are not returned.
  238. *
  239. * Used by Views.
  240. */
  241. public List<ComponentDto> selectProjects(DbSession session) {
  242. return mapper(session).selectProjects();
  243. }
  244. /**
  245. * Select all root components (projects and views), including disabled ones, for a given organization.
  246. *
  247. * Branches are not returned
  248. */
  249. public List<ComponentDto> selectAllRootsByOrganization(DbSession dbSession, String organizationUuid) {
  250. return mapper(dbSession).selectAllRootsByOrganization(organizationUuid);
  251. }
  252. public List<ComponentDto> selectGhostProjects(DbSession session, String organizationUuid, @Nullable String query, int offset, int limit) {
  253. return mapper(session).selectGhostProjects(organizationUuid, buildUpperLikeSql(query), new RowBounds(offset, limit));
  254. }
  255. public long countGhostProjects(DbSession session, String organizationUuid, @Nullable String query) {
  256. return mapper(session).countGhostProjects(organizationUuid, buildUpperLikeSql(query));
  257. }
  258. /**
  259. * 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>
  260. * @param session the database session
  261. * @param projectUuid the project uuid, which is selected with all of its children
  262. * @param handler the action to be applied to every result
  263. */
  264. public void scrollForIndexing(DbSession session, @Nullable String projectUuid, ResultHandler<ComponentDto> handler) {
  265. mapper(session).scrollForIndexing(projectUuid, handler);
  266. }
  267. /**
  268. * Retrieves all components with a specific root project Uuid, no other filtering is done by this method.
  269. *
  270. * Used by Views plugin
  271. */
  272. public List<ComponentDto> selectByProjectUuid(String projectUuid, DbSession dbSession) {
  273. return mapper(dbSession).selectByProjectUuid(projectUuid);
  274. }
  275. /**
  276. * Retrieve enabled components keys with given qualifiers
  277. *
  278. * Used by Views plugin
  279. */
  280. public Set<ComponentDto> selectComponentsByQualifiers(DbSession dbSession, Set<String> qualifiers) {
  281. checkArgument(!qualifiers.isEmpty(), "Qualifiers cannot be empty");
  282. return new HashSet<>(mapper(dbSession).selectComponentsByQualifiers(qualifiers));
  283. }
  284. public List<ComponentDto> selectProjectsByNameQuery(DbSession dbSession, @Nullable String nameQuery, boolean includeModules) {
  285. String nameQueryForSql = nameQuery == null ? null : buildLikeValue(nameQuery, BEFORE_AND_AFTER).toUpperCase(Locale.ENGLISH);
  286. return mapper(dbSession).selectProjectsByNameQuery(nameQueryForSql, includeModules);
  287. }
  288. public void insert(DbSession session, ComponentDto item) {
  289. mapper(session).insert(item);
  290. }
  291. public void insert(DbSession session, Collection<ComponentDto> items) {
  292. for (ComponentDto item : items) {
  293. insert(session, item);
  294. }
  295. }
  296. public void insert(DbSession session, ComponentDto item, ComponentDto... others) {
  297. insert(session, Lists.asList(item, others));
  298. }
  299. public void update(DbSession session, ComponentUpdateDto component) {
  300. mapper(session).update(component);
  301. }
  302. public void updateTags(DbSession session, ComponentDto component) {
  303. mapper(session).updateTags(component);
  304. }
  305. public void updateBEnabledToFalse(DbSession session, Collection<String> uuids) {
  306. executeLargeUpdates(uuids, mapper(session)::updateBEnabledToFalse);
  307. }
  308. public void applyBChangesForRootComponentUuid(DbSession session, String projectUuid) {
  309. mapper(session).applyBChangesForRootComponentUuid(projectUuid);
  310. }
  311. public void resetBChangedForRootComponentUuid(DbSession session, String projectUuid) {
  312. mapper(session).resetBChangedForRootComponentUuid(projectUuid);
  313. }
  314. public void setPrivateForRootComponentUuid(DbSession session, String projectUuid, boolean isPrivate) {
  315. mapper(session).setPrivateForRootComponentUuid(projectUuid, isPrivate);
  316. }
  317. public void delete(DbSession session, long componentId) {
  318. mapper(session).delete(componentId);
  319. }
  320. public List<KeyWithUuidDto> selectComponentKeysHavingIssuesToMerge(DbSession dbSession, String mergeBranchUuid) {
  321. return mapper(dbSession).selectComponentKeysHavingIssuesToMerge(mergeBranchUuid);
  322. }
  323. private static void checkThatNotTooManyComponents(ComponentQuery query) {
  324. checkThatNotTooManyConditions(query.getComponentIds(), "Too many component ids in query");
  325. checkThatNotTooManyConditions(query.getComponentKeys(), "Too many component keys in query");
  326. checkThatNotTooManyConditions(query.getComponentUuids(), "Too many component UUIDs in query");
  327. }
  328. }