alepha@docs:~/docs/packages/alepha$
cat orm.md
2 min read
Last commit:

#Alepha - Orm

#Installation

Part of the alepha package. Import from alepha/orm.

npm install alepha

#Overview

Postgres client based on Drizzle ORM, Alepha type-safe friendly.

ts
 1import { t } from "alepha"; 2import { $entity, $repository, db } from "alepha/postgres"; 3  4const users = $entity({ 5  name: "users", 6  schema: t.object({ 7    id: db.primaryKey(), 8    name: t.text(), 9    email: t.text(),10  }),11});12 13class App {14  users = $repository(users);15 16  getUserByName(name: string) {17    return this.users.findOne({ name: { eq: name } });18  }19}

This is not a full ORM, but rather a set of tools to work with Postgres databases in a type-safe way.

It provides:

  • A type-safe way to define entities and repositories. (via $entity and $repository)
  • Custom query builders and filters.
  • Built-in special columns like createdAt, updatedAt, deletedAt, version.
  • Automatic JSONB support.
  • Automatic synchronization of entities with the database schema (for testing and development).
  • Fallback to raw SQL via Drizzle ORM sql function.

Migrations are supported via Drizzle ORM, you need to use the drizzle-kit CLI tool to generate and run migrations.

#API Reference

#Primitives

Primitives are functions that define and configure various aspects of your application. They follow the convention of starting with $ and return configured primitive instances.

For more details, see the Primitives documentation.

#$entity()

Creates a database entity primitive that defines table structure using TypeBox schemas.

ts
 1import { t } from "alepha"; 2import { $entity } from "alepha/orm"; 3  4const userEntity = $entity({ 5  name: "users", 6  schema: t.object({ 7    id: pg.primaryKey(), 8    name: t.text(), 9    email: t.email(),10  }),11});

#$repository()

Get the repository for the given entity.

#$sequence()

Creates a PostgreSQL sequence primitive for generating unique numeric values.

#$transaction()

Creates a transaction primitive for database operations requiring atomicity and consistency.

This primitive provides a convenient way to wrap database operations in PostgreSQL transactions, ensuring ACID properties and automatic retry logic for version conflicts. It integrates seamlessly with the repository pattern and provides built-in handling for optimistic locking scenarios with automatic retry on version mismatches.

Important Notes:

  • All operations within the transaction handler are atomic
  • Automatic retry on PgVersionMismatchError for optimistic locking
  • Pass { tx } option to all repository operations within the transaction
  • Transactions are automatically rolled back on any unhandled error
  • Use appropriate isolation levels based on your consistency requirements
On This Page
No headings found...
ready
mainTypeScript
UTF-8packages_alepha_orm.md