I have a typical case where I want to ensure that datetime values sent to the database are UTC, and values read from the database come back as offset-aware UTC times. I see several threads on the issue (eg: http://goo.gl/FmdIJ is most relevant), but none address my question that I can see. UTC datetimes are what I'm working with, but not really what the question is about (although hopefully the code may help others looking for UTC stuff!).
I originally tried implementing this with a custom type (UTCDateTime) where I did appropriate conversions on the data to/from the database. That used code something like this: http://pastebin.com/xSrV9QcS That implementation worked well when creating new objects and committing them, and worked well when querying for existing objects. However, it failed when committing objects that I updated (query->make a change->commit). This is because the UTC conversion only happens on commit, and some SQLAlchemy internals were doing a comparison on the new value (naive datetime) and the old value (offset-aware datetime from DB) and raising an exception. When I realized that process_bind_param only happens on commit, I decided to switch my strategy to simply confirming that all incoming outgoing datetime values are offset-aware UTC using this simpler code: http://pastebin.com/gLfCUkX3 but in order for that to work, I also needed to and start looking into how to implement a setter on all of my datetime properties (there are lots) that would do the UTC assignment/calculation. I use declarative mixins which seemed to make this more complicated, but a setter can be set up using a solution something like this: http://stackoverflow.com/questions/5821947/5822301#5822301 However, I have a LOT of properties to do this on and it would be far better to do it at a single choke point like I initially tried. So... what I want is all assignments to a UTCEnforcedDateTime column/ property (self.start_date = x) to be converted to UTC at setting time, not at commit time. How do I do this? I can't see how to do it in the docs (coerce_compared_value was initially tempting but not a fit)/ Digging into it manually I see that the existing auto-instrumentation of my UTCEnforcedDateTime dips through InstrumentedAttribute, ScalarAttributeImp, etc, but I can't locate a good hook point to put my "fixing" code for non-UTC assignments. Does anyone have any recommendations? -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.