Skip to main content

diesel/pg/returning/
old_impl.rs

1//! `RETURNING old.col` support for PostgreSQL 18 and later.
2
3use crate::backend::{Backend, sql_dialect};
4use crate::expression::nullable::Nullable;
5use crate::expression::subselect::SubselectGroupBy;
6use crate::expression::{
7    AppearsOnTable, Expression, SelectableExpression, ValidGrouping, is_aggregate,
8};
9use crate::query_builder::returning::{
10    InsertStmtWithOnConflictDoUpdate, OldIdent, ReturningQuerySource, UpdateStmt,
11};
12use crate::query_builder::{AstPass, QueryFragment, QueryId};
13use crate::query_source::{AppearsInFromClause, Column};
14use crate::result::QueryResult;
15
16/// Wraps a column to refer to its pre-modification value in the `RETURNING`
17/// clause of a PostgreSQL `UPDATE` or `INSERT ... ON CONFLICT ... DO UPDATE`
18/// statement.
19///
20/// This is the type returned by [`old()`](old()).
21#[derive(#[automatically_derived]impl<C: ::core::fmt::Debug> ::core::fmt::Debug for
    Old<C> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "Old _column",
            &&self._column)
    }
}Debug, #[automatically_derived]impl<C: ::core::clone::Clone> ::core::clone::Clone for
    Old<C> {
    #[inline]
    fn clone(&self) -> Self {
        Old { _column: ::core::clone::Clone::clone(&self._column) }
    }
}Clone, #[automatically_derived]impl<C: ::core::marker::Copy> ::core::marker::Copy for
    Old<C> {
}Copy)]
22pub struct Old<C> {
23    _column: C,
24}
25
26impl<C> Old<C> {
27    pub(crate) fn new(c: C) -> Self {
28        Old { _column: c }
29    }
30}
31
32/// Refer to the pre-modification value of `col` in a PostgreSQL `RETURNING`
33/// clause.
34///
35/// This corresponds to the SQL `RETURNING old.col` syntax introduced in
36/// PostgreSQL 18.
37///
38/// # Requires PostgreSQL 18 or newer
39///
40/// Diesel emits `old.col` in the SQL it sends to the database. Earlier
41/// versions of PostgreSQL will reject the query at execution time.
42///
43/// # Statement compatibility
44///
45/// `old(col)` is valid inside the `RETURNING` clause of:
46///
47/// * an `UPDATE` statement, where it has the same Rust SQL type as `col`
48///   (since every returned row necessarily came from a pre-existing row).
49/// * an `INSERT ... ON CONFLICT ... DO UPDATE` statement, **but only when
50///   wrapped in [`.nullable()`]**: rows that were freshly inserted (rather
51///   than updated) have no `old` row, and `old.col` is `NULL` for them, so
52///   for type-safe deserialization you must opt into a nullable Rust SQL
53///   type. Writing `old(col)` directly (without `.nullable()`) in this
54///   context is rejected at compile time.
55///
56/// Use of `old(col)` in plain `INSERT` (without `ON CONFLICT ... DO UPDATE`)
57/// or `DELETE` `RETURNING` is rejected at compile time, because it is not useful
58/// there. (Note that `ON CONFLICT DO NOTHING` never returns untouched rows.)
59///
60/// [`.nullable()`]: crate::NullableExpressionMethods::nullable
61///
62/// # Example
63///
64/// ```rust
65/// # include!("../../doctest_setup.rs");
66/// #
67/// # #[cfg(feature = "postgres")]
68/// # fn main() {
69/// #     use schema::users::dsl::*;
70/// #     use diesel::pg::returning::old;
71/// #     let connection = &mut establish_connection();
72/// #     // `RETURNING old.col` requires PostgreSQL 18+
73/// #     if connection.version().unwrap() < diesel::connection::DatabaseVersion::new(18, 0, 0) {
74/// #         return;
75/// #     }
76/// let was_and_now = diesel::update(users.find(1))
77///     .set(name.eq("Updated"))
78///     .returning((old(name), name))
79///     .get_result::<(String, String)>(connection);
80/// assert_eq!(Ok(("Sean".to_string(), "Updated".to_string())), was_and_now);
81/// # }
82/// # #[cfg(not(feature = "postgres"))]
83/// # fn main() {}
84/// ```
85pub fn old<C: Column>(col: C) -> Old<C> {
86    Old::new(col)
87}
88
89impl<C> QueryId for Old<C> {
90    type QueryId = ();
91
92    const HAS_STATIC_QUERY_ID: bool = false;
93}
94
95impl<C> Expression for Old<C>
96where
97    C: Column + Expression,
98{
99    type SqlType = <C as Expression>::SqlType;
100}
101
102impl<C> ValidGrouping<()> for Old<C>
103where
104    C: Column,
105{
106    type IsAggregate = is_aggregate::No;
107}
108
109// `old` always names the row of the outer statement
110impl<C, GB, From> ValidGrouping<SubselectGroupBy<GB, From>> for Old<C>
111where
112    C: Column,
113    Self: ValidGrouping<GB>,
114{
115    type IsAggregate = <Self as ValidGrouping<GB>>::IsAggregate;
116}
117
118// `Old<C>` is selectable on a `RETURNING` clause whose statement-kind marker
119// is `UpdateStmt`. It is deliberately *not* selectable on
120// `ReturningQuerySource<InsertStmtWithOnConflictDoUpdate, _>` directly — only
121// `Nullable<Old<C>>` is, via the existing `Nullable` machinery and the
122// `ToInnerJoin` mapping in `returning_query_source` (which makes
123// `InsertStmtWithOnConflictDoUpdate`'s inner-join "fall back" to `UpdateStmt`).
124// That's how we force users to write `old(col).nullable()` in an
125// `INSERT ... ON CONFLICT ... DO UPDATE RETURNING` and reject `old(col)`
126// alone at compile time.
127impl<C, QS> AppearsOnTable<QS> for Old<C>
128where
129    C: Column,
130    Self: Expression,
131    // Check that we have exactly one `old` identifier in the `RETURNING` clause.
132    QS: AppearsInFromClause<OldIdent, Count = crate::query_source::Once>,
133    // Check that the `old` identifier relates the table of that column.
134    QS: AppearsInFromClause<
135            ReturningQuerySource<OldIdent, C::Table>,
136            Count = crate::query_source::Once,
137        >,
138{
139}
140
141// We intentionally did not add implementations for use of `old(col)` in plain `INSERT`
142// (without `ON CONFLICT ... DO UPDATE`) or `DELETE` `RETURNING`, because it is not useful
143// there as one can just use `RETURNING column_name`. (`ON CONFLICT DO NOTHING` never returns
144// untouched rows, so allowing `ON CONFLICT DO NOTHING ... RETURNING` might be misleading to
145// users on that regard - I, the author, have seen bugs caused by not being aware of this
146// PG behavior.)
147
148impl<C> SelectableExpression<ReturningQuerySource<UpdateStmt, C::Table>> for Old<C>
149where
150    C: Column,
151    Self: AppearsOnTable<ReturningQuerySource<UpdateStmt, C::Table>>,
152{
153}
154
155impl<C> SelectableExpression<ReturningQuerySource<InsertStmtWithOnConflictDoUpdate, C::Table>>
156    for Nullable<Old<C>>
157where
158    C: Column,
159    Self: AppearsOnTable<ReturningQuerySource<InsertStmtWithOnConflictDoUpdate, C::Table>>,
160{
161}
162
163impl<C, DB> QueryFragment<DB> for Old<C>
164where
165    DB: Backend,
166    Self: QueryFragment<DB, DB::ReturningClause>,
167{
168    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
169        <Self as QueryFragment<DB, DB::ReturningClause>>::walk_ast(self, pass)
170    }
171}
172
173impl<C, DB> QueryFragment<DB, sql_dialect::returning_clause::PgLikeReturningClause> for Old<C>
174where
175    DB: Backend<ReturningClause = sql_dialect::returning_clause::PgLikeReturningClause>,
176    C: Column,
177{
178    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
179        out.push_sql("old.");
180        out.push_identifier(C::NAME)?;
181        Ok(())
182    }
183}
184
185pub use return_type_helpers_reexported::*;
186
187pub(crate) mod return_type_helpers_reexported {
188    use super::Old;
189
190    /// The return type of [`old(col)`](super::old()).
191    #[allow(non_camel_case_types)]
192    pub type old<C> = Old<C>;
193}