Search code examples
pythonsqliteflasksqlalchemyalembic

Error while trying to migrate database (slalchemy, slqite3)


I have the next models.py file:

from app import db, bcrypt
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship


class BlogPost(db.Model):

    __tablename__ = "posts"

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String, nullable=False)
    desc = db.Column(db.String, nullable=False)
    author_id = db.Column(db.Integer, ForeignKey('users.id'))

    def __init__(self, title, desc):
        self.title = title
        self.desc = desc

    def __repr__(self):
        return "Titulo >> " + self.title

class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    email = db.Column(db.String, nullable=False)
    password = db.Column(db.String, nullable=False)
    posts = relationship("BlogPost", backref="author")

    def __init__(self, name, email, password):
        self.name = name
        self.email = email
        self.password = password

    def __repr__(self):
        return "Usuario >> ", self.name

Then I ran:

python manage.py db init

and everything was fine, the thing is when I tried to modify my models file to make a migration.. I just change the line:

self.password = password

to:

self.password = bcrypt.generate_password_hash(password)

and when I ran:

python manage.py db migrate

it works, but when I tried to upgrade with:

python manage.py db upgrade

I get the next error:

"No support for ALTER of constraints in SQLite dialect")
NotImplementedError: No support for ALTER of constraints in SQLite dialect

Note: the database just has a few records for testing.. thank you!


Solution

  • Alembic has changed how SQLite migrations are done since most tutorials for Alembic were written. ALTER commands now need to use batch mode. This mode is still compatible with other databases, if you decide to switch from SQLite later.

    For each table being altered, place all operations inside a with op.batch_alter_table('table_name'): block.

    def upgrade():
        with op.batch_alter_table('table_name'):
            op.alter_column(...)