使用Flask-Migration将SACKite3表中的UniqueKey约束添加失败并显示IntrgrityError

问题描述 投票:0回答:1

所以我使用sqlite作为我的测试数据库,并在我的models.py中有以下类

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, index=True)
    username = db.Column(db.String(40), unique=True, index=True)
    password_hash = db.Column(db.String(256))
    alternate_id = db.Column(db.String(100))
    posts = db.relationship('Posts', backref='author', lazy=True)

    def get_id(self):
        return str(self.alternate_id)

    def __init__(self, username, password):
        self.username = username
        self.password_hash = generate_password_hash(password)
        self.alternate_id = my_serializer.dumps(
            self.username + self.password_hash)

    def verify_password(self, password):
        if check_password_hash(self.password_hash, password):
            return "True"


class Posts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False, unique=True)
    description = db.Column(db.String(1500))
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    def __init__(self, title, description, author_id):
        self.title = title
        self.description = description
        self.author_id = author_id

我在unique类中将title键约束添加到列Posts,然后尝试使用Flask-Migrate更新模式。

最初我得到No support for ALTER of constraints in SQLite dialect错误,因为sqlite3不通过alembic支持它。所以我查看了alembic文档,发现您实际上可以使用batch模式迁移进行此类迁移。所以我更新了我的迁移脚本,如下所示。

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("posts") as batch_op:
        batch_op.create_unique_constraint('unique_title', ['title'])
    # ### end Alembic commands ###

现在,当我尝试运行flask db upgrade时,我收到以下错误

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: _alembic_tmp_posts.title [SQL: 'INSERT INTO
_alembic_tmp_posts (id, title, description, author_id) SELECT posts.id, posts.title, posts.description, posts.author_id \nFROM posts'] (Background on this error at: http://sqlalche.me/e/gkpj`)

我无法理解为什么抛出IntegrityError异常,因为如果我查看insert语句,列数是相同的。

是否与authors_id列有foreignkey约束有关?

sqlite flask alembic flask-migrate
1个回答
0
投票

我在其中添加unique约束的数据库表列具有重复数据,这就是我得到完整性错误的原因,我很惊讶为什么我之前没有注意到。

因此,一旦我删除了其中一个重复行,数据库升级就成功了。

© www.soinside.com 2019 - 2024. All rights reserved.