<commit_before>// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package google.registry.tools;

import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DatastoreServiceUtils.getNameOrId;
import static google.registry.util.DiffUtils.prettyPrintEntityDeepDiff;
import static java.util.stream.Collectors.joining;

import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import google.registry.model.ImmutableObject;
import google.registry.persistence.VKey;
import google.registry.schema.replay.SqlEntity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;

/** A {@link ConfirmingCommand} that changes objects in Datastore. */
public abstract class MutatingCommand extends ConfirmingCommand implements CommandWithRemoteApi {

  /**
   * A mutation of a specific entity, represented by an old and a new version of the entity. Storing
   * the old version is necessary to enable checking that the existing entity has not been modified
   * when applying a mutation that was created outside the same transaction.
   */
  private static class EntityChange {

    /** The possible types of mutation that can be performed on an entity. */
    public enum ChangeType {
      CREATE,
      DELETE,
      UPDATE;

      /** Return the ChangeType corresponding to the given combination of version existences. */
      public static ChangeType get(boolean hasOldVersion, boolean hasNewVersion) {
        checkArgument(
            hasOldVersion || hasNewVersion,
            "An entity change must have an old version or a new version (or both)");
        return !hasOldVersion ? CREATE : (!hasNewVersion ? DELETE : UPDATE);
      }
    }

    /** The type of mutation being performed on the entity. */
    final ChangeType type;

    /** The old version of the entity, or null if this is a create. */
    final ImmutableObject oldEntity;

    /** The new version of the entity, or null if this is a delete. */
    final ImmutableObject newEntity;

    /** The key that points to the entity being changed. */
    final VKey<?> key;

    private EntityChange(ImmutableObject oldEntity, ImmutableObject newEntity) {
      type = ChangeType.get(oldEntity != null, newEntity != null);
      checkArgument(
          type != ChangeType.UPDATE || Key.create(oldEntity).equals(Key.create(newEntity)),
          "Both entity versions in an update must have the same Key.");
      this.oldEntity = oldEntity;
      this.newEntity = newEntity;
      ImmutableObject entity = MoreObjects.firstNonNull(oldEntity, newEntity);

      // This is one of the few cases where it is acceptable to create an asymmetric VKey (using
      // createOfy()).  We can use this code on DatastoreOnlyEntity's where we can't construct an
      // SQL key.
      key =
          entity instanceof SqlEntity
              ? VKey.from(Key.create(entity))
              : VKey.createOfy(entity.getClass(), Key.create(entity));
    }

    /**
     * EntityChange constructor that supports Vkey override. A Vkey is a key of an entity. This is a
     * workaround to handle cases when a SqlEntity instance does not have a primary key before being
     * persisted.
     */
    private EntityChange(ImmutableObject oldEntity, ImmutableObject newEntity, VKey<?> vkey) {
      type = ChangeType.get(oldEntity != null, newEntity != null);
      Key<?> oldKey = Key.create(oldEntity), newKey = Key.create(newEntity);
      if (type == ChangeType.UPDATE) {
        checkArgument(
            oldKey.equals(newKey), "Both entity versions in an update must have the same Key.");
        checkArgument(
            oldKey.equals(vkey.getOfyKey()),
            "The Key of the entity must be the same as the OfyKey of the vkey");
      } else if (type == ChangeType.CREATE) {
        checkArgument(
            newKey.equals(vkey.getOfyKey()),
            "Both entity versions in an update must have the same Key.");
      } else if (type == ChangeType.DELETE) {
        checkArgument(
            oldKey.equals(vkey.getOfyKey()),
            "The Key of the entity must be the same as the OfyKey of the vkey");
      }
      this.oldEntity = oldEntity;
      this.newEntity = newEntity;
      key = vkey;
    }

    /** Returns a human-readable ID string for the entity being changed. */
    public String getEntityId() {<commit_msg>Create key based on the change type (#1147)<commit_after>// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package google.registry.tools;

import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DatastoreServiceUtils.getNameOrId;
import static google.registry.util.DiffUtils.prettyPrintEntityDeepDiff;
import static java.util.stream.Collectors.joining;

import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import google.registry.model.ImmutableObject;
import google.registry.persistence.VKey;
import google.registry.schema.replay.SqlEntity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;

/** A {@link ConfirmingCommand} that changes objects in Datastore. */
public abstract class MutatingCommand extends ConfirmingCommand implements CommandWithRemoteApi {

  /**
   * A mutation of a specific entity, represented by an old and a new version of the entity. Storing
   * the old version is necessary to enable checking that the existing entity has not been modified
   * when applying a mutation that was created outside the same transaction.
   */
  private static class EntityChange {

    /** The possible types of mutation that can be performed on an entity. */
    public enum ChangeType {
      CREATE,
      DELETE,
      UPDATE;

      /** Return the ChangeType corresponding to the given combination of version existences. */
      public static ChangeType get(boolean hasOldVersion, boolean hasNewVersion) {
        checkArgument(
            hasOldVersion || hasNewVersion,
            "An entity change must have an old version or a new version (or both)");
        return !hasOldVersion ? CREATE : (!hasNewVersion ? DELETE : UPDATE);
      }
    }

    /** The type of mutation being performed on the entity. */
    final ChangeType type;

    /** The old version of the entity, or null if this is a create. */
    final ImmutableObject oldEntity;

    /** The new version of the entity, or null if this is a delete. */
    final ImmutableObject newEntity;

    /** The key that points to the entity being changed. */
    final VKey<?> key;

    private EntityChange(ImmutableObject oldEntity, ImmutableObject newEntity) {
      type = ChangeType.get(oldEntity != null, newEntity != null);
      checkArgument(
          type != ChangeType.UPDATE || Key.create(oldEntity).equals(Key.create(newEntity)),
          "Both entity versions in an update must have the same Key.");
      this.oldEntity = oldEntity;
      this.newEntity = newEntity;
      ImmutableObject entity = MoreObjects.firstNonNull(oldEntity, newEntity);

      // This is one of the few cases where it is acceptable to create an asymmetric VKey (using
      // createOfy()).  We can use this code on DatastoreOnlyEntity's where we can't construct an
      // SQL key.
      key =
          entity instanceof SqlEntity
              ? VKey.from(Key.create(entity))
              : VKey.createOfy(entity.getClass(), Key.create(entity));
    }

    /**
     * EntityChange constructor that supports Vkey override. A Vkey is a key of an entity. This is a
     * workaround to handle cases when a SqlEntity instance does not have a primary key before being
     * persisted.
     */
    private EntityChange(ImmutableObject oldEntity, ImmutableObject newEntity, VKey<?> vkey) {
      type = ChangeType.get(oldEntity != null, newEntity != null);
      if (type == ChangeType.UPDATE) {
        checkArgument(
            Key.create(oldEntity).equals(Key.create(newEntity)),
            "Both entity versions in an update must have the same Key.");
        checkArgument(
            Key.create(oldEntity).equals(vkey.getOfyKey()),
            "The Key of the entity must be the same as the OfyKey of the vkey");
      } else if (type == ChangeType.CREATE) {
        checkArgument(
            Key.create(newEntity).equals(vkey.getOfyKey()),
            "Both entity versions in an update must have the same Key.");
      } else if (type == ChangeType.DELETE) {
        checkArgument(
            Key.create(oldEntity).equals(vkey.getOfyKey()),
            "The Key of the entity must be the same as the OfyKey of the vkey");
      }
      this.oldEntity = oldEntity;
      this.newEntity = newEntity;
      key = vkey;
    }

    /** Returns a human-readable ID string for the entity being changed. */
    public String getEntityId() {
{'fraction_non_alphanumeric': 0.086061985641744, 'fraction_numerical': 0.001751006828926633, 'mean_word_length': 3.2814842578710643, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5525783', 'n_tokens_mistral': 3022, 'n_tokens_neox': 2962, 'n_words': 1096}