如何使用 Diesel 和 SQLite 获取新创建的值的 id? [英] How to get the id of a newly-created value with Diesel and SQLite?

查看:81
本文介绍了如何使用 Diesel 和 SQLite 获取新创建的值的 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Diesel 的 SqliteBackend 没有实现 SupportsReturningClause trait,所以 get_result 方法不能用于检索新创建的值.

Diesel's SqliteBackend does not implement the SupportsReturningClause trait, so the get_result method cannot be used to retrieve a newly created value.

还有其他方法可以找出插入行的 id 吗?Python 对此有一个解决方案.到目前为止,我找到的唯一解决方案是对 id 使用 UUID 而不是自动增量字段.

Is there another way to find out the id of the inserted row? Python has a solution for this. The only solution I've found so far is to use a UUID for ids instead of an autoincrement field.

推荐答案

这里的根本问题是 SQLite 不支持允许您返回的 SQL RETURNING 子句作为插入语句一部分的自动生成的 ID.

The underlying issue here is that SQLite does not support SQL RETURNING clauses which would allow you to return the auto generated id as part of your insert statement.

由于 OP 只提供了一个一般性问题,我无法举例说明如何使用柴油来实现.

As the OP only provided a general question I cannot show examples how to implement that using diesel.

有多种方法可以解决此问题.所有这些都要求您执行第二个查询.

There are several ways to workaround this issue. All of them require that you execute a second query.

  1. 按 id 排序并仅选择最大的 id.这是最直接的解决办法.它直接显示了进行第二次查询的问题,因为在任何时间点都可能有一个竞速插入,这样你就可以找回错误的 id(至少在你不使用事务的情况下).

  1. Order by id and select just the largest id. That's the most direct solution. It shows directly the issues with doing a second query, as there can be a racing insert at any point in time, so that you can get back the wrong id (at least if you don't use transactions).

使用last_insert_rowid() SQL 函数接收最后插入的列的行 ID.如果未配置,则这些行 ID 与您的自动增量主整数键匹配.在柴油方面,您可以使用 no_arg_sql_function!() 在你的 crate 中定义底层的 sql 函数.

Use the last_insert_rowid() SQL function to receive the row id of the last inserted column. If not configured otherwise those row id matches your autoincrement primary integer key. On diesel side you can use no_arg_sql_function!() to define the underlying sql function in your crate.

这篇关于如何使用 Diesel 和 SQLite 获取新创建的值的 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆