> From: [email protected] [mailto:[email protected]] > On Behalf Of Michael Bayer > > On Jan 4, 2009, at 7:04 PM, Arn Vollebregt wrote: > > > It is my understanding that when one adds an object instance to a > > session, SQLAlchemy checks for the same object based on it's primary > > key. > > I wouldn't say that's accurate - it only looks at the existing > "identity" assigned to the given instance, based on what already- > loaded database state is present. If you put two brand new Foo() > objects in the session both with "id=1", SQLA wouldn't complain at > all. It lets the database do its job of detecting that constraint, > and the error is an IntegrityError raised by the DBAPI within the > flush.
But isn't the identity comprised of the object class and the primary key? Would that not make the Foo instances the same in the eyes of SQLAlchemy? Or am I perhaps confusing the id variable with the real primary key which is stored somewhere else? > > And if so, is there a way to change this behavior, without querying > > the database? > > SQLA core never chooses to reinvent functionality that's the database > already provides, so you'd have to build something on your end which > hashes all instances in a dictionary based on the desired unique > attributes. I've hopefully made this easy via the attached example > (SQLA 0.5, py2.5). If it works for you we should add it to the wiki's > UsageRecipes section. Oeh yes, that works quite good! You whipped that out quite fast :) Clean code as well! Is this declarative approach the only option, or is that just what you happen to prefer? I am trying to keep my database/SQLAlchemy 'layer' separated from my object declarations in my code, hence the question. Right, next stop for me is writing an add_or_merge() function which tries to add an object to the session, and returns an existing object when a UniqueConstraintException is raised. Sounds like a challenge when relations and association_proxy's come into play :) Thx for the help thus far! Regards, Arn Vollebregt --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en -~----------~----~----~----~------~----~------~--~---
