Modify FlushError description to take account of possible missing auto_increment setting

Issue #2170 resolved
Former user created an issue

Hi,

received FlushError today after performing: Session.add(obj), Session.commit():

"FlushError: Instance <MyInstance at 0xxxxxx> has a NULL identity key. Check if this flush is occurring at an inappropriate time, such as during a load operation."

Using SQLA 0.6.7 with Declarative ext, my SQLA model had a single PK Column: Integer, primary_key=True, autoincrement=True

As it turned out, I was missing auto_increment setting on my (MySQL) table (created by hand) which prompted this sanity check as there was no last_insert_id()

I suggest adding a more robust description to the error, listing missing auto increment setting as one of the possiblities for this error.

Regards.

Comments (4)

  1. Mike Bayer repo owner

    Here is another case...need to add "no autoincrementing primary keys present" or something like that

    from sqlalchemy import *
    from sqlalchemy.orm import *
    
    class Parent(object) :
       def __init__(self, name) :
           self.name = name
    
    class Child(object) :
       def __init__(self, name) :
           self.name = name
    
    engine = create_engine("sqlite:///", echo=True)
    metadata = MetaData(engine)
    
    prn_tab = Table("parent", metadata,
           Column('id', Integer, primary_key=True),
           Column('name', String))
    prn_tab.create()
    chl_tab = Table("child", metadata,
           Column('id', Integer, primary_key=True),
           Column('name', String))
    chl_tab.create()
    
    fck = ForeignKeyConstraint
    chl_tab.append_constraint(fck([chl_tab.c.id](chl_tab.c.id), [prn_tab.c.id](prn_tab.c.id)))
    
    mapper(Parent, prn_tab)
    mapper(Child, chl_tab)
    
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()
    session.add(Child("Carl"))
    session.commit()
    

    will consider an 0.6.8 backport once I decide how big a change we're going to do here.

  2. Mike Bayer repo owner

    Instance X has a NULL identity key. If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the SQLAlchemy mapped Table and Column object is configured to expect these generated values. Ensure also that this flush() is not occurring at an inappropriate time, such as within a load() event.

  3. Log in to comment