Package Exports
- nukak-postgres
- nukak-postgres/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (nukak-postgres) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
nukak is the smartest ORM for TypeScript, it is designed to be fast, safe, and easy to integrate into any application.
It can run in Node.js, Browser, React Native, NativeScript, Expo, Electron, Deno, Bun, and much more!
Uses a consistent API for distinct databases, including PostgreSQL, MySQL, MariaDB, and SQLite (inspired by MongoDB glorious syntax).
const companyUsers = await userRepository.findMany({
$select: { email: true, profile: { $select: { picture: true } } },
$where: { email: { $endsWith: '@domain.com' } },
$sort: { createdAt: 'desc' },
$limit: 100,
});
Why nukak?
See this article in medium.com.
Features
- Type-safe and Context-aware queries: Squeeze the power of
TypeScriptfor auto-completion and validation of operators at any depth, including relations and their fields. - Context-Object SQL Generation: Uses a sophisticated
QueryContextpattern to ensure perfectly indexed placeholders ($1, $2, etc.) and robust SQL fragment management, even in the most complex sub-queries. - Unified API across Databases: Write once, run anywhere. Seamlessly switch between
PostgreSQL,MySQL,MariaDB,SQLite, and evenMongoDB. - Serializable JSON Syntax: Queries can be expressed as
100%validJSON, allowing them to be easily transported from frontend to backend. - Naming Strategies: Effortlessly translate between TypeScript
CamelCaseand databasesnake_case(or any custom format) with a pluggable system. - Built-in Serialization: A centralized task queue and
@Serialized()decorator ensure database operations are thread-safe and race-condition free by default. - Database Migrations: Integrated migration system for version-controlled schema management and auto-generation from entities.
- High Performance: Optimized "Sticky Connections" and human-readable, minimal SQL generation.
- Modern Architecture: Pure
ESMsupport, designed forNode.js,Bun,Deno, and even mobile/browser environments. - Rich Feature Set: Soft-delete, virtual fields, repositories, and automatic handling of
JSON,JSONB, andVectortypes.
1. Install
Install the core package:
npm install nukak --save
Install one of the specific adapters for your database:
| Database | Driver | Nukak Adapter |
|---|---|---|
PostgreSQL |
pg |
nukak-postgres |
SQLite |
sqlite sqlite3 |
nukak-sqlite |
MariaDB |
mariadb |
nukak-maria |
MySQL |
mysql2 |
nukak-mysql |
For example, for Postgres install the pg driver and the nukak-postgres adapter:
npm install pg nukak-postgres --saveAdditionally, your
tsconfig.jsonmay need the following flags:"target": "es2022", "experimentalDecorators": true, "emitDecoratorMetadata": true
2. Define the entities
Annotate your classes with decorators from nukak/entity. Nukak supports detailed schema metadata for precise DDL generation.
import { Entity, Id, Field, OneToOne, OneToMany, ManyToOne, ManyToMany } from 'nukak/entity';
import type { Relation } from 'nukak/type';
@Entity()
export class User {
@Id()
id?: string;
@Field({ length: 100, index: true })
name?: string;
@Field({ unique: true, comment: 'User login email' })
email?: string;
@OneToOne({ entity: () => Profile, mappedBy: 'user', cascade: true })
profile?: Relation<Profile>; // Relation<T> handles circular dependencies
@OneToMany({ entity: () => Post, mappedBy: 'author' })
posts?: Relation<Post>[];
}
@Entity()
export class Profile {
@Id()
id?: string;
@Field()
bio?: string;
@Field({ reference: () => User })
userId?: string;
@OneToOne({ entity: () => User })
user?: User;
}
@Entity()
export class Post {
@Id()
id?: number;
@Field()
title?: string;
@Field({ reference: () => User })
authorId?: string;
@ManyToOne({ entity: () => User })
author?: User;
@ManyToMany({ entity: () => Tag, through: () => PostTag })
tags?: Tag[];
}
@Entity()
export class Tag {
@Id()
id?: string;
@Field()
name?: string;
}
@Entity()
export class PostTag {
@Id()
id?: string;
@Field({ reference: () => Post })
postId?: number;
@Field({ reference: () => Tag })
tagId?: string;
}
3. Setup a querier-pool
A querier-pool can be set in any of the bootstrap files of your app (e.g. in the server.ts).
// file: ./shared/orm.ts
import { SnakeCaseNamingStrategy } from 'nukak';
import { PgQuerierPool } from 'nukak-postgres';
export const querierPool = new PgQuerierPool(
{
host: 'localhost',
user: 'theUser',
password: 'thePassword',
database: 'theDatabase',
min: 1,
max: 10,
},
// Optional extra options.
{
// Optional, any custom logger function can be passed here (optional).
logger: console.debug,
// Automatically translate between TypeScript camelCase and database snake_case.
// This affects both queries and schema generation.
namingStrategy: new SnakeCaseNamingStrategy()
},
);
4. Manipulate the data
Nukak provides multiple ways to interact with your data, from low-level Queriers to high-level Repositories.
Using Repositories (Recommended)
Repositories provide a clean, Data-Mapper style interface for your entities.
import { GenericRepository } from 'nukak/repository';
import { User } from './shared/models/index.js';
import { querierPool } from './shared/orm.js';
// Get a querier from the pool
const querier = await querierPool.getQuerier();
try {
const userRepository = new GenericRepository(User, querier);
// Advanced querying with relations and virtual fields
const users = await userRepository.findMany({
$select: {
id: true,
name: true,
profile: ['picture'], // Select specific fields from a 1-1 relation
tagsCount: true // Virtual field (calculated at runtime)
},
$where: {
email: { $iincludes: 'nukak' }, // Case-insensitive search
status: 'active'
},
$sort: { createdAt: -1 },
$limit: 50
});
} finally {
// Always release the querier to the pool
await querier.release();
}Advanced: Deep Selection & Filtering
Nukak's query syntax is context-aware. When you query a relation, the available fields and operators are automatically suggested and validated based on that related entity.
import { GenericRepository } from 'nukak/repository';
import { User } from './shared/models/index.js';
import { querierPool } from './shared/orm.js';
const authorsWithPopularPosts = await querierPool.transaction(async (querier) => {
const userRepository = new GenericRepository(User, querier);
return userRepository.findMany({
$select: {
id: true,
name: true,
profile: {
$select: ['bio'],
// Filter related record and enforce INNER JOIN
$where: { bio: { $ne: null } },
$required: true
},
posts: {
$select: ['title', 'createdAt'],
// Filter the related collection directly
$where: { title: { $iincludes: 'typescript' } },
$sort: { createdAt: -1 },
$limit: 5
}
},
$where: {
name: { $istartsWith: 'a' }
}
});
});Advanced: Virtual Fields & Raw SQL
Define complex logic directly in your entities using raw functions from nukak/util. These are highly efficient as they are resolved during SQL generation.
import { Entity, Id, Field } from 'nukak/entity';
import { raw } from 'nukak/util';
import { ItemTag } from './shared/models/index.js';
@Entity()
export class Item {
@Id()
id: number;
@Field()
name: string;
@Field({
virtual: raw(({ ctx, dialect, escapedPrefix }) => {
ctx.append('(');
dialect.count(ctx, ItemTag, {
$where: {
itemId: raw(({ ctx }) => ctx.append(`${escapedPrefix}.id`))
}
}, { autoPrefix: true });
ctx.append(')');
})
})
tagsCount?: number;
}Thread-Safe Transactions
Nukak ensures your operations are serialized and thread-safe.
import { User, Profile } from './shared/models/index.js';
import { querierPool } from './shared/orm.js';
const result = await querierPool.transaction(async (querier) => {
const user = await querier.findOne(User, { $where: { email: '...' } });
const profileId = await querier.insertOne(Profile, { userId: user.id, ... });
return { userId: user.id, profileId };
});
// Connection is automatically released after transaction
5. Migrations & Synchronization
Nukak provides a robust migration system and an "Entity-First" synchronization engine to manage your database schema changes.
Install the migration package:
npm install nukak-migrate --save
Create a
nukak.config.tsfor the CLI:import { PgQuerierPool } from 'nukak-postgres'; import { User, Post, Profile } from './src/entities/index.js'; import { SnakeCaseNamingStrategy } from 'nukak'; export default { querierPool: new PgQuerierPool({ /* config */ }), dialect: 'postgres', entities: [User, Post, Profile], namingStrategy: new SnakeCaseNamingStrategy(), migrationsPath: './migrations' };
Manage your schema via CLI:
# Generate a migration by comparing entities vs database npx nukak-migrate generate:entities initial_schema # Run pending migrations npx nukak-migrate up # Rollback the last migration npx nukak-migrate down
Entity-First Synchronization (Development)
In development, you can use autoSync to automatically keep your database in sync with your entities without manual migrations. It is safe by default, meaning it only adds missing tables and columns.
import { Migrator } from 'nukak-migrate';
import { querierPool } from './shared/orm.js';
const migrator = new Migrator(querierPool);
// Automatically sync changes on your entities with the DB tables/columns (recommended for development only)
const migrator = new Migrator(querierPool);
await migrator.autoSync({ logging: true });Check out the full nukak-migrate README for detailed CLI commands and advanced usage.
Check out the full documentation at nukak.org for details on:
- Complex Logical Operators
- Relationship Mapping (1-1, 1-M, M-M)
- Soft Deletes & Auditing
- Database Migration & Syncing
🛠 Deep Dive: Tests & Technical Resources
For those who want to see the "engine under the hood," check out these resources in the source code:
- Entity Mocks: See how complex entities and virtual fields are defined in entityMock.ts.
- Core Dialect Logic: The foundation of our context-aware SQL generation in abstractSqlDialect.ts.
- Comprehensive Test Suite:
- Abstract SQL Spec: The base test suite shared by all dialects.
- PostgreSQL Spec | MySQL Spec | SQLite Spec.
- Querier Integration Tests: Testing the interaction between SQL generation and connection management.
