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

Sqlite: There should be a way to obtain an id of last insert #771

Closed
krdln opened this Issue Feb 28, 2017 · 1 comment

Comments

Projects
None yet
3 participants
@krdln

krdln commented Feb 28, 2017

It is a really crucial feature to be able to obtain an id an inserted object. Postgres backend allows to do that using RETURING clause via the get_result method. Sqlite exposes last_insert_rowid but it's not reexported by diesel. Without that feature, the sqlite backend is quite unusable for me.

I see a few possible solutions here:

  1. Just reexport the last_insert_rowid for SqliteConnection. The connection is not Sync so it shouldn't be a problem.
  2. Create a trait method for getting the id of the insert/update and implement it for all the backends. Postgres backend could just call get_result. This solution is nice as it allows writing backend-agnostic code.
  3. Make the get_result work on sqlite only on structs containing just the id. I actually don't know diesel well enough to understand whether this is possible by appropriate implementations of Queryable.
  4. Make the get_result work for sqlite by pulling data from the structs that are inserted. It won't work for UPDATE though. I guess that would require some architectural changes in diesel, but on the other hand, it's the simplest solution wrt porting code between backends.
  5. I've just learned that you can execute the raw query SELECT last_insert_rowid();. Maybe this workarkound could be exposed somewhere in the docs (for LoadDsl or SqliteConnection)? Also, I have to admit, I don't know how how to execute raw sql query in diesel, searching for raw yields no results.
@sgrif

This comment has been minimized.

Member

sgrif commented Mar 1, 2017

You can get the result of last_insert_rowid in your application using no_arg_sql_function! and select. We may eventually try to implement get_result for inserts on SQLite, but last_insert_rowid has a ton of caveats and gotchas that we've opted to avoid for the time being. table.order(id.desc()).first(&conn) inside of a transaction makes the tradeoffs much more apparent.

@sgrif sgrif closed this Mar 1, 2017

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