@transaction.commit_on_success
    def _lock_case_versions(self):
        """
        Select caseversions from suites, create runcaseversions.

        WARNING: Testing this code in the PyCharm debugger will give an
        incorrect number of queries, because for the debugger to show all the
        information it wants, it must do queries itself.  When testing with
        assertNumQueries, don't use the PyCharm debugger.

        """

        # get the list of environments for this run
        run_env_ids = self.environments.values_list("id", flat=True)

        # make a list of cvs in order by RunSuite, then SuiteCase.
        # This list is built from the run / suite / env combination and has
        # no knowledge of any possibly existing runcaseversions yet.
        if len(run_env_ids):
            cursor = connection.cursor()
            sql = """SELECT DISTINCT cv.id as id
                FROM execution_run as r
                    INNER JOIN execution_runsuite as rs
                        ON rs.run_id = r.id
                    INNER JOIN library_suitecase as sc
                        ON rs.suite_id = sc.suite_id
                    INNER JOIN library_suite as s
                        ON sc.suite_id = s.id
                    INNER JOIN library_caseversion as cv
                        ON cv.case_id = sc.case_id
                        AND cv.productversion_id = r.productversion_id
                    INNER JOIN library_caseversion_environments as cve
                        ON cv.id = cve.caseversion_id
                WHERE cv.status = 'active'
                    AND cv.deleted_on IS NULL
                    AND s.status = 'active'
                    AND rs.run_id = {0}
                    AND cve.environment_id IN ({1})
                ORDER BY rs.order, sc.order
                """.format(self.id, ",".join(map(str, run_env_ids)))
            cursor.execute(sql)

            cv_list = [x[0] for x in cursor.fetchall()]

            # @@@ do we need to check for duplicates?
            # use itertools.unique_everseen
            #if len(set(cv_list)) != len(cv_list):
            #    cv_list = itertools.unique_everseen(cv_list)

        else:
            cv_list = []

        # delete rcvs that we won't be needing anymore
        self._delete_runcaseversions(cv_list)

        # audit for duplicate rcvs for the same cv.id
        dups = self.runcaseversions.values("caseversion_id").annotate(
            num_records=Count("caseversion")).filter(num_records__gt=1)
        if len(dups) > 0:
            for dup in dups:
                # get the runcaseversions, and sort descending by the id
                # of the results.  So the first one is the one with the latest
                # result.  We keep that one and delete the rest.
                rcv_to_save = self.runcaseversions.annotate(
                    latest_result=Max("results__id")).filter(
                        caseversion=dup["caseversion_id"]).order_by(
                            "-latest_result")[0]
                self.runcaseversions.filter(
                    caseversion=dup["caseversion_id"]).exclude(
                        id=rcv_to_save.id).delete()

        # remaining rcvs should be ones we want to keep, and we need to inject
        # those ids into the insert/update list for bulk_insert.  So create
        # a dict mapping cv_id: rcv_id.  If one exists, its order field will
        # be updated in the build_update cmd.
        existing_rcv_map = {}
        for map_item in self.runcaseversions.values("id", "caseversion_id"):
            existing_rcv_map[map_item["caseversion_id"]] = map_item["id"]

        # build the list of rcvs that we DO need.  Be sure to include the ids
        # for rcvs that already exist so that we will just be updating the
        # order and not replacing it.  We will use a special manager that does
        # an update on insert error.

        # runcaseversion objects we will use to bulk create
        rcv_to_update = []
        rcv_proxies_to_create = []

        order = 1
        for cv in cv_list:
            if existing_rcv_map in cv:
                # we will just update the order value
                rcv_to_update.append({"caseversion_id": cv, "order": order})
            else:
                # we need to create a new one
                kwargs = {
                    "run_id": self.id,
                    "caseversion_id": cv,
                    "order": order
                    }
                rcv_proxies_to_create.append(RunCaseVersion(**kwargs))
            order += 1

        # update existing rcvs
        for rcv in rcv_to_update:
            self.runcaseversions.filter(
                caseversion=rcv["caseversion_id"]).update(order=rcv["order"])

        # insert these rcvs in bulk
        self._bulk_insert_new_runcaseversions(rcv_proxies_to_create)

        self._bulk_update_runcaseversion_environments_for_lock()

        self._lock_caseversions_complete()
dataset/ETHPy150Open mozilla/moztrap/moztrap/model/execution/models.py/Run._lock_case_versions/swapped operands of `in`