DarioB
DarioB

Reputation: 1609

Flask Migration: Problem creating table and using existing Enum in database. `create_type=False` Do not work

I am using flask-migrate, SQLAlchemy and alembic to manage my database. I want to create a new table in the database. The new table has a column which uses an existing Enum. I have read on many SO questions that you can use an existing Enum with create_type=False flag. This seems that is not working for me. See upgrade() function in my revision file below.

def upgrade():
    op.create_table(
        'label',
        sa.Column('id', UUID(as_uuid=True), default=uuid4),
        sa.Column('labelText', sa.Text, nullable=False),  
        sa.Column('sourceCountry', sa.Enum('it', 'gb', 'gr', 'bg', 'pt', name='country', create_type=False), nullable=True),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('id')

    )
    op.add_column('entity', sa.Column('labelId', UUID(as_uuid=True)))
    op.create_foreign_key(
        'fk_entity_label',
        'entity', 'label',
        ['labelId'], ['id'],
    )

Here are my versions:

Flask==1.1.1
Flask-Ext==0.1
Flask-Migrate==2.5.3
Flask-Script==2.0.6
Flask-SQLAlchemy==2.4.1
alembic==1.4.1

My error:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DuplicateObject) type "country" already exists

[SQL: CREATE TYPE country AS ENUM ('it', 'gb', 'gr', 'bg', 'pt')]
(Background on this error at: http://sqlalche.me/e/f405)

Upvotes: 3

Views: 1262

Answers (2)

Khine Zar Thwe
Khine Zar Thwe

Reputation: 1

The same error occurs during flask upgrade. By changing the name attribute, it works well.

name = 'country' to name = 'country_name'

OR if you are using Postgres with pgadmin4, remove the 'country' type object and re-run.

Upvotes: 0

DarioB
DarioB

Reputation: 1609

Found the problem. I was using sqlalchemy.Enum(), where I should use postgres.ENUM() instead. Changing that made everything work.

Upvotes: 5

Related Questions