Skip to content

Instantly share code, notes, and snippets.

@exhuma
Created March 5, 2020 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save exhuma/d3b521e93471e0816029ebfe33a9edb1 to your computer and use it in GitHub Desktop.
Save exhuma/d3b521e93471e0816029ebfe33a9edb1 to your computer and use it in GitHub Desktop.
SQLAlchemy demonstration of the "FetchedValue" feature
"""
This file demonstrated using the "FetchedValue" feature of SQLAlchemy for
values which are generated by the DB, without knowing *how* they are generated
in the DB.
"""
from sqlalchemy import Column, DateTime, FetchedValue, Unicode, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Foo(Base):
__tablename__ = "foo"
# mapper-args are necessary to tell SA to use the "RETURNING" statements.
# Note that this will cause overhead on DBs which don't support "RETURNING"
__mapper_args__ = {"eager_defaults": True}
name = Column(Unicode, primary_key=True)
# Assuming the server assigns a value by default, using "FetchedValue"
# marks this column as a column that should be added in a "RETURNING"
# statement. On DBs not supporting "RETURNING", this will cause an
# additional SELECT
created = Column(DateTime, server_default=FetchedValue())
engine = create_engine('postgresql://malbert@/malbert', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
instance = Foo(name="foo")
session.add(instance)
session.flush() # Flush is needed. FetchedValue does not trigger autoflush
print('>>---', instance.created)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment