void setParent(
      DbSession dbSession, QualityProfileKey key, @Nullable QualityProfileKey parentKey) {
    QualityProfileDto profile = db.qualityProfileDao().getNonNullByKey(dbSession, key);
    if (parentKey == null) {
      // unset if parent is defined, else nothing to do
      removeParent(dbSession, profile);

    } else if (profile.getParentKey() == null || !profile.getParentKey().equals(parentKey)) {
      QualityProfileDto parentProfile =
          db.qualityProfileDao().getNonNullByKey(dbSession, parentKey);
      if (isDescendant(dbSession, profile, parentProfile)) {
        throw new BadRequestException(
            String.format(
                "Descendant profile '%s' can not be selected as parent of '%s'", parentKey, key));
      }
      removeParent(dbSession, profile);

      // set new parent
      profile.setParent(parentKey.name());
      db.qualityProfileDao().update(dbSession, profile);
      for (ActiveRuleDto parentActiveRule :
          db.activeRuleDao().findByProfileKey(dbSession, parentKey)) {
        RuleActivation activation =
            new RuleActivation(ActiveRuleKey.of(key, parentActiveRule.getKey().ruleKey()));
        activate(dbSession, activation);
      }
    }
  }
 /**
  * Deactivate a rule on a Quality profile WITHOUT committing db session, WITHOUT checking
  * permissions, and forcing removal of inherited rules
  */
 public List<ActiveRuleChange> deactivate(DbSession dbSession, RuleDto ruleDto) {
   List<ActiveRuleChange> changes = Lists.newArrayList();
   List<ActiveRuleDto> activeRules = db.activeRuleDao().findByRule(dbSession, ruleDto);
   for (ActiveRuleDto activeRule : activeRules) {
     changes.addAll(deactivate(dbSession, activeRule.getKey(), true));
   }
   return changes;
 }
 /** Does not commit */
 private void removeParent(DbSession dbSession, QualityProfileDto profileDto) {
   if (profileDto.getParent() != null) {
     profileDto.setParent(null);
     db.qualityProfileDao().update(dbSession, profileDto);
     for (ActiveRuleDto activeRule :
         db.activeRuleDao().findByProfileKey(dbSession, profileDto.getKey())) {
       if (ActiveRuleDto.INHERITED.equals(activeRule.getInheritance())) {
         deactivate(dbSession, activeRule.getKey(), true);
       } else if (ActiveRuleDto.OVERRIDES.equals(activeRule.getInheritance())) {
         activeRule.setInheritance(null);
         db.activeRuleDao().update(dbSession, activeRule);
       }
     }
   }
 }