typeorm/docs/sequelize-migration.md
2017-10-04 13:13:22 +02:00

5.7 KiB

Migration from Sequelize to TypeORM

Setting up a connection

In sequelize you create a connection this way:

const sequelize = new Sequelize("database", "username", "password", {
  host: "localhost",
  dialect: "mysql"
});

sequelize
  .authenticate()
  .then(() => {
    console.log("Connection has been established successfully.");
  })
  .catch(err => {
    console.error("Unable to connect to the database:", err);
  });

In TypeORM you create a connection like this:

import {createConnection} from "typeorm";

createConnection({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password"
}).then(connection => {
    console.log("Connection has been established successfully.");
})
.catch(err => {
    console.error("Unable to connect to the database:", err);
});

Then you can get your connection instance from anywhere in your app using getConnection.

Schema synchronization

In sequelize you do schema synchronization this way:

Project.sync({force: true});
Task.sync({force: true});

In TypeORM you just add synchronize: true in the connection options:

createConnection({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password",
    synchronize: true
});

Creating a models

This is how models are defined in sequelize:

module.exports = function(sequelize, DataTypes) {

    const Project = sequelize.define("project", {
      title: DataTypes.STRING,
      description: DataTypes.TEXT
    });
    
    return Project;

};
module.exports = function(sequelize, DataTypes) {

    const Task = sequelize.define("task", {
      title: DataTypes.STRING,
      description: DataTypes.TEXT,
      deadline: DataTypes.DATE
    });
    
    return Task;
};

In TypeORM these models are called entities and you can define them like this:

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

@Entity()
export class Project {
    
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column()
    title: string;
    
    @Column()
    description: string;
    
}
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class Task {
    
    @PrimaryGeneratedColumn()
    id: number;
    
    @Column()
    title: string;
    
    @Column("text")
    description: string;
    
    @Column()
    deadline: Date;
    
}

Its highly recommended to define one entity class per file. TypeORM allows you to use your classes as database models and provides you a declarative way to define what part of your model will become part of your database table. The power of TypeScript gives you type hinting and other useful features that you can use in classes.

Other model settings

The following in sequelize:

flag: { type: Sequelize.BOOLEAN, allowNull: true, defaultValue: true },

Can be achieved in TypeORM like this:

@Column({ nullable: true, default: true })
flag: boolean;

Following in sequelize:

flag: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }

Is written like this in TypeORM:

@Column({ default: () => "NOW()" })
myDate: Date;

Following in sequelize:

someUnique: { type: Sequelize.STRING, unique: true },

Can be achieved this way in TypeORM:

@Column({ unique: true })
someUnique: string;

Following in sequelize:

fieldWithUnderscores: { type: Sequelize.STRING, field: 'field_with_underscores' },

Translates to this in TypeORM:

@Column({ name: "field_with_underscores" })
fieldWithUnderscores: string;

Following in sequelize:

incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },

Can be achieved this way in TypeORM:

@Column()
@Generated()
incrementMe: number;

Following in sequelize:

identifier: { type: Sequelize.STRING, primaryKey: true },

Can be achieved this way in TypeORM:

@Column({ primary: true })
identifier: string;

To create createDate and updateDate-like columns you need to defined two columns (name it what you want) in your entity:

@CreateDateColumn();
createDate: Date;

@UpdateDateColumn();
updateDate: Date;

Working with models

To create a new model in sequelize you write:

const employee = await Employee.create({ name: "John Doe", title: "senior engineer" });

In TypeORM there are several ways to create a new model:

const employee = new Employee(); // you can use constructor parameters as well
employee.name = "John Doe";
employee.title = "senior engineer";

or

const employee = Employee.create({ name: "John Doe", title: "senior engineer" });

if you want to load an exist entity from the database and replace some of its properties you can use following method:

const employee = await Employee.preload({ id: 1, name: "John Doe" });

To access properties in sequelize you do following:

console.log(employee.get('name'));

In TypeORM you simply do:

console.log(employee.name);

To create an index in sequelize you do:

sequelize.define("user", {}, {
  indexes: [
    {
      unique: true,
      fields: ["firstName", "lastName"]
    }
  ]
});

In TypeORM you do:

@Entity()
@Index(["firstName", "lastName"], { unique: true })
export class User {
}