Facet ORM
Facet is a schema-first TypeScript ORM for PostgreSQL and SQLite. You describe models in schema.facet, run facet generate to get a typed client, and query with findMany, create, nested writes and transactions. facet migrate creates and applies SQL migrations and detects drift. It works with any Postgres, Quotura or not.
Last reviewed
Install
Facet needs Node.js 22.13 or newer and has no dependencies of its own. Add pg for Postgres over TCP.
npm install facet-orm pg
npx facet init # writes schema.facet and .env
npx facet migrate dev --name initFacet is published to npm at launch. After upgrading it, run facet generate again.
The schema
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
output = "./generated"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id String @id @default(uuid())
title String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
@@index([authorId])
}- Types:
StringIntBigIntFloatDecimalBooleanDateTimeJsonand enums;?makes a field optional. - Attributes:
@id@unique@default(...)@updatedAt@map@db@relationand@@id@@unique@@index@@map. - Relations: one-to-one, one-to-many, many-to-many through an explicit join model, and self-relations.
The client
import pg from 'pg';
import { FacetClient, postgres } from './generated/index.js';
const db = new FacetClient({ adapter: postgres(new pg.Pool({ connectionString: process.env.DATABASE_URL })) });
const user = await db.user.create({ data: { email: 'ada@example.com', posts: { create: [{ title: 'Hello' }] } }, include: { posts: true } });
const feed = await db.post.findMany({ where: { title: { contains: 'hello', mode: 'insensitive' } }, orderBy: { title: 'asc' }, take: 20 });
await db.$transaction(async (tx) => {
await tx.user.update({ where: { id: user.id }, data: { name: 'Ada' } });
}, { isolationLevel: 'Serializable' });- Methods:
findManyfindFirstfindUnique(andOrThrow),createcreateManyupdateupdateManyupsertdeletedeleteManycountaggregategroupBy. - Filters:
equalsnotinnotInltltegtgtecontainsstartsWithendsWith,mode: 'insensitive',ANDORNOT, andsomeeverynoneisisNoton relations. - Relations load with one batched query per level, so there is no N+1 problem. Cursor pagination and
distinctare supported. - Transactions: interactive or as an array of queries; nested transactions become savepoints;
isolationLevelon Postgres. - Raw SQL:
$queryRawand$executeRawas tagged templates, always parameterized.
Migrations
| Command | What it does |
|---|---|
facet migrate dev --name x | Creates a migration from schema changes, applies it and regenerates the client |
facet migrate deploy | Applies pending migrations (CI and production), under an advisory lock |
facet migrate status | Shows applied and pending migrations, and drift from them |
facet db pull | Writes schema.facet from an existing database, to adopt it |
facet migrate resolve --applied x | Marks a migration as applied without running it (baselining) |
Renaming a field or model migrates as drop and add, with a warning, so edit the SQL by hand for a rename.
Compared with Prisma
Facet covers the core workflow and most of the query API. It does not have scalar lists, implicit many-to-many relations, JSON path filters, full-text search, or MySQL, SQL Server and MongoDB support. Decimal values come back as strings and BigInt as bigint. See Prisma vs Facet and moving from Prisma.