LoginSignup
4
4

More than 3 years have passed since last update.

TypeORMでPostgreSQLのコネクションプールサイズを指定する

Last updated at Posted at 2019-06-17

TypeORMでPostgreSQLのコネクションプールのサイズを指定するには、ConnectionOptionsextraプロパティ1(any型)にpoolSizeもしくはmaxを指定する:

  const connection = await createConnection({
    type: 'postgres',
    host: 'db',
    username: 'root',
    password: 'root',
    database: 'test',
    extra: {
      poolSize: 10, // connection pool size
    },
  })

この方法でPostgreSQLのプールサイズを指定できるのは、TypeOrmのPostgresDriver.tsの86行目あたりextraを[Pool]クラスのパラメータとして渡すようになっているためである:

/**
 * Organizes communication with PostgreSQL DBMS.
 */
export class PostgresDriver implements Driver {
    // ...

    /**
     * Creates a new connection pool for a given database credentials.
     */
    protected async createPool(options: PostgresConnectionOptions, credentials: PostgresConnectionCredentialsOptions): Promise<any> {
        // ...

        // build connection options for the driver
        const connectionOptions = Object.assign({}, {
            host: credentials.host,
            user: credentials.username,
            password: credentials.password,
            database: credentials.database,
            port: credentials.port,
            ssl: credentials.ssl
        }, options.extra || {}); // Poolクラスに渡すオプションとしてextraを使っている

        // create a connection pool
        const pool = new this.postgres.Pool(connectionOptions);

        // ...
    }

    // ...
}

ここのthis.postgrespgモジュールのことだが、pgモジュールは内部でpg-poolモジュールに依存しており、上コードのPoolpg-poolモジュールのPoolクラスになる。

Poolクラスのコンストラクタは次のような実装になっており、maxもしくはpoolSizeの指定がなければ10がコネクション数のデフォルト値になるようになっている:

class Pool extends EventEmitter {
  constructor (options, Client) {
    super()
    this.options = Object.assign({}, options)
    this.options.max = this.options.max || this.options.poolSize || 10
    // ...

参考


  1. extraプロパティの定義は、ConnectionOptionsPostgresConnectionOptionsBaseConnectionOptionsの順で追うと見つかる。 

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4