设置
如果您已完成安装步骤并设置了cargo prisma <command>
别名,您就可以将 Prisma Client Rust 生成器添加到您的Prisma 模式 (在新标签页中打开)中了。
一个常见的文件夹布局是为模式和迁移创建自己的文件夹
Cargo.toml
src/
main.rs
prisma/
schema.prisma
migrations/
下面是位于prisma/schema.prisma
的模式示例。它使用 SQLite 数据库并在src/prisma.rs
生成客户端
datasource db {
provider = "sqlite"
url = "file:dev.db"
}
generator client {
// Corresponds to the cargo alias created earlier
provider = "cargo prisma"
// The location to generate the client. Is relative to the position of the schema
output = "../src/prisma.rs"
}
model User {
id String @id
displayName String
}
接下来,运行cargo prisma generate
来生成将在您的 Rust 代码中使用的客户端。如果您已安装rustfmt
,则生成的代码将被格式化,以便于探索和调试。
生成的客户端不得检入源代码控制。它不能在设备或操作系统之间传输。您需要在构建项目的任何位置重新生成它。如果使用 git,请将其添加到您的.gitignore
文件中。
创建客户端
首先,确保您正在使用Tokio (在新标签页中打开)异步运行时。其他运行时尚未经过测试,但由于Prisma 引擎 (在新标签页中打开)使用它,因此可能没有其他选择。
PrismaClient::_builder()
提供了一个用于自定义生成的客户端的构建器 API。最简单的用法是在构建器上直接调用.build()
。使用上面模式作为参考,此构建器在main.rs
文件中创建了一个客户端,该文件紧挨着prisma.rs
// Stops the client from outputting a huge number of warnings during compilation.
#[allow(warnings, unused)]
mod prisma;
use prisma::PrismaClient;
use prisma_client_rust::NewClientError;
#[tokio::main]
async fn main() {
let client: Result<PrismaClient, NewClientError> = PrismaClient::_builder().build().await;
}
可以使用with_url
构建器方法来自定义客户端连接到的数据库。在大多数情况下,建议使用模式中的环境变量来控制这一点,但在某些情况下(例如,具有多个数据库的桌面应用程序),环境变量无法自定义。
命名冲突
Rust 有一组保留关键字 (在新标签页中打开),不能在您的代码中用作名称。如果您将模型或字段命名为在转换为snake_case
后将成为受限关键字,则在生成的客户端中,它将在前缀中添加r#
,而不是直接失败生成。