CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-hibernatets

A TypeScript ORM library inspired by Hibernate for working with MySQL, MariaDB, and PostgreSQL databases using decorators and async/await patterns

Overview
Eval results
Files

entity-modeling.mddocs/

Entity Modeling

Database table and column mapping using TypeScript decorators. HibernateTS provides a comprehensive decorator system that allows you to define your data models with annotations that automatically generate the database schema and handle relationships.

Capabilities

Table Decorator

Marks a class as a database table and configures table-level options.

/**
 * Marks a class as a database table
 * @param opts - Table configuration options
 * @returns Class decorator
 */
function table(opts?: TableOptions): ClassDecorator;

interface TableOptions {
  /** Table name (defaults to lowercase class name) */
  name?: string;
  /** Database collation (defaults to "utf8mb4_general_ci") */
  collation?: string;
  /** Use prototype assignment for instance creation */
  usePrototypeAssignInsteadOf0ArgsConstructor?: boolean;
  /** Array of table constraints */
  constraints?: Constraint<any>[];
}

interface Constraint<TableClass> {
  /** Constraint type */
  type: "unique";
  /** Array of column names */
  columns: Array<keyof TableClass & string>;
}

Usage Examples:

import { table } from "hibernatets";

// Basic table mapping
@table()
export class User {
  // class properties...
}

// Custom table name and options
@table({
  name: "user_accounts",
  collation: "utf8mb4_unicode_ci",
  constraints: [{
    type: "unique",
    columns: ["email", "username"]
  }]
})
export class UserAccount {
  // class properties...
}

Column Decorator

Marks a property as a database column with customizable options for data types and constraints.

/**
 * Marks a property as a database column
 * @param opts - Column configuration options
 * @returns Property decorator
 */
function column(opts?: ColumnOptions): PropertyDecorator;

interface DBColumn {
  /** Column data type (binding uses primary Key type or BigInt as default) */
  type?: "text" | "number" | "boolean" | "date" | "binding";
  /** Column size specification */
  size?: "small" | "medium" | "large";
  /** Allow null values */
  nullable?: boolean;
  /** Default column value */
  default?: string;
}

interface ColumnOptions extends DBColumn {
  /** Custom data transformations */
  transformations?: Transformations<any, any>;
}

interface Transformations<T, U> {
  /** Transform data when loading from database to property */
  loadFromDbToProperty(dbData: U): Promise<T> | T;
  /** Transform data when saving from property to database */
  saveFromPropertyToDb(obj: T): Promise<U> | U;
}

Usage Examples:

import { table, column } from "hibernatets";

@table()
export class Product {
  @column()
  name: string;

  @column({ type: "number", nullable: false })
  price: number;

  @column({ type: "text", size: "large" })
  description: string;

  @column({ type: "boolean", default: true })
  active: boolean;

  @column({ type: "date" })
  createdAt: Date;

  // Custom transformation example
  @column({
    type: "text",
    transformations: {
      loadFromDbToProperty(dbData: string): string[] {
        return JSON.parse(dbData || "[]");
      },
      saveFromPropertyToDb(tags: string[]): string {
        return JSON.stringify(tags);
      }
    }
  })
  tags: string[];
}

Primary Key Decorator

Marks a property as the primary key with configurable generation strategies.

/**
 * Marks a property as the primary key
 * @param options - Primary key configuration options
 * @returns Property decorator
 */
function primary(options?: primaryOptions): PropertyDecorator;

interface primaryOptions extends ColumnOptions {
  /** Primary key generation strategy */
  strategy?: "auto-increment" | "custom";
}

Usage Examples:

import { table, column, primary } from "hibernatets";

@table()
export class User {
  // Auto-increment primary key (default)
  @primary()
  id: number;

  @column()
  name: string;
}

@table()
export class Document {
  // Custom primary key strategy
  @primary({ strategy: "custom" })
  uuid: string;

  @column()
  title: string;
}

Mapping Decorator

Defines relationships between entities with support for OneToOne and OneToMany mappings.

/**
 * Defines relationships between entities
 * @param type - Mapping type (OneToOne or OneToMany)
 * @param model - Target entity class or Promise of class
 * @param key - Foreign key field name or function
 * @param options - Mapping configuration options
 * @returns Property decorator
 */
function mapping(
  type: Mappings,
  model: any | Promise<any>,
  key?: string | ((obj: any) => any),
  options?: MappingOptions
): PropertyDecorator;

enum Mappings {
  /** One-to-many relationship (key on target object) */
  OneToMany = 0,
  /** One-to-one relationship (key on referencing object) */
  OneToOne = 1
}

interface MappingOptions extends DBColumn {
  /** Enable lazy loading for the relationship */
  lazyLoad?: boolean;
}

interface OneToManyMappingOptions extends MappingOptions {
  /** Load type configuration (defaults to "list") */
  loadType?: "list" | "map";
}

Usage Examples:

import { table, column, primary, mapping, Mappings } from "hibernatets";

@table()
export class User {
  @primary()
  id: number;

  @column()
  name: string;

  // One-to-many: User has many Posts
  @mapping(Mappings.OneToMany, Post, "userId")
  posts: Post[];

  // One-to-one: User has one Profile
  @mapping(Mappings.OneToOne, Profile, "userId")
  profile: Profile;
}

@table()
export class Post {
  @primary()
  id: number;

  @column()
  title: string;

  @column()
  userId: number;

  // One-to-one: Post belongs to User
  @mapping(Mappings.OneToOne, User, "id")
  user: User;
}

@table()
export class Profile {
  @primary()
  id: number;

  @column()
  bio: string;

  @column()
  userId: number;

  // Lazy loading example
  @mapping(Mappings.OneToOne, User, "id", { lazyLoad: true })
  user: User;
}

Reference Decorator

Marks a property as a reference key for relationship mapping.

/**
 * Marks a property as a reference key
 * @returns Property decorator
 */
function reference(): PropertyDecorator;

Usage Examples:

import { table, column, primary, reference, mapping, Mappings } from "hibernatets";

@table()
export class Order {
  @primary()
  id: number;

  @column()
  total: number;

  @reference()
  customerId: number;

  @mapping(Mappings.OneToOne, Customer, "id")
  customer: Customer;
}

@table()
export class Customer {
  @primary()
  id: number;

  @column()
  name: string;

  @mapping(Mappings.OneToMany, Order, "customerId")
  orders: Order[];
}

Advanced Relationship Examples

Complex relationship scenarios and advanced mapping patterns.

import { table, column, primary, mapping, Mappings } from "hibernatets";

// Self-referencing relationship
@table()
export class Category {
  @primary()
  id: number;

  @column()
  name: string;

  @column({ nullable: true })
  parentId: number;

  // Self-reference: Category has subcategories
  @mapping(Mappings.OneToMany, Category, "parentId")
  subcategories: Category[];

  // Parent category
  @mapping(Mappings.OneToOne, Category, "id")
  parent: Category;
}

// Many-to-many through junction table
@table()
export class UserRole {
  @primary()
  id: number;

  @column()
  userId: number;

  @column()
  roleId: number;

  @mapping(Mappings.OneToOne, User, "id")
  user: User;

  @mapping(Mappings.OneToOne, Role, "id")
  role: Role;
}

@table()
export class User {
  @primary()
  id: number;

  @column()
  name: string;

  @mapping(Mappings.OneToMany, UserRole, "userId")
  userRoles: UserRole[];
}

@table()
export class Role {
  @primary()
  id: number;

  @column()
  name: string;

  @mapping(Mappings.OneToMany, UserRole, "roleId")
  userRoles: UserRole[];
}

Database Configuration Access

Accessing the generated database configuration for entities.

/**
 * Configuration class for entity database mapping
 */
interface DataBaseConfig<T> {
  /** Primary key field name */
  modelPrimary: string;
  /** Database table name */
  table: string;
  /** Column definitions */
  columns: { [key: string]: ColumnDefinition<any> };
  /** Table options */
  options: TableOptions;
  /** Reference key field name */
  referenceKey: string;
  /** Creates new instance of entity */
  createInstance(): T;
}

interface ColumnDefinition<K> {
  /** Property name in model */
  modelName: string;
  /** Column name in database */
  dbTableName: string;
  /** Relationship mapping configuration */
  mapping?: any;
  /** Inverse relationship definitions */
  inverseMappingDef?: any;
  /** Primary key strategy */
  primaryType?: "auto-increment" | "custom";
  /** Column options */
  opts?: ColumnOptions;
}

Usage Examples:

import { getDBConfig } from "hibernatets";

@table({ name: "users" })
export class User {
  @primary()
  id: number;

  @column()
  name: string;
}

// Access database configuration
const config = getDBConfig(User);
console.log(config.table); // "users"
console.log(config.modelPrimary); // "id"
console.log(config.columns); // Column definitions

Install with Tessl CLI

npx tessl i tessl/npm-hibernatets

docs

configuration.md

data-operations.md

database-adapters.md

entity-modeling.md

index.md

sql-conditions.md

tile.json