跳到主要內容

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 頁面上了解更多資訊。

© . This site is unofficial and not affiliated with Prisma Data, Inc.