Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the length of a Primary Key field in Alembic?

I'm trying to change the length of a Primary Key field from 3 to 6.

Model:

class Server(db.Model):
    country_code = db.Column(db.String(6), primary_key=True)

Migration:

def upgrade():
    op.alter_column('server', 'country_code',
               existing_type=mysql.VARCHAR(length=3),
               type_=sa.String(length=6))

However I'm getting this error message, which I don't quite understand, why it thinks that I'm changing it to null.

_mysql_exceptions.DataError: (1171, 'All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead')

like image 791
Houman Avatar asked Feb 24 '19 16:02

Houman


People also ask

What is op in alembic?

op is a real Python module, populated with individual proxies for each method on Operations , so symbols can be imported safely from the alembic. op namespace.

How do you delete a revision in alembic?

DELETE FROM alembic_version WHERE version_num='3aae6532b560'; INSERT INTO alembic_version VALUES ('3aae6532b560');

What is alembic Version table?

Alembic generates a table in the project table space called alembic_version that keeps track of the unique ID of the last version file applied to the schema. During an update, Alembic uses this stored version ID to determine what if any follow on version files to process.


1 Answers

You need to remove the primary key property of the column before you can change it's datatype.

def upgrade():
    # Drop primary key constraint.
    op.execute('ALTER TABLE user DROP PRIMARY KEY')

    # Change type of the primary key column.
    op.alter_column('server', 'country_code',
                    existing_type=mysql.VARCHAR(length=3),
                    type_=sa.String(length=6))

    # Re-create the primary key constraint.
    op.create_primary_key(None, 'server', ['country_code'])
like image 76
ruohola Avatar answered Oct 13 '22 01:10

ruohola