Wiz
Wiz

Reputation: 4865

SqlAlchemy + Mysql: Unable to drop tables due to IntegrityError

When I try to reinitialize my database, I keep getting an IntegrityError:

sqlalchemy.exc.IntegrityError: (IntegrityError) (1217, 'Cannot delete or update a parent row: a foreign key constraint fails') '\nDROP TABLE users' ()

In my init_db script, I have:

def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = create_engine('...')
    Session.configure(bind=engine)
    session = Session()
    Base.metadata.bind=engine
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)

It would let me drop the Users table, which is:

class User(Base):
    __tablename__='users'
    __table_args__={
        'mysql_engine':'InnoDB',
        'mysql_charset':'utf8',
    }

    user_id = Column(Integer, primary_key=True, unique=True)
    username = Column(VARCHAR(16), primary_key=True, unique=True)
    name = Column(VARCHAR(16))
    password = Column(VARCHAR(20))
    email = Column(VARCHAR(30))
    creation = Column(DateTime, default = datetime.datetime.now)    

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

Upvotes: 3

Views: 2892

Answers (1)

van
van

Reputation: 76952

I see two possible reasons:

  1. Unmapped table: You have another table in the database which has a ForeignKey to the users table, but which is not mapped to any sqlalchemy model and therefore is not dropped during drop_all operation.
  2. Missing ForeignKey mapping: Some relationship is missing in the sqlalchemy model. For example, the addresses table on the DB has a ForeignKey which points to the users table, but your model Address (or to put it properly, the mapper for the Address) does not configure this ForeignKey, and therefore during drop_all sqlalchemy has no way of knowing that this table should be dropped before the referenced one (users).

Upvotes: 7

Related Questions