【问题标题】:Typeorm : Using multiple databases in a single connection Postgresql - nodejsTypeorm:在单个连接中使用多个数据库 Postgresql - nodejs
【发布时间】:2021-10-25 08:44:11
【问题描述】:

我正在关注此文档,并且无法在单个连接中与 2 个数据库进行通信:

https://typeorm.io/#/multiple-connections/using-multiple-databases-in-a-single-connection

我成功使用了 2 个不同的连接,但我需要一个连接。在本章的最后是这样写的:

此功能仅在 mysql 和 mssql 数据库中受支持。

我正在使用 Postgresql。是不是有问题?

如果有人有解释、完整示例或存储库,那就太棒了

【问题讨论】:

    标签: node.js postgresql nestjs typeorm


    【解决方案1】:

    TypeOrmModule 通过添加具有不同连接名称的多个模块来提供多个数据库连接处理。

    注意:name 属性很重要

    @Module({
      imports: [
        TypeOrmModule.forRoot({
          type: 'postgres',
          name: 'Connection1', // this is what will be used
          host: 'localhost',
          port: 3306,
          username: 'root',
          password: 'root',
          database: 'database1',
        }),
        TypeOrmModule.forRoot({
          type: 'postgres',
          name: 'Connection2',
          host: 'localhost',
          port: 3306,
          username: 'root',
          password: 'root',
          database: 'database2',
        }),
      ],
      controllers: [AppController],
      providers: [
      ],
    })
    export class AppModule {}
    

    现在在您的 UserModule 中

    
     // same entity can be used on different connections or if you want you can use different
    @Module({
      imports: [
        TypeOrmModule.forFeature([UserEntity], 'Connection1'),
        TypeOrmModule.forFeature([UserEntity], 'Connection2'),
      ],
      providers: [UserService]
    })
    

    在用户服务中

    @Injectable()
    class UserService {
      constructor (
    @InjectRepository(UserEntity, 'Connection1') private userCon1Repo: Repository<UserEntity>,
    @InjectRepository(UserEntity, 'Connection2') private userCon2Repo: Repository<UserEntity>,
    }
    

    主要内容是,如果您想维护多个连接,则必须在 forRoot 或 forRootAsyn 中配置连接时为连接命名,并且在注入实体时,您需要在第二个参数中提供连接名称。

    我认为未提供时的名称是默认。

    Sequelize 也是如此。

    【讨论】:

      【解决方案2】:

      如果它可以帮助任何人,这就是解决方案。

      CREATE EXTENSION postgres_fdw;
      
      CREATE SERVER <connection_name>
      FOREIGN DATA WRAPPER postgres_fdw
      OPTIONS (host <host>, dbname <dbname>, port <port>);
      
      CREATE USER MAPPING FOR <user>
      SERVER <connection_name>
      OPTIONS (user <user>, password <password>);
      
      IMPORT FOREIGN SCHEMA <schema_name>
      LIMIT TO (<table_name>)
      FROM SERVER <connection_name> INTO <schema_name>;
      

      来源:https://www.akinjide.me/2017/cross-database-querying-in-postgresql/

      【讨论】:

        猜你喜欢
        • 2019-07-10
        • 2020-04-25
        • 2023-03-25
        • 2023-04-04
        • 2021-07-02
        • 2022-12-18
        • 2021-06-04
        • 2020-11-05
        • 2011-09-11
        相关资源
        最近更新 更多