databricks-sql-python icon indicating copy to clipboard operation
databricks-sql-python copied to clipboard

[sqlalchemy] Exception: Instance %s has a NULL identity key

Open wibbico opened this issue 1 year ago • 9 comments

I cant get autogenerated identity columns to work.

The table is created just fine, but sqlalchelmy cant insert any rows

Error:

sqlalchemy.orm.exc.FlushError: Instance <SampleObject at 0x7fc694ddbd90> 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 mapped 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.

Sample code:


from sqlalchemy import create_engine, text, Column, BigInteger, String, Identity
from sqlalchemy.orm import Session, DeclarativeBase

from sample import databricks_engine


@pytest.fixture()
def fix_session():
    engine = databricks_engine()
    try:
        with Session(engine) as session:
            Base.metadata.create_all(engine)
            yield session
    finally:
        with Session(engine) as session:
            rollback_query_kopf = text("DROP TABLE dummy")
            session.execute(rollback_query_kopf)
            session.commit()

class Base(DeclarativeBase):
    pass

class SampleObject(Base):
    __tablename__ = "dummy"

    bigint_col = Column(
        BigInteger, primary_key=True, server_default=Identity(), autoincrement="auto"
    )
    str_col = Column(String)

def test_insert_row_autogenerate(fix_session):
    sample = SampleObject(str_col="test")
    fix_session.add(sample)
    fix_session.commit()

    actual = fix_session.query(SampleObject).first()

    assert actual

wibbico avatar Jan 22 '24 09:01 wibbico

PING for review - @mrt @marmbrus @ahirreddy @holdenk

chetkhatri avatar Aug 31 '20 01:08 chetkhatri