Hi,
I am using the column validator in the SQLAlchemy ( http://stackoverflow.com/questions/2317081/sqlalchemy-maximum-column-length ) but I have one problem which corresponds with the Session.
First of all, I create a table using the declarative base (sqlalchemy.ext.declarative) where InstallValidatorListeners
is the validator class (see above):
Entity = declarative_base()
Entity.__sa_instrumentation_manager__ = InstallValidatorListeners
class Item(Entity):
...
class IRTerm(Entity):
__tablename__ = 'irterm'
id = Column(Integer, Sequence('irterm_id'), primary_key=True, nullable=False)
term = Column(String(M_IRTERM_TERM), index=True, nullable=False)
n = Column(Integer, nullable=False)
item_id = Column(Integer, ForeignKey('items.id'), index=True, nullable=False)
Item.ir_terms = relation(IRTerm, backref='item', cascade="all, delete, delete-orphan")
Then I create an instance of the IRTerm. The term
column has assigned the value which is longer than M_IRTERM_TERM:
doc = Item()
session.add(doc)
try:
i = IRTerm(term=33*'ab', item=doc)
except:
print 'error'
session.commit()
And there is the problem. The IRTerm
creation raises an error which is catched and the program continues. Then the session is commited and the commit()
call raises another error:
sqlalchemy.exc.OperationalError: (OperationalError) (1048, "Column 'term' cannot be null") u'INSERT INTO irterm (term, n, item_id) VALUES (%s, %s, %s)' [None, None, 2145181L]
I suppose that if the instantiation of IRTerm fails nothing is added into the session but by printing the session.new
object I see that the IRTerm instance (the instance has term==None
) is added into a session, because doc
is added into session.
How can I avoid this behavior? Is it possible to cancel the changes on the session if the object Instantiation fails?
Thank you