Getting Started
This tutorial uses PostgreSQL and ends with a client that writes and queries data. MySQL / MariaDB works the same way — swap the connection URL.
Prerequisites
- Node.js 20.0 or later
- A PostgreSQL 14+ server; the quickest way is 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+ and MariaDB 10.6+ are equally supported.
Install
bash
npm install @ofis/tsorm1
bash
pnpm add @ofis/tsorm1
bash
yarn add @ofis/tsorm1
bash
bun add @ofis/tsorm1
The mariadb and pg clients ship with the package. Installing also provides the tsorm command — see CLI.
Define Models
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 auto-generates the foreign key authorId; User.posts points back via @via(author), so the foreign key is not declared twice.
Generate the Client
bash
tsorm generate --schema schema.orm --out generated/client.ts1
Create the Tables
bash
DATABASE_URL=postgresql://postgres:test_password@127.0.0.1:5432/app tsorm push1
push is for prototyping; real projects manage schema changes with versioned migrations.
Write and Query
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