This page is part of the .

    Previous: Working with Data | Next:

    Data Manipulation with the ORM

    The previous section remained focused on the SQL Expression Language from a Core perspective, in order to provide continuity across the major SQL statement constructs. This section will then build out the lifecycle of the and how it interacts with these constructs.

    Prerequisite Sections - the ORM focused part of the tutorial builds upon two previous ORM-centric sections in this document:

    • - introduces how to make an ORM Session object

    • - where we set up our ORM mappings of the User and Address entities

    • Selecting ORM Entities and Columns - a few examples on how to run SELECT statements for entities like User

    When using the ORM, the object is responsible for constructing Insert constructs and emitting them for us in a transaction. The way we instruct the to do so is by adding object entries to it; the Session then makes sure these new entries will be emitted to the database when they are needed, using a process known as a flush.

    Whereas in the previous example we emitted an INSERT using Python dictionaries to indicate the data we wanted to add, with the ORM we make direct use of the custom Python classes we defined, back at . At the class level, the User and Address classes served as a place to define what the corresponding database tables should look like. These classes also serve as extensible data objects that we use to create and manipulate rows within a transaction as well. Below we will create two User objects each representing a potential database row to be INSERTed:

    We are able to construct these objects using the names of the mapped columns as keyword arguments in the constructor. This is possible as the User class includes an automatically generated __init__() constructor that was provided by the ORM mapping so that we could create each object using column names as keys in the constructor.

    In a similar manner as in our Core examples of Insert, we did not include a primary key (i.e. an entry for the id column), since we would like to make use of the auto-incrementing primary key feature of the database, SQLite in this case, which the ORM also integrates with. The value of the id attribute on the above objects, if we were to view it, displays itself as None:

    1. >>> squidward
    2. User(id=None, name='squidward', fullname='Squidward Tentacles')

    The None value is provided by SQLAlchemy to indicate that the attribute has no value as of yet. SQLAlchemy-mapped attributes always return a value in Python and don’t raise AttributeError if they’re missing, when dealing with a new object that has not had a value assigned.

    At the moment, our two objects above are said to be in a state called - they are not associated with any database state and are yet to be associated with a Session object that can generate INSERT statements for them.

    Adding objects to a Session

    To illustrate the addition process step by step, we will create a Session without using a context manager (and hence we must make sure we close it later!):

    1. >>> session = Session(engine)

    The objects are then added to the using the Session.add() method. When this is called, the objects are in a state known as and have not been inserted yet:

    1. >>> session.add(squidward)
    2. >>> session.add(krabs)

    When we have pending objects, we can see this state by looking at a collection on the Session called :

    1. >>> session.new
    2. IdentitySet([User(id=None, name='squidward', fullname='Squidward Tentacles'), User(id=None, name='ehkrabs', fullname='Eugene H. Krabs')])

    The above view is using a collection called IdentitySet that is essentially a Python set that hashes on object identity in all cases (i.e., using Python built-in id() function, rather than the Python hash() function).

    The Session makes use of a pattern known as . This generally means it accumulates changes one at a time, but does not actually communicate them to the database until needed. This allows it to make better decisions about how SQL DML should be emitted in the transaction based on a given set of pending changes. When it does emit SQL to the database to push out the current set of changes, the process is known as a flush.

    We can illustrate the flush process manually by calling the Session.flush() method:

    1. >>> session.flush()
    2. BEGIN (implicit)
    3. INSERT INTO user_account (name, fullname) VALUES (?, ?)
    4. [...] ('squidward', 'Squidward Tentacles')
    5. INSERT INTO user_account (name, fullname) VALUES (?, ?)
    6. [...] ('ehkrabs', 'Eugene H. Krabs')

    Above we observe the was first called upon to emit SQL, so it created a new transaction and emitted the appropriate INSERT statements for the two objects. The transaction now remains open until we call any of the Session.commit(), , or Session.close() methods of .

    While Session.flush() may be used to manually push out pending changes to the current transaction, it is usually unnecessary as the features a behavior known as autoflush, which we will illustrate later. It also flushes out changes whenever Session.commit() is called.

    Autogenerated primary key attributes

    Once the rows are inserted, the two Python objects we’ve created are in a state known as persistent, where they are associated with the object in which they were added or loaded, and feature lots of other behaviors that will be covered later.

    Another effect of the INSERT that occurred was that the ORM has retrieved the new primary key identifiers for each new object; internally it normally uses the same CursorResult.inserted_primary_key accessor we introduced previously. The squidward and krabs objects now have these new primary key identifiers associated with them and we can view them by acesssing the id attribute:

    1. >>> squidward.id
    2. 4
    3. >>> krabs.id
    4. 5

    Why did the ORM emit two separate INSERT statements when it could have used ? As we’ll see in the next section, the Session when flushing objects always needs to know the primary key of newly inserted objects. If a feature such as SQLite’s autoincrement is used (other examples include PostgreSQL IDENTITY or SERIAL, using sequences, etc.), the feature usually requires that each INSERT is emitted one row at a time. If we had provided values for the primary keys ahead of time, the ORM would have been able to optimize the operation better. Some database backends such as psycopg2 can also INSERT many rows at once while still being able to retrieve the primary key values.

    The primary key identity of the objects are significant to the , as the objects are now linked to this identity in memory using a feature known as the identity map. The identity map is an in-memory store that links all objects currently loaded in memory to their primary key identity. We can observe this by retrieving one of the above objects using the method, which will return an entry from the identity map if locally present, otherwise emitting a SELECT:

    1. >>> some_squidward = session.get(User, 4)
    2. >>> some_squidward
    3. User(id=4, name='squidward', fullname='Squidward Tentacles')

    The important thing to note about the identity map is that it maintains a unique instance of a particular Python object per a particular database identity, within the scope of a particular Session object. We may observe that the some_squidward refers to the same object as that of squidward previously:

    1. >>> some_squidward is squidward
    2. True

    The identity map is a critical feature that allows complex sets of objects to be manipulated within a transaction without things getting out of sync.

    Committing

    There’s much more to say about how the Session works which will be discussed further. For now we will commit the transaction so that we can build up knowledge on how to SELECT rows before examining more ORM behaviors and features:

    1. >>> session.commit()
    2. COMMIT

    In the preceding section , we introduced the Update construct that represents a SQL UPDATE statement. When using the ORM, there are two ways in which this construct is used. The primary way is that it is emitted automatically as part of the process used by the Session, where an UPDATE statement is emitted on a per-primary key basis corresponding to individual objects that have changes on them. A second form of UPDATE is called an “ORM enabled UPDATE” and allows us to use the construct with the Session explicitly; this is described in the next section.

    Supposing we loaded the User object for the username into a transaction (also showing off the method as well as the Result.scalar_one() method):

    1. sql>>> sandy = session.execute(select(User).filter_by(name="sandy")).scalar_one()
    2. BEGIN (implicit)
    3. SELECT user_account.id, user_account.name, user_account.fullname
    4. FROM user_account
    5. [...] ('sandy',)

    The Python object sandy as mentioned before acts as a proxy for the row in the database, more specifically the database row in terms of the current transaction, that has the primary key identity of 2:

    If we alter the attributes of this object, the tracks this change:

    1. >>> sandy.fullname = "Sandy Squirrel"

    The object appears in a collection called Session.dirty, indicating the object is “dirty”:

    1. >>> sandy in session.dirty
    2. True

    When the next emits a flush, an UPDATE will be emitted that updates this value in the database. As mentioned previously, a flush occurs automatically before we emit any SELECT, using a behavior known as autoflush. We can query directly for the User.fullname column from this row and we will get our updated value back:

    1. >>> sandy_fullname = session.execute(
    2. ... select(User.fullname).where(User.id == 2)
    3. ... ).scalar_one()
    4. UPDATE user_account SET fullname=? WHERE user_account.id = ?
    5. [...] ('Sandy Squirrel', 2)
    6. SELECT user_account.fullname
    7. FROM user_account
    8. WHERE user_account.id = ?
    9. [...] (2,)
    10. >>> print(sandy_fullname)
    11. Sandy Squirrel

    We can see above that we requested that the Session execute a single statement. However the SQL emitted shows that an UPDATE were emitted as well, which was the flush process pushing out pending changes. The sandy Python object is now no longer considered dirty:

    1. >>> sandy in session.dirty
    2. False

    However note we are still in a transaction and our changes have not been pushed to the database’s permanent storage. Since Sandy’s last name is in fact “Cheeks” not “Squirrel”, we will repair this mistake later when we roll back the transction. But first we’ll make some more data changes.

    See also

    Flushing- details the flush process as well as information about the setting.

    As previously mentioned, there’s a second way to emit UPDATE statements in terms of the ORM, which is known as an ORM enabled UPDATE statement. This allows the use of a generic SQL UPDATE statement that can affect many rows at once. For example to emit an UPDATE that will change the User.fullname column based on a value in the User.name column:

    1. >>> session.execute(
    2. ... update(User).
    3. ... where(User.name == "sandy").
    4. ... values(fullname="Sandy Squirrel Extraodinaire")
    5. ... )
    6. UPDATE user_account SET fullname=? WHERE user_account.name = ?
    7. [...] ('Sandy Squirrel Extraodinaire', 'sandy')
    8. <sqlalchemy.engine.cursor.CursorResult object ...>

    When invoking the ORM-enabled UPDATE statement, special logic is used to locate objects in the current session that match the given criteria, so that they are refreshed with the new data. Above, the sandy object identity was located in memory and refreshed:

    1. >>> sandy.fullname
    2. 'Sandy Squirrel Extraodinaire'

    The refresh logic is known as the synchronize_session option, and is described in detail in the section UPDATE and DELETE with arbitrary WHERE clause.

    See also

    - describes ORM use of update() and as well as ORM synchronization options.

    To round out the basic persistence operations, an individual ORM object may be marked for deletion by using the Session.delete() method. Let’s load up patrick from the database:

    1. sql>>> patrick = session.get(User, 3)
    2. SELECT user_account.id AS user_account_id, user_account.name AS user_account_name,
    3. user_account.fullname AS user_account_fullname
    4. FROM user_account
    5. WHERE user_account.id = ?
    6. [...] (3,)

    If we mark patrick for deletion, as is the case with other operations, nothing actually happens yet until a flush proceeds:

    1. >>> session.delete(patrick)

    Current ORM behavior is that patrick stays in the until the flush proceeds, which as mentioned before occurs if we emit a query:

    1. >>> session.execute(select(User).where(User.name == "patrick")).first()
    2. SELECT address.id AS address_id, address.email_address AS address_email_address,
    3. address.user_id AS address_user_id
    4. FROM address
    5. WHERE ? = address.user_id
    6. [...] (3,)
    7. DELETE FROM user_account WHERE user_account.id = ?
    8. [...] (3,)
    9. SELECT user_account.id, user_account.name, user_account.fullname
    10. FROM user_account
    11. [...] ('patrick',)

    See also

    delete - describes how to tune the behavior of in terms of how related rows in other tables should be handled.

    Beyond that, the patrick object instance now being deleted is no longer considered to be persistent within the , as is shown by the containment check:

    1. >>> patrick in session
    2. False

    However just like the UPDATEs we made to the sandy object, every change we’ve made here is local to an ongoing transaction, which won’t become permanent if we don’t commit it. As rolling the transaction back is actually more interesting at the moment, we will do that in the next section.

    ORM-enabled DELETE Statements

    Like UPDATE operations, there is also an ORM-enabled version of DELETE which we can illustrate by using the delete() construct with . It also has a feature by which non expired objects (see expired) that match the given deletion criteria will be automatically marked as “” in the Session:

    The squidward identity, like that of patrick, is now also in a deleted state. Note that we had to re-load squidward above in order to demonstrate this; if the object were expired, the DELETE operation would not take the time to refresh expired objects just to see that they had been deleted:

    1. >>> squidward in session
    2. False

    The has a Session.rollback() method that as expected emits a ROLLBACK on the SQL connection in progress. However, it also has an effect on the objects that are currently associated with the , in our previous example the Python object sandy. While we changed the .fullname of the sandy object to read "Sandy Squirrel", we want to roll back this change. Calling Session.rollback() will not only roll back the transaction but also expire all objects currently associated with this , which will have the effect that they will refresh themselves when next accessed using a process known as lazy loading:

    1. >>> session.rollback()
    2. ROLLBACK

    To view the “expiration” process more closely, we may observe that the Python object sandy has no state left within its Python __dict__, with the exception of a special SQLAlchemy internal state object:

    1. >>> sandy.__dict__
    2. {'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x...>}

    This is the “” state; accessing the attribute again will autobegin a new transaction and refresh sandy with the current database row:

    1. >>> sandy.fullname
    2. BEGIN (implicit)
    3. SELECT user_account.id AS user_account_id, user_account.name AS user_account_name,
    4. user_account.fullname AS user_account_fullname
    5. FROM user_account
    6. WHERE user_account.id = ?
    7. [...] (2,)
    8. 'Sandy Cheeks'

    We may now observe that the full database row was also populated into the __dict__ of the sandy object:

    1. >>> sandy.__dict__
    2. {'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x...>,
    3. 'id': 2, 'name': 'sandy', 'fullname': 'Sandy Cheeks'}

    For deleted objects, when we earlier noted that patrick was no longer in the session, that object’s identity is also restored:

    1. >>> patrick in session
    2. True

    and of course the database data is present again as well:

    1. sql>>> session.execute(select(User).where(User.name == 'patrick')).scalar_one() is patrick
    2. SELECT user_account.id, user_account.name, user_account.fullname
    3. FROM user_account
    4. WHERE user_account.name = ?
    5. [...] ('patrick',)
    6. True

    Within the above sections we used a Session object outside of a Python context manager, that is, we didn’t use the with statement. That’s fine, however if we are doing things this way, it’s best that we explicitly close out the when we are done with it:

    1. >>> session.close()
    2. ROLLBACK

    Closing the Session, which is what happens when we use it in a context manager as well, accomplishes the following things:

    • It all connection resources to the connection pool, cancelling out (e.g. rolling back) any transactions that were in progress.

      This means that when we make use of a session to perform some read-only tasks and then close it, we don’t need to explicitly call upon Session.rollback() to make sure the transaction is rolled back; the connection pool handles this.

    • It expunges all objects from the .

      This means that all the Python objects we had loaded for this Session, like sandy, patrick and squidward, are now in a state known as . In particular, we will note that objects that were still in an expired state, for example due to the call to , are now non-functional, as they don’t contain the state of a current row and are no longer associated with any database transaction in which to be refreshed:

      1. >>> squidward.name
      2. Traceback (most recent call last):
      3. ...
      4. sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is not bound to a Session; attribute refresh operation cannot proceed

      The detached objects can be re-associated with the same, or a new Session using the method, which will re-establish their relationship with their particular database row:

      1. >>> session.add(squidward)
      2. >>> squidward.name
      3. BEGIN (implicit)
      4. SELECT user_account.id AS user_account_id, user_account.name AS user_account_name, user_account.fullname AS user_account_fullname
      5. FROM user_account
      6. WHERE user_account.id = ?
      7. [...] (4,)
      8. 'squidward'

      Tip

      Try to avoid using objects in their detached state, if possible. When the Session is closed, clean up references to all the previously attached objects as well. For cases where detached objects are necessary, typically the immediate display of just-committed objects for a web application where the is closed before the view is rendered, set the Session.expire_on_commit flag to False.

    SQLAlchemy 1.4 / 2.0 Tutorial

    Next Tutorial Section: