CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-typeorm

Data-Mapper ORM for TypeScript and ES2021+ supporting MySQL/MariaDB, PostgreSQL, MS SQL Server, Oracle, SAP HANA, SQLite, MongoDB databases.

Overview
Eval results
Files

entity-definition.mddocs/

Entity Definition

Comprehensive entity definition system using TypeScript decorators for defining database schemas, relationships, and constraints with compile-time type safety. TypeORM's decorator-based approach provides a clean and intuitive way to map TypeScript classes to database tables.

Capabilities

Core Entity Decorators

Basic decorators for defining entities and their core properties.

/**
 * Marks a class as a database entity (table)
 * @param options - Entity configuration options
 */
function Entity(options?: EntityOptions): ClassDecorator;

/**
 * Marks a class as a child entity in table inheritance
 * @param discriminatorValue - Value used to identify this child type
 */
function ChildEntity(discriminatorValue?: any): ClassDecorator;

/**
 * Configures table inheritance strategy for an entity
 * @param options - Inheritance configuration
 */
function TableInheritance(options: TableInheritanceOptions): ClassDecorator;

/**
 * Marks a class as a database view entity
 * @param options - View entity configuration
 */
function ViewEntity(options: ViewEntityOptions): ClassDecorator;

interface EntityOptions {
  /** Custom table name (defaults to class name) */
  name?: string;
  /** Database name (for multi-database setups) */
  database?: string;
  /** Schema name (for databases supporting schemas) */
  schema?: string;
  /** Storage engine (MySQL specific) */
  engine?: string;
  /** Whether to synchronize this entity */
  synchronize?: boolean;
  /** Default ordering for queries */
  orderBy?: Record<string, "ASC" | "DESC">;
  /** Entity comment */
  comment?: string;
}

interface TableInheritanceOptions {
  /** Inheritance pattern: single-table or joined-table */
  pattern: "STI" | "CTI";
  /** Column name for discriminator (STI only) */
  column?: string;
}

Usage Examples:

import { Entity, ChildEntity, TableInheritance } from "typeorm";

// Basic entity
@Entity("users")
export class User {
  // ... properties
}

// Entity with custom options
@Entity({
  name: "user_profiles",
  schema: "public",
  orderBy: {
    createdAt: "DESC"
  },
  comment: "User profile information"
})
export class UserProfile {
  // ... properties
}

// Table inheritance - parent class
@Entity()
@TableInheritance({ column: "type", pattern: "STI" })
export class Content {
  @Column({ type: "varchar" })
  type: string;
  // ... common properties
}

// Child entities
@ChildEntity("article")
export class Article extends Content {
  // ... article-specific properties
}

@ChildEntity("video")
export class Video extends Content {
  // ... video-specific properties
}

Column Decorators

Decorators for defining table columns with various data types and constraints.

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

/**
 * Marks a property as a primary key column
 * @param options - Primary column options
 */
function PrimaryColumn(options?: ColumnOptions): PropertyDecorator;

/**
 * Marks a property as an auto-generated primary key column
 * @param strategy - Generation strategy: "increment", "identity", "uuid", "rowid"
 * @param options - Column options
 */
function PrimaryGeneratedColumn(
  strategy?: "increment" | "identity" | "uuid" | "rowid",
  options?: ColumnOptions
): PropertyDecorator;

/**
 * Automatically sets creation timestamp
 * @param options - Column options
 */
function CreateDateColumn(options?: ColumnOptions): PropertyDecorator;

/**
 * Automatically sets update timestamp
 * @param options - Column options
 */
function UpdateDateColumn(options?: ColumnOptions): PropertyDecorator;

/**
 * Timestamp column for soft deletes
 * @param options - Column options
 */
function DeleteDateColumn(options?: ColumnOptions): PropertyDecorator;

/**
 * Version column for optimistic locking
 * @param options - Column options
 */
function VersionColumn(options?: ColumnOptions): PropertyDecorator;

/**
 * Virtual/computed column that doesn't exist in database
 * @param options - Virtual column options
 */
function VirtualColumn(options?: VirtualColumnOptions): PropertyDecorator;

/**
 * Column specifically for database views
 * @param options - View column options
 */
function ViewColumn(options?: ColumnOptions): PropertyDecorator;

/**
 * MongoDB ObjectId column
 * @param options - Column options
 */
function ObjectIdColumn(options?: ColumnOptions): PropertyDecorator;

interface ColumnOptions {
  /** Column data type */
  type?: ColumnType;
  /** Column name in database */
  name?: string;
  /** Column length (for string types) */
  length?: number;
  /** Column precision (for decimal types) */
  precision?: number;
  /** Column scale (for decimal types) */
  scale?: number;
  /** Whether column allows NULL values */
  nullable?: boolean;
  /** Default column value */
  default?: any;
  /** Column comment */
  comment?: string;
  /** Whether column is primary key */
  primary?: boolean;
  /** Whether column is unique */
  unique?: boolean;
  /** Column charset (MySQL specific) */
  charset?: string;
  /** Column collation */
  collation?: string;
  /** Value transformer for serialization/deserialization */
  transformer?: ValueTransformer | ValueTransformer[];
  /** Whether to select this column by default */
  select?: boolean;
  /** Whether to insert this column */
  insert?: boolean;
  /** Whether to update this column */
  update?: boolean;
  /** Array type (PostgreSQL specific) */
  array?: boolean;
  /** Enum values (for enum columns) */
  enum?: Object | (string | number)[];
  /** PostgreSQL-specific options */
  hstoreType?: "object" | "string";
}

Usage Examples:

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn,
  VersionColumn
} from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({
    type: "varchar",
    length: 100,
    nullable: false,
    comment: "User's full name"
  })
  name: string;

  @Column({
    type: "varchar",
    length: 255,
    unique: true,
    transformer: {
      to: (value: string) => value.toLowerCase(),
      from: (value: string) => value
    }
  })
  email: string;

  @Column({
    type: "int",
    default: 0,
    unsigned: true
  })
  loginCount: number;

  @Column({
    type: "enum",
    enum: ["active", "inactive", "pending"],
    default: "pending"
  })
  status: "active" | "inactive" | "pending";

  @Column({
    type: "text",
    nullable: true
  })
  bio?: string;

  @Column({
    type: "decimal",
    precision: 10,
    scale: 2,
    default: 0
  })
  balance: number;

  // PostgreSQL array column
  @Column({
    type: "text",
    array: true,
    default: () => "ARRAY[]::text[]"
  })
  tags: string[];

  // JSON column
  @Column({
    type: "jsonb",
    nullable: true
  })
  metadata?: Record<string, any>;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  @DeleteDateColumn()
  deletedAt?: Date;

  @VersionColumn()
  version: number;
}

Constraint and Index Decorators

Decorators for defining database constraints and indexes for data integrity and performance.

/**
 * Creates a database index on the decorated property
 * @param options - Index configuration options
 */
function Index(options?: IndexOptions): PropertyDecorator;

/**
 * Creates a database index with custom name and configuration
 * @param name - Index name
 * @param options - Index configuration options
 */
function Index(name: string, options?: IndexOptions): PropertyDecorator;

/**
 * Creates a unique constraint on the decorated property
 * @param options - Unique constraint options
 */
function Unique(options?: UniqueOptions): PropertyDecorator;

/**
 * Creates a unique constraint with custom name
 * @param name - Constraint name
 * @param columns - Column names for composite unique constraint
 */
function Unique(name: string, columns: string[]): ClassDecorator;

/**
 * Creates a check constraint on the entity
 * @param name - Constraint name
 * @param expression - SQL expression for the check
 */
function Check(name: string, expression: string): ClassDecorator;

/**
 * Creates an exclusion constraint (PostgreSQL specific)
 * @param name - Constraint name
 * @param expression - Exclusion expression
 */
function Exclusion(name: string, expression: string): ClassDecorator;

/**
 * Marks a column value as generated by the database
 * @param strategy - Generation strategy: "increment", "uuid", "rowid"
 */
function Generated(strategy?: "increment" | "uuid" | "rowid"): PropertyDecorator;

interface IndexOptions {
  /** Index name */
  name?: string;
  /** Whether index is unique */
  unique?: boolean;
  /** Spatial index (MySQL specific) */
  spatial?: boolean;
  /** Full-text index (MySQL specific) */
  fulltext?: boolean;
  /** Index method (PostgreSQL specific) */
  using?: string;
  /** Partial index condition (PostgreSQL specific) */
  where?: string;
  /** Index columns for composite index */
  columns?: string[];
  /** Whether to synchronize this index */
  synchronize?: boolean;
}

Usage Examples:

import { Entity, Column, Index, Unique, Check, Generated } from "typeorm";

@Entity()
@Index(["email", "status"]) // Composite index on class
@Unique("UQ_USER_EMAIL_DOMAIN", ["email", "domain"])
@Check("CHK_USER_AGE", "age >= 0 AND age <= 150")
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Index() // Simple index
  email: string;

  @Column()
  @Index("IDX_USER_STATUS") // Named index
  status: string;

  @Column()
  @Unique() // Unique constraint
  username: string;

  @Column()
  @Index({ unique: true, name: "IDX_USER_SSN" }) // Unique index
  ssn: string;

  @Column()
  age: number;

  @Column()
  domain: string;

  // PostgreSQL specific examples
  @Column({ type: "tsvector" })
  @Index({ using: "gin" }) // GIN index for full-text search
  searchVector: string;

  @Column()
  @Generated("uuid")
  uuid: string;

  // Partial index (PostgreSQL)
  @Column()
  @Index({
    where: "active = true",
    name: "IDX_ACTIVE_USERS_EMAIL"
  })
  active: boolean;
}

Embedded and Composite Types

Support for embedded objects and composite types for better data organization.

/**
 * Embeds properties of another class into this entity
 * @param type - Class to embed
 * @param options - Embedded options
 */
function Embedded(
  type: () => Function,
  options?: EmbeddedOptions
): PropertyDecorator;

/**
 * Marks a class as embeddable
 */
function Embeddable(): ClassDecorator;

interface EmbeddedOptions {
  /** Prefix for embedded columns */
  prefix?: string | boolean;
  /** Array of embedded objects */
  array?: boolean;
}

Usage Examples:

import { Entity, Column, Embedded, Embeddable } from "typeorm";

// Embeddable class
@Embeddable()
export class Address {
  @Column()
  street: string;

  @Column()
  city: string;

  @Column()
  state: string;

  @Column()
  zipCode: string;

  @Column()
  country: string;
}

@Embeddable()
export class Name {
  @Column()
  first: string;

  @Column()
  last: string;
}

// Entity using embedded types
@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Embedded(() => Name)
  name: Name;

  @Embedded(() => Address, { prefix: "home_" })
  homeAddress: Address;

  @Embedded(() => Address, { prefix: "work_" })
  workAddress: Address;
}

// Results in columns: id, nameFirst, nameLast, home_street, home_city, etc.

Column Types

TypeORM supports a wide range of column types across different databases:

Common Types

  • int, integer, tinyint, smallint, mediumint, bigint
  • float, double, decimal, numeric
  • char, varchar, text, tinytext, mediumtext, longtext
  • boolean, bool
  • date, time, datetime, timestamp
  • json, jsonb (PostgreSQL)
  • enum
  • uuid
  • blob, longblob, bytea

Database-Specific Types

  • PostgreSQL: array, hstore, ltree, point, line, polygon, geometry, geography
  • MySQL: year, bit, geometry, point, linestring, polygon
  • MongoDB: objectid
  • SQL Server: nchar, nvarchar, ntext, xml, uniqueidentifier

Each column type has specific options and validation rules depending on the target database system.

Install with Tessl CLI

npx tessl i tessl/npm-typeorm

docs

data-source.md

entity-definition.md

entity-schema.md

events.md

find-options.md

index.md

migrations.md

query-builder.md

relationships.md

repository.md

tile.json