我有非常简单的代码导致我的 MySQL 数据库挂起:
import sqlalchemy as sa
from sqlalchemy import orm
# creating the engine, the base, etc
import utils
import config
utils.base_init(config)
Base = config.Base
class Parent(Base):
__tablename__ = 'Parents'
id = sa.Column(sa.Integer, primary_key=True)
children = orm.relationship('Child', backref='parent')
class Child(Base):
id = sa.Column(sa.Integer, primary_key=True)
parent_id = sa.Column(sa.Integer)
__tablename__ = 'Children'
__table_args__ = (sa.ForeignKeyConstraint(
['parent_id'],
['Parents.id'],
onupdate='CASCADE', ondelete='CASCADE'),{})
Base.metadata.create_all()
session = orm.sessionmaker(bind=config.Base.metadata.bind)()
p = Parent(id=1)
c1 = Child(id=1)
c2 = Child(id=2)
session.add(p)
session.add(c1)
session.add(c2)
session.commit()
# Works
# Base.metadata.drop_all()
c1.parent
# 2012-08-17 20:16:21,459 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
# 2012-08-17 20:16:21,460 INFO sqlalchemy.engine.base.Engine SELECT `Children`.id AS `Children_id`, `Children`.parent_id AS `Children_parent_id`
# FROM `Children`
# WHERE `Children`.id = %s
# 2012-08-17 20:16:21,460 INFO sqlalchemy.engine.base.Engine (1,)
Base.metadata.drop_all()
# hangs until i kill the connection above.
# server status: 'Waiting for table metadata lock'
看起来 SQL Alchemy 在发出加载关系属性所需的选择查询后没有释放元数据锁?我怎样才能让它释放它?我什至不明白为什么选择语句首先需要锁定表!
当然,我可以通过关闭会话来让这段特定的代码工作,但这在我的实际程序中并不实用。