TypeORM

TypeORM - data-mapper ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in Node.JS and Browser.

Connection and Connection Options

Connection is a single database connection to a specific database of a database management system. You can have multiple connections to multiple databases in your application.

ConnectionOptions is an interface with settings and options for specific connection. Options contain database and other connection-related settings. You must provide connection options for each of your connections.

Creating a new connection

To create a new connection you should use facade methods from "typeorm" namespace:

Example how you can create a single connection:


import {createConnection} from "typeorm";

createConnection({
    driver: {
        type: "mysql",
        host: "localhost",
        port: 3306,
        username: "root",
        password: "admin",
        database: "test"
    },
    entities: [
        __dirname + "/entity/*.js" // here we load all entities from entity directory
    ],
    autoSchemaSync: true
}).then(connection => {

    // connected. Now you can manipulate your entities!

});
        

Connection options

To perform a connection you need to specify a connection options. ConnectionOptions is an interface:


export interface ConnectionOptions {

    /**
     * Database connection options.
     */
    readonly driver: {

        /**
         * Database type. This value is required.
         */
        readonly type: "mysql"|"postgres"|"mariadb"|"sqlite"|"oracle"|"mssql"|"websql";

        /**
         * Connection url to where perform connection to.
         */
        readonly url?: string;

        /**
         * Database host.
         */
        readonly host?: string;

        /**
         * Database host port.
         */
        readonly port?: number;

        /**
         * Database username.
         */
        readonly username?: string;

        /**
         * Database password.
         */
        readonly password?: string;

        /**
         * Database name to connect to.
         */
        readonly database?: string;

        /**
         * Connection SID (used for Oracle databases).
         */
        readonly sid?: string;

        /**
         * Storage type or path to the storage (used for SQLite databases).
         */
        readonly storage?: string;

        /**
         * Indicates if connection pooling should be used or not.
         * Be default it is enabled if its supported by a platform. Set to false to disable it.
         */
        readonly usePool?: boolean;

        /**
         * Extra connection options to be passed to the driver.
         */
        readonly extra?: any;

        /**
         * Prefix to use on all tables of this connection in the database.
         */
        readonly tablesPrefix?: string;

    };

    /**
     * Connection name. If connection name is not given then it will be called "default".
     * Different connections must have different names.
     */
    readonly name?: string;

    /**
     * Name of the naming strategy or target class of the naming strategy to be used for this connection.
     */
    readonly usedNamingStrategy?: string|Function;

    /**
     * Entities to be loaded for this connection.
     * Accepts both entity classes and directories where from entities need to be loaded.
     * Directories support glob patterns.
     */
    readonly entities?: Function[]|string[];

    /**
     * Subscribers to be loaded for this connection.
     * Accepts both subscriber classes and directories where from subscribers need to be loaded.
     * Directories support glob patterns.
     */
    readonly subscribers?: Function[]|string[];

    /**
     * Naming strategies to be loaded for this connection.
     * Accepts both naming strategy classes and directories where from naming strategies need to be loaded.
     * Directories support glob patterns.
     */
    readonly namingStrategies?: Function[]|string[];

    /**
     * Entity schemas to be loaded for this connection.
     * Accepts both entity schema classes and directories where from entity schemas need to be loaded.
     * Directories support glob patterns.
     */
    readonly entitySchemas?: EntitySchema[]|string[];

    /**
     * Logging options.
     */
    readonly logging?: {

        /**
         * Some specific logger to be used. By default it is a console.
         */
        readonly logger?: (level: string, message: any) => void;

        /**
         * Set to true if you want to log every executed query.
         */
        readonly logQueries?: boolean;

        /**
         * Set to true if you want to log only failed query.
         */
        readonly logOnlyFailedQueries?: boolean;

        /**
         * Set to true if you want to log error of the failed query.
         */
        readonly logFailedQueryError?: boolean;

        /**
         * If set to true then schema creation logs will be logged.
         */
        readonly logSchemaCreation?: boolean;

    };

    /**
     * Drops the schema each time connection is being established.
     * Be careful with this option and don't use this in production - otherwise you'll loose all production data.
     * This option is useful during debug and development.
     */
    readonly dropSchemaOnConnection?: boolean;

    /**
     * Indicates if database schema should be auto created on every application launch.
     * Be careful with this option and don't use this in production - otherwise you can loose production data.
     * This option is useful during debug and development.
     * Alternative to it, you can use CLI and run schema:sync command.
     */
    readonly autoSchemaSync?: boolean;

    /**
     * Environment in which connection will run.
     * Current environment is determined from the environment NODE_ENV variable's value.
     * For example, if NODE_ENV is "test" and this property is set to "test",
     * then this connection will be created. On any other NODE_ENV value it will be skipped.
     * This option is specific to the configuration in the ormconfig.json file.
     */
    readonly environment?: string;

}
        
Example of connection options:

const connectionOptions: ConnectionOptions = {
    driver: {
        type: "mysql",
        host: "localhost",
        port: 3306,
        username: "root",
        password: "admin",
        database: "test"
    },
    logging: {
        logQueries: true,
        logFailedQueryError: true,
    }
    autoSchemaSync: true,
    entities: [__dirname + "/modules/**/entity/{*.ts,*.js}"],
    subscribers: [__dirname + "/modules/**/subscriber/{*.ts,*.js}"]
}
        

Working with connection

There are several useful methods in the Connection object:

Here is example how you can use these methods:


import {createConnection, ConnectionOptions} from "typeorm";
import {User} from "./User"; // lets say we have this entity
import {Photo} from "./Photo"; // lets say we have this entity
import {Post} from "./Post"; // lets say we have this entity

const connectionOptions: ConnectionOptions = {
    driver: {
        type: "mysql",
        host: "localhost",
        port: 3306,
        username: "root",
        password: "admin",
        database: "test"
    },
    entities: [User, Photo, Post],
    autoSchemaSync: true
};

createConnection(connectionOptions).then(connection => {

    // using these repositories you can create, insert, update and delete entities:
    const userRepository  = connection.getRepository(User);
    const photoRepository = connection.getRepository(Photo);
    const postRepository  = connection.getRepository(Post);

    // using this entity manager you can do any operation your repositories can with any entity:
    const entityManager = connection.entityManager;

});
        

Creating connection from ormconfig.json

You can create a file named ormconfig.json in the root of your application (near package.json) and TypeORM will initialize you connections from that file. Here is how your configuration should look like:


  {
    "name": "default",
    "driver": {
      "type": "mysql",
      "host": "localhost",
      "port": 3306,
      "username": "root",
      "password": "admin",
      "database": "test"
    },
    "autoSchemaSync": true
  },
  {
    "name": "seconary-connection",
    "driver": {
      "type": "postgres",
      "host": "localhost",
      "port": 5432,
      "username": "root",
      "password": "admin",
      "database": "test"
    },
    "autoSchemaSync": true
  }
]
        

Configurations can be environment-specific, for example:


  {
    "environment": "prod",
    "name": "default",
    "driver": {
      "type": "mysql",
      "host": "localhost",
      "port": 3306,
      "username": "root",
      "password": "admin",
      "database": "test"
    },
    "autoSchemaSync": true
  },
  {
    "environment": "dev",
    "name": "default",
    "driver": {
      "type": "postgres",
      "host": "localhost",
      "port": 5432,
      "username": "root",
      "password": "admin",
      "database": "test"
    },
    "autoSchemaSync": true
  }
]
        

Now, if you set NODE_ENV to "prod", then mysql connection will be established. If you set NODE_ENV to "dev" then postgres connection will be established.

Once you created a configuration you need to call createConnection() method without connection options object. If you want to establish all connections from the ormconfig.json then call a createConnections() method instead.

Creating connection from environment variables

TypeORM can create connection when you call createConnection() method without connection options automatically from environment variables. These are environment variables you can to set:

Creating a new connection manually

Creating a new connection manually is easy as:

let connection = new Connection(name: string, driver: Driver, logger: Logger);

But in most of cases you may want to use createConnection or ConnectionManager methods instead.

Connection API:

Here is a public API of Connection that you can use:

Fork me on GitHub