def _organize_states_for_save(base_mapper, states, uowtransaction):

    for state, dict_, mapper, connection in _connections_for_states(
            base_mapper, uowtransaction,
            states):

        has_identity = bool(state.key)

        instance_key = state.key or mapper._identity_key_from_state(state)

        row_switch = update_version_id = None

        # call before_XXX extensions
        if not has_identity:
            mapper.dispatch.before_insert(mapper, connection, state)
        else:
            mapper.dispatch.before_update(mapper, connection, state)

        if mapper._validate_polymorphic_identity:
            mapper._validate_polymorphic_identity(mapper, state, dict_)

        # detect if we have a "pending" instance (i.e. has
        # no instance_key attached to it), and another instance
        # with the same identity key already exists as persistent.
        # convert to an UPDATE if so.
        if not has_identity and \
                instance_key in uowtransaction.session.identity_map:
            instance = \
                uowtransaction.session.identity_map[instance_key]
            existing = attributes.instance_state(instance)

            if not uowtransaction.was_already_deleted(existing):
                if not uowtransaction.is_deleted(existing):
                    raise orm_exc.FlushError(
                        "New instance %s with identity key %s conflicts "
                        "with persistent instance %s" %
                        (state_str(state), instance_key,
                         state_str(existing)))

                base_mapper._log_debug(
                    "detected row switch for identity %s.  "
                    "will update %s, remove %s from "
                    "transaction", instance_key,
                    state_str(state), state_str(existing))

                # remove the "delete" flag from the existing element
                uowtransaction.remove_state_actions(existing)
                row_switch = existing

        if (has_identity or row_switch) and mapper.version_id_col is not None:
            update_version_id = mapper._get_committed_state_attr_by_column(
                row_switch if row_switch else state,
                row_switch.dict if row_switch else dict_,
                mapper.version_id_col)

        yield (state, dict_, mapper, connection,
               has_identity, row_switch, update_version_id)
Make an initial pass across a set of states for INSERT or
dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/orm/persistence.py/_organize_states_for_save