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

Open
#323 11 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python, sqlalchemy
Domain
database

Research direction

Start by running the supplied test_insert_row_autogenerate with the fix_session and databricks_engine fixture, then trace the insert and flush behavior that produces the NULL identity key. Done means the sample row inserts successfully and the autogenerated bigint identity is available when the row is queried.

Written by the indexing model from the issue text.

Description

sqlalchemy

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
Dominant language
Python
Stars
233
Forks
152
Avg merge
21h 5m
Merged PRs (30d)
10

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from databricks/databricks-sql-python

All issues in databricks/databricks-sql-python

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.