Bruno Negrão Zica
Bruno Negrão Zica

Reputation: 814

How to add a new column to an existing entity with typeorm

I am starting to study typeorm and I am confused about what happens if I add a new column to an existing entity that was already persisted with data. I use SQlite.

I saw in the documentation, in the "Migrations" section, it looks like there is a procedure that must be done if I want to add a new column.

But when I saw this issue in typeorm's github, I understood that if I just add the new "@Column" annotated property to the Entity class would be enough and typeorm would create the column automatically when the app starts.

I was really hoping that typeorm would be able to handle that schema change automatically.

Can someone help?

Upvotes: 4

Views: 22810

Answers (2)

vugen
vugen

Reputation: 11

I had to create new migration, which will add new column "is_delete" in table users between column "password" and "created_at"

I created new migration file. After this in public async up i inserted:

await queryRunner.query(`ALTER TABLE \`users\` ADD \`is_delete\` int NOT NULL DEFAULT '0' AFTER \`password\` `);

Maybe for someone it will be useful

Upvotes: 1

Sascha
Sascha

Reputation: 1849

TypeOrm is capable of changing the schema but is does not run migrations automatically on server start (this is not a wanted behaviour). If you want the migrations to be executed when the app the starts you need to todo the following to steps:

  1. Create migration file:

After changing your entity (like adding a new column) you need to generate a migration file:

typeorm migration:generate -c 'connectionName'

That migration file is then created into a folder configured in your ormconfig.json.

  1. Run migrations

Before you start your server, you need to create the database connection and run the migrations. So your main file should look like

import { Connection, getConnectionManager } from 'typeorm';

const connectionManager = getConnectionManager();
const connection = connectionManager.get(connectionName);
await connection.runMigrations();

// start your server
startServer();

For development purpose you can also use schema synchronization, in that case typeorm syncs your database with your entity:

npx typeorm schema:sync -c 'connectionName'

Upvotes: 9

Related Questions