0

I want to create a new table with my alembic migration file and add 2 records on the table. My upgrade() function

def upgrade():
    op.create_table(
        'new_table',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('text', sa.String(length=180), nullable=False),
        sa.PrimaryKeyConstraint('id', name='pk_new_table'),
        sa.UniqueConstraint('text', name='uq_new_table__text'),
    )

    # Create ad-hoc table as a helper
    new_table = sa.table(
        'new_table',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('text', sa.String(length=180), nullable=False),
        sa.PrimaryKeyConstraint('id', name='pk_new_table'),
        sa.UniqueConstraint('text', name='uq_new_table__text'),
    )
    op.bulk_insert(new_table, [
        {'text': 'First'},
        {'text': 'Second'}
    ])

When running the upgrade through alembic I get the following error

AttributeError: 'PrimaryKeyConstraint' object has no attribute 'key'

This error begins from the line that contains the sa.UniqueConstraint('text', name='uq_new_table__text'), on the SqlAlchemy table. What could be wrong?

Database backend on which the migration is applied is MySQL server.

Apostolos
  • 7,763
  • 17
  • 80
  • 150
  • 1
    You've mixed [`table`](http://docs.sqlalchemy.org/en/latest/core/selectable.html#sqlalchemy.sql.expression.table) and [`Table`](http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Table). The former is a light weight table construct which accepts a name and [`column`](http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.column) arguments (not `Column`) and the latter is the full blown representation of a table in metadata. – Ilja Everilä Mar 14 '17 at 08:15
  • 1
    Thank you. Fixed it since op.create_table returns the a table and can use it in the bulk_insert() method – Apostolos Mar 14 '17 at 08:34
  • Even easier is just removing the primary key constraints and unique constraints from the `sa.table(...)` call. `sa.table` only accepts actual `Column` objects, unlike `op.create_table`, which accepts both `Column`s and constraints. – Connor Brinton Mar 01 '19 at 21:54

0 Answers0