Skip to content

Commit

Permalink
fix(#144): ensure enum-types have unique names
Browse files Browse the repository at this point in the history
  • Loading branch information
dtonder committed Sep 4, 2024
1 parent 5f1e098 commit 24cb0da
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 5 additions & 1 deletion sqlalchemy_history/table_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"""
import sqlalchemy as sa

from sqlalchemy.sql.sqltypes import Enum


class ColumnReflector(object):
def __init__(self, manager, parent_table, model=None):
Expand All @@ -19,7 +21,7 @@ def reflect_column(self, column):
"""Make a copy of parent table column and some alterations to it.
:param column: SQLAlchemy Column object of parent table
`
"""
# Make a copy of the column so that it does not point to wrong table.
column_copy = column._copy()
Expand All @@ -31,6 +33,8 @@ def reflect_column(self, column):
column_copy.autoincrement = False
if column_copy.name == self.option("transaction_column_name"):
column_copy.nullable = False
if isinstance(column_copy.type, Enum):
column_copy.type.name = 'history_' + column_copy.type.name

if not column_copy.primary_key:
column_copy.nullable = True
Expand Down
24 changes: 24 additions & 0 deletions tests/builders/test_table_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ class Article(self.Model):
last_update = sa.Column(
sa.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
enum_col = sa.Column(
sa.Enum('TYPE_A', 'TYPE_B', name='test_enum')
)

self.Article = Article

Expand Down Expand Up @@ -124,3 +127,24 @@ def test_created_tables_retain_schema(self):
table = version_class(self.Article).__table__
assert table.schema is not None
assert table.schema == self.Article.__table__.schema


class TestEnumNaming(TestCase):
def create_models(self):
class Article(self.Model):
__tablename__ = "article"
__versioned__ = copy(self.options)

id = sa.Column(
sa.Integer, sa.Sequence(f"{__tablename__}_seq", start=1), autoincrement=True, primary_key=True
)

enum_col = sa.Column(
sa.Enum('TYPE_A', 'TYPE_B', name='test_enum')
)

self.Article = Article

def test_name_enums(self):
version_model = version_class(self.Article)
assert version_model.enum_col.type.name == 'history_test_enum'

0 comments on commit 24cb0da

Please sign in to comment.