Does last_insert_id of Sqlx return the ID of the current query? #2523
Replies: 1 comment
-
DISCLAIMER: I am still pretty new to raw SQL myself. Correct me, if I am wrong. If you're using a database such as Postgres or MariaDB you should work with the INSERT INTO plumbuses (fleeb)
VALUES (?)
RETURNING id -- (or whatever column from table plumbuses you want)
(Assuming you're on MySQL:) As far as I know: yes. Also, if you're bulk inserting, the value returned should point to the first inserted row (although, I am not sure, if this is still the case). This also gives you the issue, that The following code wasn't tested; it might not work, however, it'll illustrate the idea: let mut tx = db.begin().await?;
// Step 1: Create
sqlx::query!("INSERT INTO ...", params).execute(&mut tx).await?;
// Step 2: Retrieve the ID
let id: i64 = sqlx::query("SELECT LAST_INSERT_ID()").execute(&mut tx).await?;
// Step 3: Execute transaction
tx.commit().await?; Because the If my suspicion is correct that you're still using MySQL, my advice would be to switch either to MariaDB (directly compatible with MySQL) or use Postgres for the extended and new features. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello
Sqxl Rust has a function
last_insert_id()
after executing anINSERT
query.E.g:
But is this trustworthy? Is this always the inserted id of the recently executed query? What if this code gets executed twice by two different users? Won't it return the ID of the wrong user if it collided?
How would I get the row ID of the query I just executed in sqlx?
Beta Was this translation helpful? Give feedback.
All reactions