Sqxl Rust has a function last_insert_id() after executing an INSERT query.
E.g:
let result = sqlx::query("INSERT INTO example (a, b) VALUES (?,?)")
.bind(&a)
.bind(&b)
.execute(&mysql.conn)
.await;
match result {
//...
Ok(r) => {
//....
println!("{}", r.last_insert_id());
//...
}
}
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?
At least for MySQL - and probably for every DMBS, since this is a very common pattern - sqlx has no idea what that value is. It gets it from the response provided by the underlying DBMS.
MySQL, in turn, promises that the relevant response will contain the last insert ID, which is tracked per connection and is set based on the auto_increment field, if any, of the most recent row inserted by that connection specifically.
So the answer to your question is, the database keeps track of it for you and gives you the result for your connection. sqlx just makes that answer available as-is.
If you were using a DBMS that supported it, I'd suggest using a returning clause in the query, since it's more general and easier to understand. However, as of this writing, MySQL still does not support it.
In both cases it just sends the request to the database. And in both cases it's guaranteed to work for the MySQL and doesn't guaranteed to work for any random database.