sqlalchemy icon indicating copy to clipboard operation
sqlalchemy copied to clipboard

support dataclass defaults that don't affect subsequent ORM operations

Open CaselIT opened this issue 1 year ago • 32 comments

The use case for this is mainly dataclass defaults, so that we can use mapped_column(default=<new-constrant-here>) and that's equivalent to not setting the field at all.

This should also work for relationships:

Some considerations from other discussions:

i think one area that we have a choice to make is if you have an object with state and you say, myobject.foo = NO_VALUE - does that expire the attribute or just do nothing? I vote for the latter https://github.com/sqlalchemy/sqlalchemy/discussions/12165#discussioncomment-11509551

I guess the behaviour wanted is

thing = session.get(Thing, 1)
assert thing.foo == 'bar'
thing.foo = NO_VALUE
assert thing.foo == 'bar'

and if foo is expired it stays expired, so

thing = session.get(Thing, 1)
session.expire(thing, 'foo')
assert 'foo' in sa.inspect(x).expired_attributes
thing.foo = NO_VALUE
assert 'foo' in sa.inspect(x).expired_attributes

In the above example either behaviour is fine. Not sure if before assert thing.foo == 'bar' in the first example 'foo' should be in the expired_attributes or not. I trust your insight here if you prefer for not. https://github.com/sqlalchemy/sqlalchemy/discussions/12165#discussioncomment-11510441

Connected discussions:

  • https://github.com/sqlalchemy/sqlalchemy/discussions/12165
  • https://github.com/sqlalchemy/sqlalchemy/discussions/9383
  • https://github.com/sqlalchemy/sqlalchemy/discussions/9856

Target is 2.0.x but may be moved to 2.1 depending on the changes

CaselIT avatar Dec 09 '24 18:12 CaselIT

I prefer UNSET compared with NO_VALUE as a word, but overall they mean probably the same thing

CaselIT avatar Dec 09 '24 20:12 CaselIT

myobject.foo = NO_VALUE - does that expire the attribute or just do nothing

Another case:

thing = session.get(Thing, 1)
assert thing.foo == 'bar'
thing.foo = 'new-value'
thing.foo = NO_VALUE
# assert thing.foo == 'bar' # this would again pass
session.commit()  # nothing to do here. No update is done, new-value is lost

Here I think the correct behaviour would be to ignore the set of new-value, so I would go for expire, since I'm not sure if it can be done without expiring the field. If we can do that that I'm back ad no preference

CaselIT avatar Dec 09 '24 20:12 CaselIT

as mentioned elsewhere there's not a great way to type this

if you say

field: Mapped[str | None] = mapped_column(default=DONTSET)

That's going to fail typing, would have to be like

field: Mapped[str | None | DontSetType] = mapped_column(default=DONTSET)

unless if we typed DONTSET as None .....

zzzeek avatar Dec 09 '24 22:12 zzzeek

so that typing looks like:

if TYPE_CHECKING:
    DONTSET = None
else:
    DONTSET = object()

class UserMappedModel(MappedAsDataclass, Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default=DONTSET)

we also have a way to customize that default "scalar get" value which is little used : https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.AttributeEvents.init_scalar

to use that, someone would need to make another DONTSET of their own, like:

if TYPE_CHECKING:
    DONTSET_MY_DEFAULT = "default"
else:
    DONTSET_MY_DEFAULT = DONTSET

class UserMappedModel(MappedAsDataclass, Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str] = mapped_column(default=DONTSET_MY_DEFAULT)

zzzeek avatar Dec 09 '24 22:12 zzzeek

maybe we have a bunch of them canned for typical defaults

if TYPE_CHECKING:
    DONTSET_NONE = None
    DONTSET_STR = "string"
    DONTSET_INT = 0
    # ... etc

else:
    _DONTSET = object()
    DONTSET_NONE = _DONTSET
    DONTSET_STR = _DONTSET
    DONTSET_INT = _DONTSET
    # ...

zzzeek avatar Dec 09 '24 22:12 zzzeek

this does the basic thing

diff --git a/lib/sqlalchemy/orm/attributes.py b/lib/sqlalchemy/orm/attributes.py
index d65597238..9c47d9553 100644
--- a/lib/sqlalchemy/orm/attributes.py
+++ b/lib/sqlalchemy/orm/attributes.py
@@ -45,6 +45,7 @@ from .base import ATTR_EMPTY
 from .base import ATTR_WAS_SET
 from .base import CALLABLES_OK
 from .base import DEFERRED_HISTORY_LOAD
+from .base import DONT_SET
 from .base import INCLUDE_PENDING_MUTATIONS  # noqa
 from .base import INIT_OK
 from .base import instance_dict as instance_dict
@@ -1268,6 +1269,9 @@ class _ScalarAttributeImpl(_AttributeImpl):
         check_old: Optional[object] = None,
         pop: bool = False,
     ) -> None:
+        if value is DONT_SET:
+            return
+
         if self.dispatch._active_history:
             old = self.get(state, dict_, PASSIVE_RETURN_NO_VALUE)
         else:
@@ -1434,6 +1438,9 @@ class _ScalarObjectAttributeImpl(_ScalarAttributeImpl):
     ) -> None:
         """Set a value on the given InstanceState."""
 
+        if value is DONT_SET:
+            return
+
         if self.dispatch._active_history:
             old = self.get(
                 state,
diff --git a/lib/sqlalchemy/orm/base.py b/lib/sqlalchemy/orm/base.py
index b5f7dbbaf..948ed0bed 100644
--- a/lib/sqlalchemy/orm/base.py
+++ b/lib/sqlalchemy/orm/base.py
@@ -97,6 +97,7 @@ class LoaderCallableStatus(Enum):
 
     """
 
+    DONT_SET = 5
 
 (
     PASSIVE_NO_RESULT,
@@ -104,6 +105,7 @@ class LoaderCallableStatus(Enum):
     ATTR_WAS_SET,
     ATTR_EMPTY,
     NO_VALUE,
+    DONT_SET,
 ) = tuple(LoaderCallableStatus)
 
 NEVER_SET = NO_VALUE

demo

from __future__ import annotations

from sqlalchemy import create_engine
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session, MappedAsDataclass
from sqlalchemy.orm.attributes import DONT_SET
from typing import TYPE_CHECKING

class Base(DeclarativeBase):
    pass

if TYPE_CHECKING:
    DONTSET_NONE = None

else:
    DONTSET_NONE = DONT_SET

class UserMappedModel(MappedAsDataclass, Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default=DONTSET_NONE)

e = create_engine("sqlite://")
Base.metadata.create_all(e)

session = Session(e)

user = UserMappedModel(id=1, name="Jon", status="active")
session.merge(user)
session.commit()


user = UserMappedModel(id=1, name="John")
assert user.status is None
new_user = session.merge(user)
session.commit()

print(new_user)

there can be the possibility of doing more with the init_scalar event and having this None be more customizable

zzzeek avatar Dec 09 '24 23:12 zzzeek

as mentioned elsewhere there's not a great way to type this

We can just type this as Any. That eliminates any typing issue

CaselIT avatar Dec 09 '24 23:12 CaselIT

@n-leonovets I can see doing the above pattern, integrating init_scalar, and having the two flags such as:

class UserMappedModel(MappedAsDataclass, Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default=None, stealth_default=True)

what it means is that making a UserMappedModel will not actually populate None into __dict__ if not passed, that is, it still is using DONT_SET above, you just dont see it.

stealth_default could set up an event to support other kinds of defaults too other than None, this is what init_scalar supports

here is that

from __future__ import annotations

from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session, MappedAsDataclass
from sqlalchemy.orm.attributes import DONT_SET
from typing import TYPE_CHECKING

class Base(DeclarativeBase):
    pass


class UserMappedModel(MappedAsDataclass, Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]

    if TYPE_CHECKING:
        # what the API would be
        status: Mapped[str] = mapped_column(default="default_status", stealth_default=True)
    else:
        # what actually happens, part I
        status: Mapped[str] = mapped_column(default=DONT_SET)

# what actually happens, part II
@event.listens_for(UserMappedModel.status, "init_scalar", retval=True)
def receive_init_scalar(target, value, dict_):
    return "default_status"

e = create_engine("sqlite://")
Base.metadata.create_all(e)

session = Session(e)

user = UserMappedModel(id=1, name="Jon", status="active")
session.merge(user)
session.commit()


user = UserMappedModel(id=1, name="John")
assert user.status == "default_status"

new_user = session.merge(user)
session.commit()

print(new_user)

zzzeek avatar Dec 09 '24 23:12 zzzeek

I'm -1 on doing that under the hood, but that new argument may make sense to add. But I think it's better to just pass to it the value while keeping default as is.

So something like mapped_column(default=UNSET, new_argument="default_status")

CaselIT avatar Dec 09 '24 23:12 CaselIT

@n-leonovets Я могу представить себе выполнение вышеуказанного шаблона, интеграцию init_scalarи наличие двух флагов, например:

class UserMappedModel(MappedAsDataclass, Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default=None, stealth_default=True)

это означает, что создание UserMappedModelволи фактически не заполнит Noneполе __dict__if not passed, то есть оно все равно используется DONT_SETвыше, вы просто его не видите.

stealth_default может настроить событие для поддержки других типов значений по умолчанию None, кроме того, что поддерживает init_scalar

вот это

from __future__ import annotations

from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session, MappedAsDataclass
from sqlalchemy.orm.attributes import DONT_SET
from typing import TYPE_CHECKING

class Base(DeclarativeBase):
    pass


class UserMappedModel(MappedAsDataclass, Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]

    if TYPE_CHECKING:
        # what the API would be
        status: Mapped[str] = mapped_column(default="default_status", stealth_default=True)
    else:
        # what actually happens, part I
        status: Mapped[str] = mapped_column(default=DONT_SET)

# what actually happens, part II
@event.listens_for(UserMappedModel.status, "init_scalar", retval=True)
def receive_init_scalar(target, value, dict_):
    return "default_status"

e = create_engine("sqlite://")
Base.metadata.create_all(e)

session = Session(e)

user = UserMappedModel(id=1, name="Jon", status="active")
session.merge(user)
session.commit()


user = UserMappedModel(id=1, name="John")
assert user.status == "default_status"

new_user = session.merge(user)
session.commit()

print(new_user)

looks a little strange and not obvious. I think it's worth striving for standard model behavior, regardless of whether MappedAsDataclass is used or not.

adding event.listens_for is not obvious and different behavior from the base model.

It seems to me that it is worth finalizing this proposed solution https://github.com/sqlalchemy/sqlalchemy/discussions/12165#discussioncomment-11513942, because... it is more obvious and can be hidden in alchemy so that users do not have to learn a new approach to alchemy, which is already not obvious in many places

nleononline avatar Dec 10 '24 00:12 nleononline

Please view my comments carefully, I am proposing this line for public API

status: Mapped[str] = mapped_column(default="default_status", stealth_default=True)

zzzeek avatar Dec 10 '24 00:12 zzzeek

Я -1 за то, чтобы делать это под капотом, но этот новый аргумент, возможно, имеет смысл добавить. Но я думаю, что лучше просто передать ему значение, оставив значение по умолчанию как есть.

Итак, что-то вродеmapped_column(default=UNSET, new_argument="default_status")

it looks interesting and simple. If new_argument is what we get in the object, but when working with session it will be ignored - this is not a bad option.

The only thing that might be worth moving this to default and adding a more obvious setting, for example exclude_default or exclude_defalut_for_session...

nleononline avatar Dec 10 '24 00:12 nleononline

there's no "exclude_default_for_session" type thing going on here, this remains very simple, that the object value is left omitted from __dict__ entirely, which implies that there's no value present for an INSERT statement or similar operation, that's it

zzzeek avatar Dec 10 '24 00:12 zzzeek

Пожалуйста, внимательно просмотрите мои комментарии, я предлагаю эту строку для публичного API.

status: Mapped[str] = mapped_column(default="default_status", stealth_default=True)
event

I haven’t worked with event (and few people have), so I have no thoughts about such an example.

nleononline avatar Dec 10 '24 00:12 nleononline

while the event system in general is widely used, the particular "event" shown here is part of the demonstration of the internal implementation, as I tried to indicate above

zzzeek avatar Dec 10 '24 00:12 zzzeek

Хотя система событий в целом широко используется, конкретное «событие», показанное здесь, является частью демонстрации внутренней реализации, как я пытался показать выше.

It seems to me that solving this problem through event is not the best idea (this is NOT obvious). It's better then:

status: Mapped[str] = mapped_column(default=UNSET, dataclass_argument="ACTIVE")

as suggested here: https://github.com/sqlalchemy/sqlalchemy/issues/12168#issuecomment-2529777870

But I still think there should be a slightly better solution.

nleononline avatar Dec 10 '24 00:12 nleononline

It seems to me that this is the most adequate way.

There is a simple Default type that you can wrap a value in. We can call self.is_default and if we get True, do not add the value to session methods.

DefaultArg = TypeVar("DefaultArg")


class Default(Generic[DefaultArg]):
    def __init__(self, value: DefaultArg):
        self.value = value

    def __repr__(self) -> DefaultArg:
        return f"{self.value}"

    def unwrap(self) -> DefaultArg:
        return self.value


class Base(DeclarativeBase):

    def __getattribute__(self, name: str):
        value = super().__getattribute__(name)
        if isinstance(value, Default):
            return value.unwrap()
        return value

    def is_default(self, name: str) -> bool:
        value = super().__getattribute__(name)
        return isinstance(value, Default)


class User(Base, MappedAsDataclass, kw_only=True):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default=Default("ACTIVE"))
    is_paid: Mapped[bool] = mapped_column(default=Default(False))


user = User(id=1, name="John")

print(user.status)
> ACTIVE
print(type(user.status)
> <class 'str'>
print(isinstance(user.status, str))
> True
print(user.is_default("status"))
> True

The advantage is that we can hide this construction in the library implementation and get the same behavior for standard values ​​in regular models and MappedAsDataclass, fixing the original problem https://github.com/sqlalchemy/sqlalchemy/discussions/12165

As a result, the code will not be different, are you using a regular model or MappedAsDataclass:

class User(Base, MappedAsDataclass, kw_only=True):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str | None] = mapped_column(default="ACTIVE")  << Default("ACTIVE")
    is_paid: Mapped[bool] = mapped_column(default=False)  << Default(False)

Also, using this approach, we can add an exclude_default or exclude_unset method to the mapped_column and allow users to choose whether they want to exclude the default value or not.

class User(Base, MappedAsDataclass, kw_only=True):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    status: Mapped[str] = mapped_column(default="ACTIVE", exclude_unset=False)
    is_paid: Mapped[bool] = mapped_column(default=False, exclude_unset=True)

By updating the user, we obviously understand that he is active, but in order not to explicitly indicate his status each time, we will simply specify exclude_unset=False and rely on the default value.

nleononline avatar Dec 10 '24 01:12 nleononline

@n-leonovets your proposal is not compatible with how dataclasses is type checked so I -1 on implementing it like that. Also it doesn't solve the issue without changing every place where sqlalchemy getts the value for an attribute.

Any imoalmentation that replies on a container object has the same problem

CaselIT avatar Dec 10 '24 06:12 CaselIT

So mike to recap you don't want to only provide an unset but also a way of changing the init scalar value provided by the instrumented attribute with a parameter in the column definition?

CaselIT avatar Dec 10 '24 07:12 CaselIT

@n-leonovets Sorry I saw a double comment and removed one, but I guess you removed the other one

CaselIT avatar Dec 10 '24 07:12 CaselIT