or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-source.mdentity-definition.mdentity-schema.mdevents.mdfind-options.mdindex.mdmigrations.mdquery-builder.mdrelationships.mdrepository.md

index.mddocs/

0

# TypeORM

1

2

TypeORM is a comprehensive Object-Relational Mapping (ORM) library for TypeScript and JavaScript that supports both Data Mapper and Active Record patterns. It provides database abstraction for multiple database systems including MySQL/MariaDB, PostgreSQL, MS SQL Server, Oracle, SAP HANA, SQLite, and MongoDB, with features like entity management, repositories, migrations, transactions, associations, and query builders.

3

4

## Package Information

5

6

- **Package Name**: typeorm

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install typeorm`

10

11

## Core Imports

12

13

```typescript

14

import { DataSource, Entity, Column, PrimaryGeneratedColumn, Repository } from "typeorm";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { DataSource, Entity, Column, PrimaryGeneratedColumn, Repository } = require("typeorm");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import { DataSource, Entity, Column, PrimaryGeneratedColumn } from "typeorm";

27

28

// Define an entity

29

@Entity()

30

export class User {

31

@PrimaryGeneratedColumn()

32

id: number;

33

34

@Column()

35

name: string;

36

37

@Column()

38

email: string;

39

}

40

41

// Create a data source (connection)

42

const dataSource = new DataSource({

43

type: "postgres",

44

host: "localhost",

45

port: 5432,

46

username: "test",

47

password: "test",

48

database: "test",

49

entities: [User],

50

synchronize: true,

51

});

52

53

// Initialize and use

54

await dataSource.initialize();

55

const userRepository = dataSource.getRepository(User);

56

const user = await userRepository.save({ name: "John", email: "john@example.com" });

57

```

58

59

## Architecture

60

61

TypeORM is built around several key components:

62

63

- **DataSource**: Central connection management and configuration point

64

- **Entities**: Class-based models representing database tables using decorators

65

- **Repositories**: Data access layer providing CRUD operations and custom queries

66

- **Query Builder**: Fluent API for building complex SQL queries programmatically

67

- **Entity Manager**: Direct database operations interface with transaction support

68

- **Migration System**: Version control for database schema changes

69

- **Decorator System**: Extensive metadata definition using TypeScript decorators

70

71

## Capabilities

72

73

### Data Source Management

74

75

Central connection and configuration management for database interactions. Replaces the deprecated Connection API with enhanced features and cleaner architecture.

76

77

```typescript { .api }

78

class DataSource {

79

constructor(options: DataSourceOptions);

80

initialize(): Promise<DataSource>;

81

destroy(): Promise<void>;

82

getRepository<Entity>(target: EntityTarget<Entity>): Repository<Entity>;

83

getTreeRepository<Entity>(target: EntityTarget<Entity>): TreeRepository<Entity>;

84

transaction<T>(runInTransaction: (manager: EntityManager) => Promise<T>): Promise<T>;

85

query(query: string, parameters?: any[]): Promise<any>;

86

readonly isInitialized: boolean;

87

readonly manager: EntityManager;

88

}

89

90

type DataSourceOptions = MysqlConnectionOptions | PostgresConnectionOptions | SqliteConnectionOptions | MongoConnectionOptions | /* ... other database types */;

91

```

92

93

[Data Source Management](./data-source.md)

94

95

### Entity Definition

96

97

Comprehensive entity definition system using TypeScript decorators for defining database schemas, relationships, and constraints with compile-time type safety.

98

99

```typescript { .api }

100

function Entity(options?: EntityOptions): ClassDecorator;

101

function Column(options?: ColumnOptions): PropertyDecorator;

102

function PrimaryColumn(options?: ColumnOptions): PropertyDecorator;

103

function PrimaryGeneratedColumn(strategy?: "increment" | "identity" | "uuid", options?: ColumnOptions): PropertyDecorator;

104

function CreateDateColumn(options?: ColumnOptions): PropertyDecorator;

105

function UpdateDateColumn(options?: ColumnOptions): PropertyDecorator;

106

107

interface EntityOptions {

108

name?: string;

109

database?: string;

110

schema?: string;

111

engine?: string;

112

synchronize?: boolean;

113

orderBy?: Record<string, "ASC" | "DESC">;

114

}

115

```

116

117

[Entity Definition](./entity-definition.md)

118

119

### Relationship Management

120

121

Powerful relationship definition system supporting one-to-one, one-to-many, many-to-one, and many-to-many associations with advanced configuration options.

122

123

```typescript { .api }

124

function OneToOne<T>(typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), options?: RelationOptions): PropertyDecorator;

125

function OneToMany<T>(typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), inverseSide: string | ((object: T) => any), options?: RelationOptions): PropertyDecorator;

126

function ManyToOne<T>(typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), options?: RelationOptions): PropertyDecorator;

127

function ManyToMany<T>(typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), options?: RelationOptions): PropertyDecorator;

128

function JoinColumn(options?: JoinColumnOptions | JoinColumnOptions[]): PropertyDecorator;

129

function JoinTable(options?: JoinTableOptions): PropertyDecorator;

130

```

131

132

[Relationship Management](./relationships.md)

133

134

### Repository Pattern

135

136

Type-safe repository pattern implementation providing CRUD operations, custom queries, and specialized repositories for different data access patterns.

137

138

```typescript { .api }

139

class Repository<Entity> {

140

save<T extends DeepPartial<Entity>>(entity: T, options?: SaveOptions): Promise<T & Entity>;

141

save<T extends DeepPartial<Entity>>(entities: T[], options?: SaveOptions): Promise<(T & Entity)[]>;

142

findOne(options: FindOneOptions<Entity>): Promise<Entity | null>;

143

find(options?: FindManyOptions<Entity>): Promise<Entity[]>;

144

findBy(where: FindOptionsWhere<Entity>): Promise<Entity[]>;

145

remove(entity: Entity, options?: RemoveOptions): Promise<Entity>;

146

remove(entities: Entity[], options?: RemoveOptions): Promise<Entity[]>;

147

delete(criteria: string | string[] | number | number[] | Date | Date[] | ObjectID | ObjectID[] | FindOptionsWhere<Entity>): Promise<DeleteResult>;

148

createQueryBuilder(alias?: string): SelectQueryBuilder<Entity>;

149

}

150

151

class TreeRepository<Entity> extends Repository<Entity> {

152

findTrees(options?: FindTreeOptions): Promise<Entity[]>;

153

findAncestors(entity: Entity, options?: FindTreeOptions): Promise<Entity[]>;

154

findDescendants(entity: Entity, options?: FindTreeOptions): Promise<Entity[]>;

155

}

156

```

157

158

[Repository Pattern](./repository.md)

159

160

### Query Building

161

162

Powerful query builder providing fluent API for constructing complex SQL queries with type safety and database-agnostic syntax.

163

164

```typescript { .api }

165

class SelectQueryBuilder<Entity> {

166

select(selection?: string | string[]): SelectQueryBuilder<Entity>;

167

addSelect(selection: string | string[]): SelectQueryBuilder<Entity>;

168

where(where: string | ((qb: SelectQueryBuilder<Entity>) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;

169

andWhere(where: string | ((qb: SelectQueryBuilder<Entity>) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;

170

orWhere(where: string | ((qb: SelectQueryBuilder<Entity>) => string) | Brackets | ObjectLiteral | ObjectLiteral[], parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;

171

leftJoin(property: string, alias: string, condition?: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;

172

innerJoin(property: string, alias: string, condition?: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;

173

orderBy(sort: string | ((alias: string) => string), order?: "ASC" | "DESC", nulls?: "NULLS FIRST" | "NULLS LAST"): SelectQueryBuilder<Entity>;

174

groupBy(groupBy: string): SelectQueryBuilder<Entity>;

175

having(having: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;

176

limit(limit?: number): SelectQueryBuilder<Entity>;

177

offset(offset?: number): SelectQueryBuilder<Entity>;

178

getOne(): Promise<Entity | null>;

179

getMany(): Promise<Entity[]>;

180

getRawOne(): Promise<any>;

181

getRawMany(): Promise<any[]>;

182

}

183

```

184

185

[Query Building](./query-builder.md)

186

187

### Find Options & Operators

188

189

Type-safe find options system with powerful query operators for building complex where conditions without raw SQL.

190

191

```typescript { .api }

192

interface FindOneOptions<Entity = any> {

193

select?: FindOptionsSelect<Entity>;

194

where?: FindOptionsWhere<Entity>[] | FindOptionsWhere<Entity>;

195

relations?: FindOptionsRelations<Entity>;

196

order?: FindOptionsOrder<Entity>;

197

cache?: boolean | number | { id: any; milliseconds: number };

198

lock?: { mode: "optimistic"; version: number | Date } | { mode: "pessimistic_read" | "pessimistic_write" | "dirty_read" | "pessimistic_partial_write" | "pessimistic_write_or_fail" | "for_no_key_update" };

199

withDeleted?: boolean;

200

loadRelationIds?: boolean | FindOptionsRelationIds;

201

relationLoadStrategy?: "join" | "query";

202

}

203

204

function Equal(value: any): FindOperator<any>;

205

function Not(value: any): FindOperator<any>;

206

function LessThan(value: any): FindOperator<any>;

207

function MoreThan(value: any): FindOperator<any>;

208

function In(values: any[]): FindOperator<any>;

209

function Like(value: string): FindOperator<string>;

210

function Between(from: any, to: any): FindOperator<any>;

211

function IsNull(): FindOperator<any>;

212

```

213

214

[Find Options & Operators](./find-options.md)

215

216

### Migration System

217

218

Database schema version control system for managing database structure changes, data migrations, and deployment workflows.

219

220

```typescript { .api }

221

interface MigrationInterface {

222

up(queryRunner: QueryRunner): Promise<any>;

223

down(queryRunner: QueryRunner): Promise<any>;

224

}

225

226

class Migration {

227

constructor(id: number | string, timestamp: number, name: string, instance?: MigrationInterface);

228

readonly id: number | string;

229

readonly timestamp: number;

230

readonly name: string;

231

readonly instance?: MigrationInterface;

232

}

233

234

class MigrationExecutor {

235

executePendingMigrations(): Promise<Migration[]>;

236

undoLastMigration(): Promise<void>;

237

showMigrations(): Promise<boolean>;

238

}

239

```

240

241

[Migration System](./migrations.md)

242

243

### Entity Schema (Code-First)

244

245

Code-first entity definition system allowing dynamic entity creation without decorators, ideal for runtime schema generation.

246

247

```typescript { .api }

248

class EntitySchema<T = any> {

249

constructor(options: EntitySchemaOptions<T>);

250

readonly options: EntitySchemaOptions<T>;

251

}

252

253

interface EntitySchemaOptions<T> {

254

name: string;

255

target?: Function;

256

tableName?: string;

257

database?: string;

258

schema?: string;

259

columns: { [P in keyof T]: EntitySchemaColumnOptions };

260

relations?: { [key: string]: EntitySchemaRelationOptions };

261

indices?: EntitySchemaIndexOptions[];

262

uniques?: EntitySchemaUniqueOptions[];

263

checks?: EntitySchemaCheckOptions[];

264

exclusions?: EntitySchemaExclusionOptions[];

265

}

266

```

267

268

[Entity Schema](./entity-schema.md)

269

270

### Event System & Subscribers

271

272

Comprehensive entity lifecycle event system with hooks and subscribers for implementing cross-cutting concerns like auditing, validation, and caching.

273

274

```typescript { .api }

275

interface EntitySubscriberInterface<Entity = any> {

276

listenTo?(): ObjectType<Entity> | Function | string;

277

afterLoad?(entity: Entity, event?: LoadEvent<Entity>): Promise<any> | void;

278

beforeInsert?(event: InsertEvent<Entity>): Promise<any> | void;

279

afterInsert?(event: InsertEvent<Entity>): Promise<any> | void;

280

beforeUpdate?(event: UpdateEvent<Entity>): Promise<any> | void;

281

afterUpdate?(event: UpdateEvent<Entity>): Promise<any> | void;

282

beforeRemove?(event: RemoveEvent<Entity>): Promise<any> | void;

283

afterRemove?(event: RemoveEvent<Entity>): Promise<any> | void;

284

}

285

286

function EventSubscriber(): ClassDecorator;

287

function BeforeInsert(): MethodDecorator;

288

function AfterInsert(): MethodDecorator;

289

function BeforeUpdate(): MethodDecorator;

290

function AfterUpdate(): MethodDecorator;

291

function BeforeRemove(): MethodDecorator;

292

function AfterRemove(): MethodDecorator;

293

```

294

295

[Event System & Subscribers](./events.md)

296

297

## Core Types

298

299

```typescript { .api }

300

type EntityTarget<Entity> = ObjectType<Entity> | EntitySchema<Entity> | string;

301

type ObjectType<T> = { new (): T } | Function;

302

interface ObjectLiteral { [key: string]: any; }

303

type DeepPartial<T> = { [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]; };

304

305

enum DatabaseType {

306

"mysql" = "mysql",

307

"postgres" = "postgres",

308

"cockroachdb" = "cockroachdb",

309

"sqlite" = "sqlite",

310

"better-sqlite3" = "better-sqlite3",

311

"oracle" = "oracle",

312

"mssql" = "mssql",

313

"mongodb" = "mongodb"

314

}

315

```