快速开始
本教程使用 PostgreSQL,完成后即可得到能写入和查询数据的客户端。MySQL / MariaDB 流程完全一致,替换连接串即可。
前提条件
- Node.js 20.0 及以上
- 一个 PostgreSQL 14+ 服务;最快的方式是 Docker:
bash
docker run --name tsorm-postgres -e POSTGRES_PASSWORD=test_password -e POSTGRES_DB=app -p 127.0.0.1:5432:5432 -d postgres:141
MySQL 8.0.16+ 与 MariaDB 10.6+ 同样支持。
安装
bash
npm install @ofis/tsorm1
bash
pnpm add @ofis/tsorm1
bash
yarn add @ofis/tsorm1
bash
bun add @ofis/tsorm1
MySQL 的 mariadb 与 PostgreSQL 的 pg 客户端随包安装。安装同时提供 tsorm 命令,用法见 CLI。
定义模型
ts
model User {
id: int @id @auto
email: string @unique
name?: string
posts: Post[] @via(author)
}
model Post {
id: int @id @auto
title: string
published: boolean = false
createdAt: datetime = now()
author: User
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
Post.author 会自动生成外键字段 authorId;User.posts 通过 @via(author) 指向对应关系,外键无需重复声明。
生成客户端
bash
tsorm generate --schema schema.orm --out generated/client.ts1
创建表
bash
DATABASE_URL=postgresql://postgres:test_password@127.0.0.1:5432/app tsorm push1
push 适合原型阶段;正式项目用版本化迁移管理结构。
写入和查询
ts
import { createClient } from "./generated/client.ts";
const db = createClient({
connection: "postgresql://postgres:test_password@127.0.0.1:5432/app",
});
try {
await db.user.create({
data: {
email: "alice@example.com",
posts: { create: { title: "Hello ORM" } },
},
});
const users = await db.user.findMany({
where: { posts: { some: { published: false } } },
include: { posts: { take: 3, orderBy: { id: "desc" } } },
});
console.log(users);
} finally {
await db.$close();
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bash
node main.ts1