As my TypeORM project grows in size and its components become more discreet yet interconnected, I am exploring ways to separate it into multiple databases while maintaining cross-database relations.
To achieve this, I have been experimenting with the database
setting on the @Entity
decorator, following the guidelines provided at:
In order to test this approach, I created a simple example with two entities that should ideally reside in different databases:
@Entity({ database: 'test' })
export default class Entity1 {
@PrimaryGeneratedColumn()
id?: number
@Column()
name?: string
@Column()
address?: string
}
and
@Entity({ database: 'database2' })
export default class Entity2 {
@PrimaryGeneratedColumn()
id?: number
@Column()
name?: string
@Column()
address?: string
}
The code snippet below initializes the database connections:
import {createConnections} from "typeorm";
async function doDbExample() {
const connections = await createConnections([{
name: "db1Connection",
type: "postgres",
host: "db",
port: 5432,
username: "test",
password: "testPassword",
database: "test",
entities: [__dirname + "/entity/*{.js,.ts}"],
synchronize: true
}]);
console.log("Created connections")
}
doDbExample()
However, despite specifying the database for each entity, both tables end up in the same database of the connection. This behavior raises the question of whether I am missing something or encountering a bug in TypeORM where the database
setting is not being respected as expected.
I am executing the code using ts-node-dev
.
For a comprehensive reproducible example, including a Dockerized setup of the database environment, please refer to the repository on GitHub: https://github.com/petterroea/TypeOrmBug-MRE