跳到主要内容

TypeScript 项目中 CockroachDB 的内省

使用 Prisma ORM 内省你的数据库

在本指南中,我们将使用包含三个表的演示 SQL schema

CREATE TABLE "User" (
id INT8 PRIMARY KEY DEFAULT unique_rowid(),
name STRING(255),
email STRING(255) UNIQUE NOT NULL
);

CREATE TABLE "Post" (
id INT8 PRIMARY KEY DEFAULT unique_rowid(),
title STRING(255) UNIQUE NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
content STRING,
published BOOLEAN NOT NULL DEFAULT false,
"authorId" INT8 NOT NULL,
FOREIGN KEY ("authorId") REFERENCES "User"(id)
);

CREATE TABLE "Profile" (
id INT8 PRIMARY KEY DEFAULT unique_rowid(),
bio STRING,
"userId" INT8 UNIQUE NOT NULL,
FOREIGN KEY ("userId") REFERENCES "User"(id)
);

注意:某些字段用双引号括起来,以确保 CockroachDB 使用正确的字母大小写。如果未使用双引号,CockroachDB 会将所有内容都读取为小写字符。

展开查看表格的图形概览

用户

列名类型主键外键必填默认值
idINT8✔️✔️自增
nameSTRING(255)-
emailSTRING(255)✔️-

Post

列名类型主键外键必填默认值
idINT8✔️✔️自增
createdAtTIMESTAMP✔️now()
titleSTRING(255)✔️-
contentSTRING-
publishedBOOLEAN✔️false
authorIdINT8✔️✔️-

Profile

列名类型主键外键必填默认值
idINT8✔️✔️自增
bioSTRING-
userIdINT8✔️✔️-

下一步,你将内省你的数据库。内省的结果将是 Prisma schema 中的一个数据模型

运行以下命令来内省你的数据库

npx prisma db pull

此命令读取用于定义 `schema.prisma` 中 `url` 的环境变量 `DATABASE_URL`,在我们的例子中,它设置在 `.env` 文件中,并连接到你的数据库。连接建立后,它会内省数据库(即读取数据库 schema)。然后它将数据库 schema 从 SQL 转换为 Prisma 数据模型。

内省完成后,你的 Prisma schema 将被更新

Introspect your database

数据模型现在看起来类似于这样

prisma/schema.prisma
model Post {
id BigInt @id @default(autoincrement())
title String @unique @db.String(255)
createdAt DateTime @default(now()) @db.Timestamp(6)
content String?
published Boolean @default(false)
authorId BigInt
User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model Profile {
id BigInt @id @default(autoincrement())
bio String?
userId BigInt @unique
User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model User {
id BigInt @id @default(autoincrement())
name String? @db.String(255)
email String @unique @db.String(255)
Post Post[]
Profile Profile?
}

Prisma ORM 的数据模型是你数据库 schema 的声明性表示,它作为生成的 Prisma 客户端库的基础。你的 Prisma 客户端实例将暴露为这些模型量身定制的查询。

目前,数据模型存在一些小“问题”

  • User 关系字段是大写的,因此不符合 Prisma 的命名约定。为了表达更多“语义”,如果这个字段命名为 author 以更好地描述 UserPost 之间的关系,那会更好。
  • User 上的 PostProfile 关系字段以及 Profile 上的 User 关系字段都是大写的。为了符合 Prisma 的命名约定,这两个字段都应该小写为 postprofileuser
  • 即使小写后,User 上的 post 字段仍然有点命名不当。那是因为它实际上指的是一个帖子列表——因此一个更好的名称是复数形式:posts

这些更改对于生成的 Prisma 客户端 API 很重要,在其中使用小写关系字段 authorpostsprofileuser 会让 JavaScript/TypeScript 开发人员感觉更自然和惯用。因此,你可以配置你的 Prisma 客户端 API

因为关系字段虚拟的(即它们不直接在数据库中体现),所以你可以手动在 Prisma schema 中重命名它们,而无需触及数据库

prisma/schema.prisma
model Post {
id BigInt @id @default(autoincrement())
title String @unique @db.String(255)
createdAt DateTime @default(now()) @db.Timestamp(6)
content String?
published Boolean @default(false)
authorId BigInt
author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model Profile {
id BigInt @id @default(autoincrement())
bio String?
userId BigInt @unique
user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model User {
id BigInt @id @default(autoincrement())
name String? @db.String(255)
email String @unique @db.String(255)
posts Post[]
profile Profile?
}

在此示例中,数据库 schema 遵循了 Prisma ORM 模型的命名约定(只有通过内省生成的虚拟关系字段不符合约定,需要调整)。这优化了生成的 Prisma 客户端 API 的人体工程学。

使用自定义模型和字段名称

然而,有时你可能希望对 Prisma 客户端 API 中暴露的列名和表名进行额外的更改。一个常见的例子是将数据库 schema 中常用的snake_case表示法转换为 JavaScript/TypeScript 开发人员感觉更自然的PascalCasecamelCase表示法。

假设你从内省中获得了以下基于snake_case表示法的模型

model my_user {
user_id Int @id @default(sequence())
first_name String?
last_name String @unique
}

如果你为此模型生成了 Prisma 客户端 API,它将在其 API 中使用snake_case表示法

const user = await prisma.my_user.create({
data: {
first_name: 'Alice',
last_name: 'Smith',
},
})

如果你不想在 Prisma 客户端 API 中使用数据库的表名和列名,你可以使用@map@@map 来配置它们

model MyUser {
userId Int @id @default(sequence()) @map("user_id")
firstName String? @map("first_name")
lastName String @unique @map("last_name")

@@map("my_user")
}

通过这种方法,你可以随意命名你的模型及其字段,并使用 @map(用于字段名)和 @@map(用于模型名)指向底层表和列。你的 Prisma 客户端 API 现在看起来如下所示

const user = await prisma.myUser.create({
data: {
firstName: 'Alice',
lastName: 'Smith',
},
})

配置你的 Prisma 客户端 API 页面上了解更多信息。

© . All rights reserved.