Multiple connections, databases, schemas and replication setup

    This approach allows you to connect to any number of databases you haveand each database will have its own configuration, own entities and overall ORM scope and settings.

    For each connection a new instance will be created.You must specify a unique name for each connection you create.

    The connection options can also be loaded from an ormconfig file. You can load all connections fromthe ormconfig file:

    1. import {createConnections} from "typeorm";
    2. const connections = await createConnections();

    or you can specify which connection to create by name:

    1. import {createConnection} from "typeorm";
    2. const connection = await createConnection("db2Connection");

    When working with connections you must specify a connection name to get a specific connection:

    1. import {getConnection} from "typeorm";
    2. const db1Connection = getConnection("db1Connection");
    3. // you can work with "db1" database now...
    4. const db2Connection = getConnection("db2Connection");
    5. // you can work with "db2" database now...

    Benefit of using this approach is that you can configure multiple connections with different login credentials,host, port and even database type itself.Downside for might be that you’ll need to manage and work with multiple connection instances.

    If you don’t want to create multiple connections,but want to use multiple databases in a single connection,you can specify database name per-entity you use:

    1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
    2. @Entity({ database: "secondDB" })
    3. export class User {
    4. @PrimaryGeneratedColumn()
    5. id: number;
    6. @Column()
    7. firstName: string;
    8. @Column()
    9. lastName: string;
    10. }
    1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
    2. @Entity({ database: "thirdDB" })
    3. export class Photo {
    4. @PrimaryGeneratedColumn()
    5. id: number;
    6. @Column()
    7. url: string;
    8. }

    If you want to select data from a different database you only need to provide an entity:

    This code will produce following sql query (depend on database type):

    1. SELECT * FROM "secondDB"."user" "user", "thirdDB"."photo" "photo"
    2. WHERE "photo"."userId" = "user"."id"

    You can also specify a table path instead of the entity:

    1. const users = await connection
    2. .createQueryBuilder()
    3. .select()
    4. .from("secondDB.user", "user")
    5. .addFrom("thirdDB.photo", "photo")
    6. .andWhere("photo.userId = user.id")
    7. .getMany(); // userId is not a foreign key since its cross-database request

    This feature is supported only in mysql and mssql databases.

    You can use multiple schemas in your applications, just set schema on each entity:

    1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
    2. @Entity({ schema: "secondSchema" })
    3. export class User {
    4. @PrimaryGeneratedColumn()
    5. id: number;
    6. @Column()
    7. firstName: string;
    8. @Column()
    9. }
    1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
    2. @Entity({ schema: "thirdSchema" })
    3. export class Photo {
    4. @PrimaryGeneratedColumn()
    5. id: number;
    6. @Column()
    7. url: string;
    8. }

    User entity will be created inside secondSchema schema and Photo entity inside thirdSchema schema.All other entities will be created in default connection schema.

    If you want to select data from a different schema you only need to provide an entity:

    1. const users = await connection
    2. .createQueryBuilder()
    3. .select()
    4. .from(User, "user")
    5. .addFrom(Photo, "photo")
    6. .andWhere("photo.userId = user.id")
    7. .getMany(); // userId is not a foreign key since its cross-database request

    You can also specify a table path instead of the entity:

    1. const users = await connection
    2. .createQueryBuilder()
    3. .select()
    4. .from("secondSchema.user", "user") // in mssql you can even specify a database: secondDB.secondSchema.user
    5. .addFrom("thirdSchema.photo", "photo") // in mssql you can even specify a database: thirdDB.thirdSchema.photo
    6. .andWhere("photo.userId = user.id")
    7. .getMany();

    This feature is supported only in postgres and mssql databases.In mssql you can also combine schemas and databases, for example:

    1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
    2. @Entity({ database: "secondDB", schema: "public" })
    3. export class User {
    4. @PrimaryGeneratedColumn()
    5. id: number;
    6. @Column()
    7. firstName: string;
    8. @Column()
    9. lastName: string;
    10. }

    You can setup read/write replication using TypeORM.Example of replication connection settings:

    1. {
    2. type: "mysql",
    3. logging: true,
    4. replication: {
    5. master: {
    6. host: "server1",
    7. port: 3306,
    8. username: "test",
    9. password: "test",
    10. database: "test"
    11. },
    12. slaves: [{
    13. host: "server2",
    14. port: 3306,
    15. username: "test",
    16. password: "test",
    17. }, {
    18. host: "server3",
    19. username: "test",
    20. password: "test",
    21. database: "test"
    22. }]
    23. }
    24. }

    All schema update and write operations are performed using master server.All simple queries performed by find methods or select query builder are using a random slave instance.

    If you want to explicitly use master in SELECT created by query builder, you can use the following code:

    1. const masterQueryRunner = connection.createQueryRunner("master");
    2. try {
    3. const postsFromMaster = await connection.createQueryBuilder(Post, "post")
    4. .setQueryRunner(masterQueryRunner)
    5. .getMany();
    6. } finally {
    7. await masterQueryRunner.release();
    8. }

    Note that connection created by a QueryRunner need to be explicitly released.

    Replication is supported by mysql, postgres and sql server databases.

    1. {
    2. replication: {
    3. master: {
    4. host: "server1",
    5. port: 3306,
    6. username: "test",
    7. password: "test",
    8. database: "test"
    9. },
    10. slaves: [{
    11. host: "server2",
    12. port: 3306,
    13. username: "test",
    14. password: "test",
    15. database: "test"
    16. }, {
    17. host: "server3",
    18. port: 3306,
    19. username: "test",
    20. password: "test",
    21. database: "test"
    22. }],
    23. /**
    24. * If true, PoolCluster will attempt to reconnect when connection fails. (Default: true)
    25. */
    26. canRetry: true,
    27. /**
    28. * If connection fails, node's errorCount increases.
    29. * When errorCount is greater than removeNodeErrorCount, remove a node in the PoolCluster. (Default: 5)
    30. */
    31. removeNodeErrorCount: 5,
    32. /**
    33. * If connection fails, specifies the number of milliseconds before another connection attempt will be made.
    34. * If set to 0, then node will be removed instead and never re-used. (Default: 0)
    35. */
    36. restoreNodeTimeout: 0,
    37. /**
    38. * Determines how slaves are selected:
    39. * RR: Select one alternately (Round-Robin).
    40. * RANDOM: Select the node by random function.
    41. * ORDER: Select the first node available unconditionally.
    42. */
    43. selector: "RR"
    44. }