TypeORMでPostgreSQLのコネクションプールのサイズを指定するには、ConnectionOptions
のextra
プロパティ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.postgres
はpgモジュールのことだが、pg
モジュールは内部でpg-pool
モジュールに依存しており、上コードのPool
はpg-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
// ...
参考
-
extra
プロパティの定義は、[ConnectionOptions]→[PostgresConnectionOptions]→[BaseConnectionOptions]の順で追うと見つかる。
[ConnectionOptions]: https://github.com/typeorm/typeorm/blob/0.2.18/src/connection/ConnectionOptions.ts#L21
[PostgresConnectionOptions]: https://github.com/typeorm/typeorm/blob/0.2.18/src/driver/postgres/PostgresConnectionOptions.ts#L7
[BaseConnectionOptions]: https://github.com/typeorm/typeorm/blob/0.2.18/src/connection/BaseConnectionOptions.ts#L104 ↩