Skip to main content

old

Function old 

Source
pub fn old<C: Column>(col: C) -> Old<C>
Available on crate feature postgres_backend only.
Expand description

Refer to the pre-modification value of col in a PostgreSQL RETURNING clause.

This corresponds to the SQL RETURNING old.col syntax introduced in PostgreSQL 18.

§Requires PostgreSQL 18 or newer

Diesel emits old.col in the SQL it sends to the database. Earlier versions of PostgreSQL will reject the query at execution time.

§Statement compatibility

old(col) is valid inside the RETURNING clause of:

  • an UPDATE statement, where it has the same Rust SQL type as col (since every returned row necessarily came from a pre-existing row).
  • an INSERT ... ON CONFLICT ... DO UPDATE statement, but only when wrapped in .nullable(): rows that were freshly inserted (rather than updated) have no old row, and old.col is NULL for them, so for type-safe deserialization you must opt into a nullable Rust SQL type. Writing old(col) directly (without .nullable()) in this context is rejected at compile time.

Use of old(col) in plain INSERT (without ON CONFLICT ... DO UPDATE) or DELETE RETURNING is rejected at compile time, because it is not useful there. (Note that ON CONFLICT DO NOTHING never returns untouched rows.)

§Example

let was_and_now = diesel::update(users.find(1))
    .set(name.eq("Updated"))
    .returning((old(name), name))
    .get_result::<(String, String)>(connection);
assert_eq!(Ok(("Sean".to_string(), "Updated".to_string())), was_and_now);