0
# Data Source Management
1
2
Central connection and configuration management for database interactions. The DataSource class replaces the deprecated Connection API with enhanced features and cleaner architecture, providing a unified interface for database connection management across all supported database types.
3
4
## Capabilities
5
6
### DataSource Class
7
8
The main database connection class that manages database connections, provides access to repositories and entity managers, and handles initialization/cleanup.
9
10
```typescript { .api }
11
/**
12
* Main database connection class for TypeORM applications
13
*/
14
class DataSource {
15
/**
16
* Creates a new DataSource instance with the provided options
17
* @param options - Database connection configuration options
18
*/
19
constructor(options: DataSourceOptions);
20
21
/**
22
* Initializes the data source, establishes database connection
23
* @returns Promise resolving to the initialized DataSource instance
24
*/
25
initialize(): Promise<DataSource>;
26
27
/**
28
* Closes the database connection and cleans up resources
29
* @returns Promise resolving when connection is closed
30
*/
31
destroy(): Promise<void>;
32
33
/**
34
* Gets a repository for the specified entity
35
* @param target - Entity class, schema, or name
36
* @returns Repository instance for the entity
37
*/
38
getRepository<Entity>(target: EntityTarget<Entity>): Repository<Entity>;
39
40
/**
41
* Gets a tree repository for the specified entity
42
* @param target - Entity class, schema, or name
43
* @returns TreeRepository instance for hierarchical data
44
*/
45
getTreeRepository<Entity>(target: EntityTarget<Entity>): TreeRepository<Entity>;
46
47
/**
48
* Gets a MongoDB repository for the specified entity
49
* @param target - Entity class, schema, or name
50
* @returns MongoRepository instance for MongoDB operations
51
*/
52
getMongoRepository<Entity>(target: EntityTarget<Entity>): MongoRepository<Entity>;
53
54
/**
55
* Executes operations within a database transaction
56
* @param runInTransaction - Function to execute within transaction
57
* @returns Promise resolving to the transaction result
58
*/
59
transaction<T>(runInTransaction: (manager: EntityManager) => Promise<T>): Promise<T>;
60
61
/**
62
* Executes raw SQL query with optional parameters
63
* @param query - SQL query string
64
* @param parameters - Query parameters
65
* @returns Promise resolving to query results
66
*/
67
query(query: string, parameters?: any[]): Promise<any>;
68
69
/**
70
* Creates a query runner for advanced database operations
71
* @returns QueryRunner instance
72
*/
73
createQueryRunner(): QueryRunner;
74
75
/**
76
* Synchronizes database schema with entity definitions
77
* @param dropBeforeSync - Whether to drop existing database before sync
78
* @returns Promise resolving when synchronization completes
79
*/
80
synchronize(dropBeforeSync?: boolean): Promise<void>;
81
82
/**
83
* Drops the entire database
84
* @returns Promise resolving when database is dropped
85
*/
86
dropDatabase(): Promise<void>;
87
88
/**
89
* Runs pending database migrations
90
* @param options - Migration execution options
91
* @returns Promise resolving to array of executed migrations
92
*/
93
runMigrations(options?: MigrationRunOptions): Promise<Migration[]>;
94
95
/**
96
* Undoes the last executed migration
97
* @param options - Migration undo options
98
* @returns Promise resolving when migration is undone
99
*/
100
undoLastMigration(options?: MigrationUndoOptions): Promise<void>;
101
102
/**
103
* Lists all migrations and whether they have been run
104
* @returns Promise resolving to true if there are pending migrations
105
*/
106
showMigrations(): Promise<boolean>;
107
108
/**
109
* Gets metadata for the specified entity
110
* @param target - Entity class, schema, or name
111
* @returns Entity metadata for the target
112
*/
113
getMetadata(target: EntityTarget<any>): EntityMetadata;
114
115
/**
116
* Checks if metadata exists for the specified entity
117
* @param target - Entity class, schema, or name
118
* @returns True if metadata exists for the target
119
*/
120
hasMetadata(target: EntityTarget<any>): boolean;
121
122
/**
123
* Creates a new entity manager with optional query runner
124
* @param queryRunner - Optional query runner for transaction context
125
* @returns New EntityManager instance
126
*/
127
createEntityManager(queryRunner?: QueryRunner): EntityManager;
128
129
/**
130
* Creates a generic query builder for custom SQL operations
131
* @param queryRunner - Optional query runner for transaction context
132
* @returns SelectQueryBuilder instance for custom queries
133
*/
134
createQueryBuilder(queryRunner?: QueryRunner): SelectQueryBuilder<any>;
135
136
/** Whether the data source has been initialized */
137
readonly isInitialized: boolean;
138
139
/** The EntityManager instance for this data source */
140
readonly manager: EntityManager;
141
142
/** The configured database driver */
143
readonly driver: Driver;
144
145
/** Connection options used to create this data source */
146
readonly options: DataSourceOptions;
147
}
148
```
149
150
**Usage Examples:**
151
152
```typescript
153
import { DataSource } from "typeorm";
154
import { User, Post } from "./entities";
155
156
// PostgreSQL connection
157
const dataSource = new DataSource({
158
type: "postgres",
159
host: "localhost",
160
port: 5432,
161
username: "myuser",
162
password: "mypassword",
163
database: "mydatabase",
164
entities: [User, Post],
165
synchronize: false,
166
logging: true,
167
});
168
169
// Initialize connection
170
await dataSource.initialize();
171
172
// Get repositories
173
const userRepository = dataSource.getRepository(User);
174
const postRepository = dataSource.getRepository(Post);
175
176
// Execute transaction
177
await dataSource.transaction(async manager => {
178
const user = await manager.save(User, { name: "John" });
179
const post = await manager.save(Post, { title: "Hello", author: user });
180
});
181
182
// Raw query
183
const results = await dataSource.query(
184
"SELECT * FROM users WHERE age > $1",
185
[18]
186
);
187
188
// Cleanup
189
await dataSource.destroy();
190
```
191
192
### DataSource Options
193
194
Configuration options for different database types, providing type-safe configuration for each supported database system.
195
196
```typescript { .api }
197
/**
198
* Union type of all supported database connection options
199
*/
200
type DataSourceOptions =
201
| MysqlConnectionOptions
202
| PostgresConnectionOptions
203
| SqliteConnectionOptions
204
| BetterSqlite3ConnectionOptions
205
| CockroachConnectionOptions
206
| OracleConnectionOptions
207
| MssqlConnectionOptions
208
| MongoConnectionOptions
209
| AuroraDataApiConnectionOptions
210
| AuroraDataApiPostgresConnectionOptions
211
| AuroraDataApiMysqlConnectionOptions
212
| SapConnectionOptions
213
| SpannerConnectionOptions;
214
215
/**
216
* Base connection options shared across all database types
217
*/
218
interface BaseConnectionOptions {
219
/** Database type identifier */
220
type: DatabaseType;
221
222
/** Custom connection name for multiple connections */
223
name?: string;
224
225
/** Array of entity classes to be used with this connection */
226
entities?: (ObjectType<any> | EntitySchema<any> | string)[];
227
228
/** Array of subscriber classes */
229
subscribers?: (ObjectType<any> | string)[];
230
231
/** Array of migration classes */
232
migrations?: (ObjectType<any> | string)[];
233
234
/** Logger configuration */
235
logger?: "advanced-console" | "simple-console" | "file" | "debug" | Logger;
236
237
/** Enable/disable logging */
238
logging?: boolean | "all" | ("query" | "schema" | "error" | "warn" | "info" | "log" | "migration")[];
239
240
/** Auto schema synchronization (dev only) */
241
synchronize?: boolean;
242
243
/** Drop schema on connection */
244
dropSchema?: boolean;
245
246
/** Run migrations automatically */
247
migrationsRun?: boolean;
248
249
/** Enable connection pooling */
250
pool?: {
251
max?: number;
252
min?: number;
253
acquire?: number;
254
idle?: number;
255
};
256
257
/** Connection timeout in milliseconds */
258
connectTimeoutMS?: number;
259
260
/** Extra connection options */
261
extra?: any;
262
}
263
264
/**
265
* PostgreSQL specific connection options
266
*/
267
interface PostgresConnectionOptions extends BaseConnectionOptions {
268
type: "postgres";
269
host?: string;
270
port?: number;
271
username?: string;
272
password?: string | (() => string) | (() => Promise<string>);
273
database?: string;
274
schema?: string;
275
ssl?: boolean | TlsOptions;
276
uuidExtension?: "uuid-ossp" | "pgcrypto";
277
logNotifications?: boolean;
278
installExtensions?: boolean;
279
applicationName?: string;
280
replication?: {
281
master: {
282
host: string;
283
port: number;
284
username: string;
285
password: string;
286
database: string;
287
};
288
slaves: {
289
host: string;
290
port: number;
291
username: string;
292
password: string;
293
database: string;
294
}[];
295
};
296
}
297
298
/**
299
* MySQL specific connection options
300
*/
301
interface MysqlConnectionOptions extends BaseConnectionOptions {
302
type: "mysql" | "mariadb";
303
host?: string;
304
port?: number;
305
username?: string;
306
password?: string | (() => string) | (() => Promise<string>);
307
database?: string;
308
charset?: string;
309
timezone?: string;
310
connectTimeout?: number;
311
acquireTimeout?: number;
312
timeout?: number;
313
ssl?: string | (tls.SecureContextOptions & { rejectUnauthorized?: boolean });
314
socketPath?: string;
315
debug?: boolean;
316
trace?: boolean;
317
multipleStatements?: boolean;
318
flags?: string;
319
bigNumberStrings?: boolean;
320
dateStrings?: boolean | string[];
321
supportBigNumbers?: boolean;
322
legacySpatialSupport?: boolean;
323
}
324
```
325
326
**Configuration Examples:**
327
328
```typescript
329
// PostgreSQL with SSL
330
const postgresConfig: DataSourceOptions = {
331
type: "postgres",
332
host: "localhost",
333
port: 5432,
334
username: "user",
335
password: "password",
336
database: "mydb",
337
ssl: {
338
rejectUnauthorized: false,
339
ca: fs.readFileSync("ca-certificate.crt").toString(),
340
},
341
entities: ["src/entities/*.ts"],
342
synchronize: false,
343
logging: ["error", "warn"],
344
pool: {
345
max: 20,
346
min: 5,
347
}
348
};
349
350
// MySQL with multiple statements
351
const mysqlConfig: DataSourceOptions = {
352
type: "mysql",
353
host: "localhost",
354
port: 3306,
355
username: "root",
356
password: "password",
357
database: "test",
358
charset: "utf8mb4",
359
timezone: "+00:00",
360
multipleStatements: true,
361
entities: [User, Post],
362
migrations: ["src/migrations/*.ts"],
363
migrationsRun: true,
364
};
365
366
// SQLite for development
367
const sqliteConfig: DataSourceOptions = {
368
type: "sqlite",
369
database: ":memory:", // or "path/to/database.sqlite"
370
entities: [User, Post],
371
synchronize: true,
372
logging: true,
373
};
374
```
375
376
### Migration Types
377
378
```typescript { .api }
379
/**
380
* Options for running migrations
381
*/
382
interface MigrationRunOptions {
383
/** Transaction mode: "all" | "none" | "each" */
384
transaction?: "all" | "none" | "each";
385
/** Whether to run migrations in fake mode */
386
fake?: boolean;
387
}
388
389
/**
390
* Options for undoing migrations
391
*/
392
interface MigrationUndoOptions {
393
/** Transaction mode: "all" | "none" | "each" */
394
transaction?: "all" | "none" | "each";
395
/** Whether to undo migrations in fake mode */
396
fake?: boolean;
397
}
398
```
399
400
### Connection Management Utilities
401
402
Helper classes and functions for advanced connection scenarios and legacy compatibility.
403
404
```typescript { .api }
405
/**
406
* @deprecated Use DataSource instead
407
* Legacy Connection class for backward compatibility
408
*/
409
class Connection {
410
/** @deprecated Use DataSource.initialize() instead */
411
connect(): Promise<Connection>;
412
/** @deprecated Use DataSource.destroy() instead */
413
close(): Promise<void>;
414
/** @deprecated Use DataSource.getRepository() instead */
415
getRepository<Entity>(target: EntityTarget<Entity>): Repository<Entity>;
416
}
417
418
/**
419
* @deprecated Use DataSource instead
420
* Legacy connection manager for multiple connections
421
*/
422
class ConnectionManager {
423
/** @deprecated Create DataSource instances directly */
424
create(options: ConnectionOptions): Connection;
425
/** @deprecated Use DataSource.getRepository() directly */
426
get(name?: string): Connection;
427
}
428
429
/**
430
* Reads connection configuration from files
431
* Supports ormconfig.json, ormconfig.js, ormconfig.env, etc.
432
*/
433
class ConnectionOptionsReader {
434
/**
435
* Reads all connection options from configuration files
436
* @returns Promise resolving to array of connection options
437
*/
438
all(): Promise<DataSourceOptions[]>;
439
440
/**
441
* Gets connection options by name
442
* @param name - Connection name to retrieve
443
* @returns Promise resolving to connection options
444
*/
445
get(name: string): Promise<DataSourceOptions>;
446
}
447
```
448
449
## Database Support
450
451
TypeORM supports the following database systems:
452
453
- **PostgreSQL** - Full feature support including arrays, JSON, and PostGIS
454
- **MySQL/MariaDB** - Complete MySQL 5.7+ and MariaDB support
455
- **SQLite** - Lightweight embedded database support
456
- **Microsoft SQL Server** - Enterprise database support
457
- **Oracle** - Enterprise Oracle database support
458
- **MongoDB** - NoSQL document database support (limited ORM features)
459
- **SAP HANA** - In-memory database support
460
- **CockroachDB** - Distributed PostgreSQL-compatible database
461
- **Amazon Aurora** - MySQL and PostgreSQL compatible cloud database
462
463
Each database type has specific configuration options and may support different feature subsets of the TypeORM API.