Migrations

How migrations work

Once you get into production you'll need to synchronize model changes into the database. Typically it is unsafe to use synchronize: true for schema synchronization on production once you get data in your database. Here is where migrations come to help.
A migration is just a single file with sql queries to update a database schema and apply new changes to an existing database.
Let's say you already have a database and a post entity:
1
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
2
​
3
@Entity()
4
export class Post {
5
​
6
@PrimaryGeneratedColumn()
7
id: number;
8
​
9
@Column()
10
title: string;
11
​
12
@Column()
13
text: string;
14
​
15
}
Copied!
And your entity worked in production for months without any changes. You have thousands of posts in your database.
Now you need to make a new release and rename title to name. What would you do?
You need to create a new migration with the following SQL query (postgres dialect):
1
ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name";
Copied!
Once you run this SQL query your database schema is ready to work with your new codebase. TypeORM provides a place where you can write such sql queries and run them when needed. This place is called "migrations".

Creating a new migration

Pre-requisites: Installing CLI​
Before creating a new migration you need to setup your connection options properly:
1
{
2
"type": "mysql",
3
"host": "localhost",
4
"port": 3306,
5
"username": "test",
6
"password": "test",
7
"database": "test",
8
"entities": ["entity/*.js"],
9
"migrationsTableName": "custom_migration_table",
10
"migrations": ["migration/*.js"],
11
"cli": {
12
"migrationsDir": "migration"
13
}
14
}
Copied!
Here we setup three options:
  • "migrationsTableName": "migrations" - Specify this option only if you need migration table name to be different from "migrations".
  • "migrations": ["migration/*.js"] - indicates that typeorm must load migrations from the given "migration" directory.
  • "cli": { "migrationsDir": "migration" } - indicates that the CLI must create new migrations in the "migration" directory.
Once you setup connection options you can create a new migration using CLI:
1
typeorm migration:create -n PostRefactoring
Copied!
Here, PostRefactoring is the name of the migration - you can specify any name you want. After you run the command you can see a new file generated in the "migration" directory named {TIMESTAMP}-PostRefactoring.ts where {TIMESTAMP} is the current timestamp when the migration was generated. Now you can open the file and add your migration sql queries there.
You should see the following content inside your migration:
1
import {MigrationInterface, QueryRunner} from "typeorm";
2
​
3
export class PostRefactoringTIMESTAMP implements MigrationInterface {
4
​
5
async up(queryRunner: QueryRunner): Promise<void> {
6
​
7
}
8
​
9
async down(queryRunner: QueryRunner): Promise<void> {
10
​
11
}
12
​
13
​
14
}
Copied!
There are two methods you must fill with your migration code: up and down. up has to contain the code you need to perform the migration. down has to revert whatever up changed. down method is used to revert the last migration.
Inside both up and down you have a QueryRunner object. All database operations are executed using this object. Learn more about query runner.
Let's see what the migration looks like with our Post changes:
1
import {MigrationInterface, QueryRunner} from "typeorm";
2
​
3
export class PostRefactoringTIMESTAMP implements MigrationInterface {
4
​
5
async up(queryRunner: QueryRunner): Promise<void> {
6
await queryRunner.query(`ALTER TABLE "post" RENAME COLUMN "title" TO "name"`);
7
}
8
​
9
async down(queryRunner: QueryRunner): Promise<void> {
10
await queryRunner.query(`ALTER TABLE "post" RENAME COLUMN "name" TO "title"`); // reverts things made in "up" method
11
}
12
}
Copied!

Running and reverting migrations

Once you have a migration to run on production, you can run them using a CLI command:
1
typeorm migration:run
Copied!
typeorm migration:create and typeorm migration:generate will create .ts files, unless you use the o flag (see more in Generating migrations). The migration:run and migration:revert commands only work on .js files. Thus the typescript files need to be compiled before running the commands. Alternatively you can use ts-node in conjunction with typeorm to run .ts migration files.
Example with ts-node:
1
ts-node --transpile-only ./node_modules/typeorm/cli.js migration:run
Copied!
Example ts-node not using node_modules directly:
1
ts-node $(yarn bin typeorm) migration:run
Copied!
This command will execute all pending migrations and run them in a sequence ordered by their timestamps. This means all sql queries written in the up methods of your created migrations will be executed. That's all! Now you have your database schema up-to-date.
If for some reason you want to revert the changes, you can run:
1
typeorm migration:revert
Copied!
This command will execute down in the latest executed migration. If you need to revert multiple migrations you must call this command multiple times.

Generating migrations

TypeORM is able to automatically generate migration files with schema changes you made.
Let's say you have a Post entity with a title column, and you have changed the name title to name. You can run following command:
1
typeorm migration:generate -n PostRefactoring
Copied!
And it will generate a new migration called {TIMESTAMP}-PostRefactoring.ts with the following content:
1
import {MigrationInterface, QueryRunner} from "typeorm";
2
​
3
export class PostRefactoringTIMESTAMP implements MigrationInterface {
4
​
5
async up(queryRunner: QueryRunner): Promise<void> {
6
await queryRunner.query(`ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`);
7
}
8
​
9
async down(queryRunner: QueryRunner): Promise<void> {
10
await queryRunner.query(`ALTER TABLE "post" ALTER COLUMN "name" RENAME TO "title"`);
11
}
12
​
13
​
14
}
Copied!
Alternatively you can also output your migrations as Javascript files using the o (alias for --outputJs) flag. This is useful for Javascript only projects in which TypeScript additional packages are not installed. This command, will generate a new migration file {TIMESTAMP}-PostRefactoring.js with the following content:
1
const { MigrationInterface, QueryRunner } = require("typeorm");
2
​
3
module.exports = class PostRefactoringTIMESTAMP {
4
​
5
async up(queryRunner) {
6
await queryRunner.query(`ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`);
7
}
8
​
9
async down(queryRunner) {
10
await queryRunner.query(`ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`);
11
}
12
}
Copied!
See, you don't need to write the queries on your own. The rule of thumb for generating migrations is that you generate them after each change you made to your models. To apply multi-line formatting to your generated migration queries, use the p (alias for --pretty) flag.

Connection option

If you need to run/revert your migrations for another connection rather than the default, use the -c (alias for --connection) and pass the config name as an argument
1
typeorm -c <your-config-name> migration:{run|revert}
Copied!

Using migration API to write migrations

In order to use an API to change a database schema you can use QueryRunner.
Example:
1
import {MigrationInterface, QueryRunner, Table, TableIndex, TableColumn, TableForeignKey } from "typeorm";
2
​
3
export class QuestionRefactoringTIMESTAMP implements MigrationInterface {
4
​
5
async up(queryRunner: QueryRunner): Promise<void> {
6
await queryRunner.createTable(new Table({
7
name: "question",
8
columns: [
9
{
10
name: "id",
11
type: "int",
12
isPrimary: true
13
},
14
{
15
name: "name",
16
type: "varchar",
17
}
18
]
19
}), true)
20
​
21
await queryRunner.createIndex("question", new TableIndex({
22
name: "IDX_QUESTION_NAME",
23
columnNames: ["name"]
24
}));
25
​
26
await queryRunner.createTable(new Table({
27
name: "answer",
28
columns: [
29
{
30
name: "id",
31
type: "int",
32
isPrimary: true
33
},
34
{
35
name: "name",
36
type: "varchar",
37
},
38
{
39
name: 'created_at',
40
type: 'timestamp',
41
default: 'now()'
42
}
43
]
44
}), true);
45
​
46
await queryRunner.addColumn("answer", new TableColumn({
47
name: "questionId",
48
type: "int"
49
}));
50
​
51
await queryRunner.createForeignKey("answer", new TableForeignKey({
52
columnNames: ["questionId"],
53
referencedColumnNames: ["id"],
54
referencedTableName: "question",
55
onDelete: "CASCADE"
56
}));
57
}
58
​
59
async down(queryRunner: QueryRunner): Promise<void> {
60
const table = await queryRunner.getTable("answer");
61
const foreignKey = table.foreignKeys.find(fk => fk.columnNames.indexOf("questionId") !== -1);
62
await queryRunner.dropForeignKey("answer", foreignKey);
63
await queryRunner.dropColumn("answer", "questionId");
64
await queryRunner.dropTable("answer");
65
await queryRunner.dropIndex("question", "IDX_QUESTION_NAME");
66
await queryRunner.dropTable("question");
67
}
68
​
69
}
Copied!
​
1
getDatabases(): Promise<string[]>
Copied!
Returns all available database names including system databases.
​
1
getSchemas(database?: string): Promise<string[]>
Copied!
  • database - If database parameter specified, returns schemas of that database
Returns all available schema names including system schemas. Useful for SQLServer and Postgres only.
​
1
getTable(tableName: string): Promise<Table|undefined>
Copied!
  • tableName - name of a table to be loaded
Loads a table by a given name from the database.
​
1
getTables(tableNames: string[]): Promise<Table[]>
Copied!
  • tableNames - name of a tables to be loaded
Loads a tables by a given names from the database.
​
1
hasDatabase(database: string): Promise<boolean>
Copied!
  • database - name of a database to be checked
Checks if database with the given name exist.
​
1
hasSchema(schema: string): Promise<boolean>
Copied!
  • schema - name of a schema to be checked
Checks if schema with the given name exist. Used only for SqlServer and Postgres.
​
1
hasTable(table: Table|string): Promise<boolean>
Copied!
  • table - Table object or name
Checks if table exist.
​
1
hasColumn(table: Table|string, columnName: string): Promise<boolean>
Copied!
  • table - Table object or name
  • columnName - name of a column to be checked
Checks if column exist in the table.
​
1
createDatabase(database: string, ifNotExist?: boolean): Promise<void>
Copied!
  • database - database name
  • ifNotExist - skips creation if true, otherwise throws error if database already exist
Creates a new database.
​
1
dropDatabase(database: string, ifExist?: boolean): Promise<void>
Copied!
  • database - database name
  • ifExist - skips deletion if true, otherwise throws error if database was not found
Drops database.
​
1
createSchema(schemaPath: string, ifNotExist?: boolean): Promise<void>
Copied!
  • schemaPath - schema name. For SqlServer can accept schema path (e.g. 'dbName.schemaName') as parameter. If schema path passed, it will create schema in specified database
  • ifNotExist - skips creation if true, otherwise throws error if schema already exist
Creates a new table schema.
​
1
dropSchema(schemaPath: string, ifExist?: boolean, isCascade?: boolean): Promise<void>
Copied!
  • schemaPath - schema name. For SqlServer can accept schema path (e.g. 'dbName.schemaName') as parameter. If schema path passed, it will drop schema in specified database
  • ifExist - skips deletion if true, otherwise throws error if schema was not found
  • isCascade - If true, automatically drop objects (tables, functions, etc.) that are contained in the schema. Used only in Postgres.
Drops a table schema.
​
1
createTable(table: Table, ifNotExist?: boolean, createForeignKeys?: boolean, createIndices?: boolean): Promise<void>
Copied!
  • table - Table object.
  • ifNotExist - skips creation if true, otherwise throws error if table already exist. Default false
  • createForeignKeys - indicates whether foreign keys will be created on table creation. Default true
  • createIndices - indicates whether indices will be created on table creation. Default true
Creates a new table.
​
1
dropTable(table: Table|string, ifExist?: boolean, dropForeignKeys?: boolean, dropIndices?: boolean): Promise<void>
Copied!
  • table - Table object or table name to be dropped
  • ifExist - skips dropping if true, otherwise throws error if table does not exist
  • dropForeignKeys - indicates whether foreign keys will be dropped on table deletion. Default true
  • dropIndices - indicates whether indices will be dropped on table deletion. Default true
Drops a table.
​
1
renameTable(oldTableOrName: Table|string, newTableName: string): Promise<void>
Copied!
  • oldTableOrName - old Table object or name to be renamed
  • newTableName - new table name
Renames a table.
​
1
addColumn(table: Table|string, column: TableColumn): Promise<void>
Copied!
  • table - Table object or name
  • column - new column
Adds a new column.
​
1
addColumns(table: Table|string, columns: TableColumn[]): Promise<void>
Copied!
  • table - Table object or name
  • columns - new columns
Adds a new column.
​
1
renameColumn(table: Table|string, oldColumnOrName: TableColumn|string, newColumnOrName: TableColumn|string): Promise<void>
Copied!
  • table - Table object or name
  • oldColumnOrName - old column. Accepts TableColumn object or column name
  • newColumnOrName - new column. Accepts TableColumn object or column name
Renames a column.
​
1
changeColumn(table: Table|string, oldColumn: TableColumn|string, newColumn: TableColumn): Promise<void>
Copied!
  • table - Table object or name
  • oldColumn - old column. Accepts TableColumn object or column name
  • newColumn - new column. Accepts TableColumn object
Changes a column in the table.
​
1
changeColumns(table: Table|string, changedColumns: { oldColumn: TableColumn, newColumn: TableColumn }[]): Promise<void>
Copied!
  • table - Table object or name
  • changedColumns - array of changed columns.
    • oldColumn - old TableColumn object
    • newColumn - new TableColumn object
Changes a columns in the table.
​
1
dropColumn(table: Table|string, column: TableColumn|string): Promise<void>
Copied!
  • table - Table object or name
  • column - TableColumn object or column name to be dropped
Drops a column in the table.
​
1
dropColumns(table: Table|string, columns: TableColumn[]|string[]): Promise<void>
Copied!
  • table - Table object or name
  • columns - array of TableColumn objects or column names to be dropped
Drops a columns in the table.
​
1
createPrimaryKey(table: Table|string, columnNames: string[]): Promise<void>
Copied!
  • table - Table object or name
  • columnNames - array of column names which will be primary
Creates a new primary key.
​
1
updatePrimaryKeys(table: Table|string, columns: TableColumn[]): Promise<void>
Copied!
  • table - Table object or name
  • columns - array of TableColumn objects which will be updated
Updates composite primary keys.
​
1
dropPrimaryKey(table: Table|string): Promise<void>
Copied!
  • table - Table object or name
Drops a primary key.
​
1
createUniqueConstraint(table: Table|string, uniqueConstraint: TableUnique): Promise<void>
Copied!
  • table - Table object or name
  • uniqueConstraint - TableUnique object to be created
Creates new unique constraint.
Note: does not work for MySQL, because MySQL stores unique constraints as unique indices. Use createIndex() method instead.
​
1
createUniqueConstraints(table: Table|string, uniqueConstraints: TableUnique[]): Promise<void>
Copied!
  • table - Table object or name
  • uniqueConstraints - array of TableUnique objects to be created
Creates new unique constraints.
Note: does not work for MySQL, because MySQL stores unique constraints as unique indices. Use createIndices() method instead.
​
1
dropUniqueConstraint(table: Table|string, uniqueOrName: TableUnique|string): Promise<void>
Copied!
  • table - Table object or name
  • uniqueOrName - TableUnique object or unique constraint name to be dropped
Drops an unique constraint.
Note: does not work for MySQL, because MySQL stores unique constraints as unique indices. Use dropIndex() method instead.
​
1
dropUniqueConstraints(table: Table|string, uniqueConstraints: TableUnique[]): Promise<void>
Copied!
  • table - Table object or name
  • uniqueConstraints - array of TableUnique objects to be dropped
Drops an unique constraints.
Note: does not work for MySQL, because MySQL stores unique constraints as unique indices. Use dropIndices() method instead.
​
1
createCheckConstraint(table: Table|string, checkConstraint: TableCheck): Promise<void>
Copied!
  • table - Table object or name
  • checkConstraint - TableCheck object
Creates new check constraint.
Note: MySQL does not support check constraints.
​
1
createCheckConstraints(table: Table|string, checkConstraints: TableCheck[]): Promise<void>
Copied!
  • table - Table object or name
  • checkConstraints - array of TableCheck objects
Creates new check constraint.
Note: MySQL does not support check constraints.
​
1
dropCheckConstraint(table: Table|string, checkOrName: TableCheck|string): Promise<void>
Copied!
  • table - Table object or name
  • checkOrName - TableCheck object or check constraint name
Drops check constraint.
Note: MySQL does not support check constraints.
​
1
dropCheckConstraints(table: Table|string, checkConstraints: TableCheck[]): Promise<void>
Copied!
  • table - Table object or name
  • checkConstraints - array of TableCheck objects
Drops check constraints.
Note: MySQL does not support check constraints.
​
1
createForeignKey(table: Table|string, foreignKey: TableForeignKey): Promise<void>
Copied!
  • table - Table object or name
  • foreignKey - TableForeignKey object
Creates a new foreign key.
​
1
createForeignKeys(table: Table|string, foreignKeys: TableForeignKey[]): Promise<void>
Copied!
  • table - Table object or name
  • foreignKeys - array of TableForeignKey objects
Creates a new foreign keys.
​
1
dropForeignKey(table: Table|string, foreignKeyOrName: TableForeignKey|string): Promise<void>
Copied!
  • table - Table object or name
  • foreignKeyOrName - TableForeignKey object or foreign key name
Drops a foreign key.
​
1
dropForeignKeys(table: Table|string, foreignKeys: TableForeignKey[]): Promise<void>
Copied!
  • table - Table object or name
  • foreignKeys - array of TableForeignKey objects
Drops a foreign keys.
​
1
createIndex(table: Table|string, index: TableIndex): Promise<void>
Copied!
  • table - Table object or name
  • index - TableIndex object
Creates a new index.
​
1
createIndices(table: Table|string, indices: TableIndex[]): Promise<void>
Copied!
  • table - Table object or name
  • indices - array of TableIndex objects
Creates a new indices.
​
1
dropIndex(table: Table|string, index: TableIndex|string): Promise<void>
Copied!
  • table - Table object or name
  • index - TableIndex object or index name
Drops an index.
​
1
dropIndices(table: Table|string, indices: TableIndex[]): Promise<void>
Copied!
  • table - Table object or name
  • indices - array of TableIndex objects
Drops an indices.
​
1
clearTable(tableName: string): Promise<void>
Copied!
  • tableName - table name
Clears all table contents.
Note: this operation uses SQL's TRUNCATE query which cannot be reverted in transactions.
​
1
enableSqlMemory(): void
Copied!
Enables special query runner mode in which sql queries won't be executed, instead they will be memorized into a special variable inside query runner. You can get memorized sql using getMemorySql() method.
​
1
disableSqlMemory(): void
Copied!
Disables special query runner mode in which sql queries won't be executed. Previously memorized sql will be flushed.
​
1
clearSqlMemory(): void
Copied!
Flushes all memorized sql statements.
​
1
getMemorySql(): SqlInMemory
Copied!
  • returns SqlInMemory object with array of upQueries and downQueries sql statements
Gets sql stored in the memory. Parameters in the sql are already replaced.
​
1
executeMemoryUpSql(): Promise<void>
Copied!
Executes memorized up sql queries.
​
1
executeMemoryDownSql(): Promise<void>
Copied!
Executes memorized down sql queries.
​