[Sqlalchemy-tickets] Issue #3282: enhance use_alter to be more forgiving, include an "auto" mode (z
Brought to you by:
zzzeek
|
From: Mike B. <iss...@bi...> - 2015-01-01 17:03:30
|
New issue 3282: enhance use_alter to be more forgiving, include an "auto" mode https://bitbucket.org/zzzeek/sqlalchemy/issue/3282/enhance-use_alter-to-be-more-forgiving Mike Bayer: the case of a schema that's been reflected, or otherwise incurs dependencies, is too dependent on simplistic use_alter flags in order to do subsequent schema creates. introduce an "auto" mode that figures this out more naturally at metadata create time, and just knows how to warn/error in the drop case if a name is missing. allow use_alter to be meaningfully changed after the fact as well. ``` #!python from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class A(Base): __tablename__ = 'a' id = Column(Integer, primary_key=True) b_id = Column(ForeignKey('b.id')) bs = relationship("B") class B(Base): __tablename__ = 'b' id = Column(Integer, primary_key=True) a_id = Column(ForeignKey('a.id')) from sqlalchemy.schema import AddConstraint, DropConstraint from sqlalchemy import event for table in Base.metadata.tables.values(): for fkc in table.foreign_keys: # setting this here isn't good enough, because # we do the events as a fixed thing inside of set_parent(). fkc.use_alter = True # we don't actually need a name for the CREATE part, just # the drop. fkc.constraint.name = table.name event.listen(Base.metadata, "after_create", AddConstraint(fkc.constraint)) event.listen(Base.metadata, "before_drop", DropConstraint(fkc.constraint)) e = create_engine("postgresql://scott:tiger@localhost/test", echo=True) #Base.metadata.drop_all(e) Base.metadata.create_all(e) ``` |