Skip to content

Bug: update causing IntegrityError #535

Closed

Description

@Harshal6927

Description

With release of version 1.5.0, the update method only works with Python dictionaries.
Passing any other data type defined in ModelDictT will result in an IntegrityError.

Example below works with Advanced Alchemy version <= 1.4.5

URL to code causing the issue

No response

MCVE

from advanced_alchemy.base import BigIntBase
from advanced_alchemy.repository import SQLAlchemySyncRepository
from advanced_alchemy.service import SQLAlchemySyncRepositoryService
from msgspec import UNSET, Struct, UnsetType
from sqlalchemy import create_engine
from sqlalchemy.orm import Mapped, Session


# Model
class Item(BigIntBase):
    name: Mapped[str]
    description: Mapped[str]


# Schemas
class ItemCreate(Struct):
    name: str
    description: str


class ItemUpdate(Struct):
    name: str | UnsetType = UNSET
    description: str | UnsetType = UNSET


class ItemRead(Struct):
    id: int
    name: str
    description: str


class ItemService(SQLAlchemySyncRepositoryService[Item]):
    class ItemRepo(SQLAlchemySyncRepository[Item]):
        model_type = Item

    repository_type = ItemRepo


engine = create_engine("sqlite:///:memory:")
Item.metadata.create_all(engine)

with Session(engine, expire_on_commit=False, autoflush=False) as session, ItemService.new(session) as service:
    # Create
    item_in_db = service.create(ItemCreate(name="One", description="1 item"))
    session.commit()

    item = service.to_schema(item_in_db, schema_type=ItemRead)
    print(f"Created item: {item}")

    # Update
    item_in_db = service.update(item_id=item.id, data=ItemUpdate(name="Updated name one"))
    session.commit()

    item = service.to_schema(item_in_db, schema_type=ItemRead)
    print(f"Updated item: {item}")

Logs

With 1.5.0

❯ /home/harshal/projects/byte-bond/.venv/bin/python /home/harshal/projects/byte-bond/.idea/test.py
cd /home/harshal/projects/byte-bond/.idea
Created item: ItemRead(id=1, name='One', description='1 item')
Traceback (most recent call last):
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1967, in _exec_single_context
    self.dialect.do_execute(
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 951, in do_execute
    cursor.execute(statement, parameters)
sqlite3.IntegrityError: NOT NULL constraint failed: item.description

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/advanced_alchemy/exceptions.py", line 286, in wrap_sqlalchemy_exception
    yield
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/advanced_alchemy/repository/_sync.py", line 1525, in update
    self._flush_or_commit(auto_commit=auto_commit)
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/advanced_alchemy/repository/_sync.py", line 1689, in _flush_or_commit
    return self.session.commit() if auto_commit else self.session.flush()
                                                     ^^^^^^^^^^^^^^^^^^^^
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 4345, in flush
    self._flush(objects)
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 4480, in _flush
    with util.safe_reraise():
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py", line 224, in __exit__
    raise exc_value.with_traceback(exc_tb)
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 4441, in _flush
    flush_context.execute()
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py", line 466, in execute
    rec.execute(self)
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/orm/unitofwork.py", line 642, in execute
    util.preloaded.orm_persistence.save_obj(
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py", line 85, in save_obj
    _emit_update_statements(
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/orm/persistence.py", line 912, in _emit_update_statements
    c = connection.execute(
        ^^^^^^^^^^^^^^^^^^^
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1419, in execute
    return meth(
           ^^^^^
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 526, in _execute_on_connection
    return connection._execute_clauseelement(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1641, in _execute_clauseelement
    ret = self._execute_context(
          ^^^^^^^^^^^^^^^^^^^^^^
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1846, in _execute_context
    return self._exec_single_context(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1986, in _exec_single_context
    self._handle_dbapi_exception(
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 2355, in _handle_dbapi_exception
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1967, in _exec_single_context
    self.dialect.do_execute(
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 951, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: item.description
[SQL: UPDATE item SET name=?, description=? WHERE item.id = ?]
[parameters: ('Updated name one', None, 1)]
(Background on this error at: https://sqlalche.me/e/20/gkpj)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/harshal/projects/byte-bond/.idea/test.py", line 51, in <module>
    item_in_db = service.update(item_id=item.id, data=ItemUpdate(name="Updated name one"))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/advanced_alchemy/service/_sync.py", line 760, in update
    self.repository.update(
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/advanced_alchemy/repository/_sync.py", line 1479, in update
    with wrap_sqlalchemy_exception(
  File "/usr/lib/python3.12/contextlib.py", line 158, in __exit__
    self.gen.throw(value)
  File "/home/harshal/projects/byte-bond/.venv/lib/python3.12/site-packages/advanced_alchemy/exceptions.py", line 321, in wrap_sqlalchemy_exception
    raise IntegrityError(
advanced_alchemy.exceptions.IntegrityError: There was a data validation error during processing

With 1.4.5

❯ /home/harshal/projects/byte-bond/.venv/bin/python /home/harshal/projects/byte-bond/.idea/test.py
Created item: ItemRead(id=1, name='One', description='1 item')
Updated item: ItemRead(id=1, name='Updated name one', description='1 item')

Package Version

1.5.0+

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Activity

  1. yuuuxt commented on Sep 1, 2025

    @yuuuxt
    Contributor

    I'm seeing updated_at is not updated when updating using BigIntAuditBase and sqlite after upgrading to 1.5.0, which works on 1.4.5. (Haven't got time to investigate further)

  2. Harshal6927 commented on Sep 1, 2025

    @Harshal6927
    MemberAuthor
  3. yuuuxt commented on Sep 16, 2025

    @yuuuxt
    Contributor

    Is releasing a new version to fix this and "removing" versions from 1.5.0 to 1.6.2 a good idea?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions