Skip to main content

diesel/mysql_like/query_builder/
insert_returning_id.rs

1//! `execute_returning_id` for MySQL and MariaDB inserts.
2
3use core::num::NonZeroU64;
4
5use crate::mysql_like::MysqlLikeBackend;
6use crate::mysql_like::connection::MysqlLikeConnection;
7use crate::query_builder::{InsertStatement, QueryFragment, QueryId, SingleRowInsertValues};
8use crate::query_source::{AutoIncrementTable, QuerySource};
9use crate::result::QueryResult;
10
11impl<T: QuerySource, U, Op, Ret> InsertStatement<T, U, Op, Ret> {
12    /// Executes this insert and returns the `AUTO_INCREMENT` value it set, or
13    /// `None` if it set none. The value comes from [`mysql_stmt_insert_id`],
14    /// read straight from the executed statement, so it needs neither a
15    /// `RETURNING` clause nor an extra `SELECT LAST_INSERT_ID()` round trip.
16    ///
17    /// Only available for single-row inserts into a table whose
18    /// [`table!`](crate::table!) definition marks a column with
19    /// `#[auto_increment]` (emitted by `diesel print-schema`).
20    ///
21    /// [`mysql_stmt_insert_id`]: https://dev.mysql.com/doc/c-api/8.4/en/mysql-stmt-insert-id.html
22    ///
23    /// # Caveats
24    /// - A key you supply explicitly is reported back rather than `None`, as
25    ///   is the key of the row an `ON DUPLICATE KEY UPDATE` clause updates
26    /// - An `INSERT IGNORE` whose row is skipped gives `None`
27    /// - Differs from the SQL `LAST_INSERT_ID()` function in the cases above
28    ///   and for `LAST_INSERT_ID(expr)`
29    ///
30    /// # Example
31    /// ```rust
32    /// # include!("../../doctest_setup.rs");
33    /// # fn main() {
34    /// #     run_test().unwrap();
35    /// # }
36    /// # fn run_test() -> QueryResult<()> {
37    /// #     use schema::users::dsl::*;
38    /// use core::num::NonZeroU64;
39    /// let conn = &mut establish_connection();
40    /// let new_id = diesel::insert_into(users)
41    ///     .values(name.eq("Ruby"))
42    ///     .execute_returning_id(conn)?;
43    /// // Ids 1 and 2 are seeded, so the generated id is 3.
44    /// assert_eq!(new_id, NonZeroU64::new(3));
45    /// # Ok(())
46    /// # }
47    /// ```
48    pub fn execute_returning_id<DB>(
49        self,
50        conn: &mut MysqlLikeConnection<DB>,
51    ) -> QueryResult<Option<NonZeroU64>>
52    where
53        DB: MysqlLikeBackend,
54        T: AutoIncrementTable,
55        U: SingleRowInsertValues<T>,
56        Self: QueryFragment<DB> + QueryId,
57    {
58        conn.execute_returning_id(&self)
59    }
60}