Skip to content

version_id_col should accept string attr name like polymorphic_on does, make sure all mapper args that point to a column can work like this #6084

Open

Description

@benpreisler

Describe the bug
The special version_id_col mapper arg doesn't work by assigning the property in __mapper_args__ because it accesses the outer field object instead of the inner Column object when trying to look up the object on the ColumnMapping:

prop = self.mapper._props.get(column)

Expected behavior
The documentation indicates that the version property should be assigned to the version_id_col to enable version checking

To Reproduce

from dataclasses import dataclass
from dataclasses import field

from sqlalchemy import Column, VARCHAR, INTEGER, create_engine
from sqlalchemy.orm import registry, sessionmaker

mapper_registry = registry()
engine = create_engine('MY_URL', echo=True, future=True)
Session = sessionmaker(engine, expire_on_commit=False)


@mapper_registry.mapped
@dataclass
class MyEntity:
    __tablename__ = "my_entity"
    __sa_dataclass_metadata_key__ = "sa"
    my_uuid: str = field(metadata={"sa": Column(VARCHAR(36), primary_key=True)})
    my_version: int = field(metadata={"sa": Column(INTEGER)})
    __mapper_args__ = {"version_id_col": my_version}


my_entity = MyEntity(my_uuid='bef0f282-811f-4125-a3ed-4f4d296e7209', my_version=1)

with Session() as session:
    with session.begin():
        session.add(my_entity)

with Session() as session:
    with session.begin():
        e = session.get(MyEntity, my_entity.my_uuid)
        session.delete(e)

Error

test_file.py:23: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
../../testing_utils/test_file.py:195: in
    session.delete(entity)
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/session.py:936: in __exit__
    self.rollback()
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py:70: in __exit__
    compat.raise_(
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/util/compat.py:198: in raise_
    raise exception
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/session.py:933: in __exit__
    self.commit()
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/session.py:820: in commit
    self._prepare_impl()
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/session.py:799: in _prepare_impl
    self.session.flush()
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/session.py:3224: in flush
    self._flush(objects)
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/session.py:3364: in _flush
    transaction.rollback(_capture_exception=True)
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py:70: in __exit__
    compat.raise_(
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/util/compat.py:198: in raise_
    raise exception
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/session.py:3324: in _flush
    flush_context.execute()
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py:453: in execute
    rec.execute(self)
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py:664: in execute
    util.preloaded.orm_persistence.delete_obj(
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py:323: in delete_obj
    states_to_delete = list(
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py:466: in _organize_states_for_delete
    update_version_id = mapper._get_committed_state_attr_by_column(
../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/mapper.py:2918: in _get_committed_state_attr_by_column
    prop = self._columntoproperty[column]
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
...
column = Field(name='my_version',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x10a7da4c0>,default_factory=<...repr=True,hash=None,compare=True,metadata=mappingproxy({'sa': Column(None, INTEGER(), table=None)}),_field_type=_FIELD)

    def __missing__(self, column):
        prop = self.mapper._props.get(column)
        if prop:
            raise orm_exc.UnmappedColumnError(
                "Column '%s.%s' is not available, due to "
                "conflicting property '%s':%r"
                % (column.table.name, column.name, column.key, prop)
            )
>       raise orm_exc.UnmappedColumnError(
            "No column %s is configured on mapper %s..."
            % (column, self.mapper)
        )
E       sqlalchemy.orm.exc.UnmappedColumnError: No column Field(name='my_version',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x10a7da4c0>,default_factory=<dataclasses._MISSING_TYPE object at 0x10a7da4c0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({'sa': Column(None, INTEGER(), table=None)}),_field_type=_FIELD) is configured on mapper mapped class MyEntity->test_file...

../../../../../../.pyenv/versions/my_proj/lib/python3.8/site-packages/sqlalchemy/orm/mapper.py:3590: UnmappedColumnError

Versions.

  • OS: MacOS Catalina 10.15.7
  • Python: 3.8.6
  • SQLAlchemy: 1.4.1
  • Database: postgres 12
  • DBAPI: psycopg2

Additional context
Workaround:
pull the column out of the field and pass that in
py __mapper_args__ = {"version_id_col": my_version.metadata['sa']}

Have a nice day!

Activity

  1. added
    requires triage
    on Mar 18, 2021
  2. added
    question
    and removed
    requires triage
    on Mar 18, 2021
  3. zzzeek commented on Mar 18, 2021

    @zzzeek
    Member

    hiya -

    I think the workaround is appropriate because here we have dataclasses that are assigning these attributes to "field()" objects; when passing the column to version_id_col, that has to be a Column object.

    what would be more convenient is if "version_id_col" accepted a string , which then resolves to the appropriate column after the mapping has taken place. This would be consistent with how parameters like "polymorphic_on" work, you can send a string name for those too. this issue applies to both of these parameters and maybe some others too I'm not thinking of.

  4. changed the title [-]version_id_col not working as expected on dataclasses[/-] [+]version_id_col should accept string attr name like polymorphic_on does, make sure all mapper args that point to a column can work like this[/+] on Mar 18, 2021
  5. added
    use case
    and removed
    question
    on Mar 18, 2021
  6. added this to the 1.4.x milestone on Mar 18, 2021
  7. added
    fairly easy
    on Mar 18, 2021
  8. benpreisler commented on Mar 18, 2021

    @benpreisler
    Author

    Yeah that sounds good - thanks!

  9. modified the milestones: 1.4.x, 2.x.x on Jul 19, 2022
  10. Anurag-M1 commented on Sep 19, 2026

    @Anurag-M1

    Hi @zzzeek, I have implemented support for string attribute and column names for version_id_col resolving to the mapped ColumnProperty (matching the pattern of polymorphic_on), along with comprehensive tests in test/orm/test_versioning.py and changelog entry. The pull request is prepared at #13596.

    Could a maintainer please add the open for pull requests label to this issue so that #13596 can be reopened? Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    fairly easyormuse case

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions