From: Andrew Brookins Date: Fri, 10 Dec 2021 19:24:51 +0000 (-0800) Subject: Add a note on using server_default=FetchedValue() X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=12caabd587f89c00cb1a922685c636751b955cae;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git Add a note on using server_default=FetchedValue() Add a note on using server_default=FetchedValue() with server-generated `onupdate()` defaults. --- diff --git a/doc/build/orm/persistence_techniques.rst b/doc/build/orm/persistence_techniques.rst index 18bb984cdd..ecd52b3250 100644 --- a/doc/build/orm/persistence_techniques.rst +++ b/doc/build/orm/persistence_techniques.rst @@ -306,6 +306,37 @@ above table will look like: INSERT INTO my_table DEFAULT VALUES RETURNING my_table.id, my_table.timestamp, my_table.special_identifier +Usage with server-generated ``onupdate`` values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you are using the :paramref:`.orm.mapper.eager_defaults` flag on a table +definition with any columns marked with :paramref:`_schema.Column.onupdate` +that use a server-side function to generate the column's value, +you should mark the column with ``server_default=FetchedValue()``. + +Doing so ensures that SQLAlchemy includes these columns in the RETURNING clause +on dialects that support RETURNING. + +This is especially useful for columns that track the "updated" time of a row +using server-side generated timestamps, like the following example: + + class MyModel(Base): + __tablename__ = 'my_table' + + id = Column(Integer, primary_key=True) + created = Column(DateTime(), server_default=func.now()) + + # Use the dialect-appropriate ``now()`` function to generate an updated + # time and include the "updated" column in the RETURNING clause. + updated = Column(DateTime(), onupdate=func.now(), server_default=FetchedValue()) + + __mapper_args__ = {"eager_defaults": True} + +Without ``server_default=FetchedValue()``, SQLAlchemy will make a SELECT after +an INSERT or UPDATE to get the server-generated value for the column even if +the dialect supports RETURNING. + + Case 2: non primary key, RETURNING or equivalent is not supported or not needed --------------------------------------------------------------------------------