New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MySql : call LAST_INSERT_ID() after insert to get the last generated id. #1011

Closed
mmrath opened this Issue Jul 9, 2017 · 4 comments

Comments

Projects
None yet
4 participants
@mmrath

mmrath commented Jul 9, 2017

Setup

Versions

  • Rust: 1.20-nightly
  • Diesel: 0.14
  • Database: MySQL
  • Operating System ALL

Feature Flags

  • diesel:
  • diesel_codegen:

Problem Description

After insert into a table with auto_incremented primary key, we need to get the generated id after the insert.

What are you trying to accomplish?

In PG the following works.

let tag1: Tag = diesel::insert(&cat_tag)
        .into(tags::table)
        .get_result(conn)
        .expect("Error saving cat tag");

But we don't have anything similar for MySQL

What is the expected output?

Something like the above to work in MySQL

What is the actual output?

Are you seeing any additional errors?

Steps to reproduce

Checklist

  • I have already looked over the issue tracker for similar issues.
@sgrif

This comment has been minimized.

Member

sgrif commented Jul 9, 2017

LAST_INSERT_ID has many gotchas that I'm not comfortable implicitly relying on. If you'd like to use LAST_INSERT_ID, you can very easily do so with the sql_function! macro.

@sgrif sgrif closed this Jul 9, 2017

@vityafx

This comment has been minimized.

vityafx commented Jul 13, 2017

@sgrif could you be so kind giving an example please? (I am interested in sqlite and postgre-sql).

@mmrath

This comment has been minimized.

mmrath commented Jul 15, 2017

@vityafx In case you have not found a solution yet.

in my db module I have

no_arg_sql_function!(last_insert_id, types::Bigint);

I use it as below

let generated_id: i64 = select(db::last_insert_id).first(conn).unwrap();

@haruhinoshana

This comment has been minimized.

haruhinoshana commented Apr 9, 2018

@mmrath sir do you have a sample to implement this get last_insert_id im new at diesel and rust itself it will be a big help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment