新池
¥new Pool
new Pool(config: Config)
构造一个新的池实例。
¥Constructs a new pool instance.
池最初创建为空,并将在需要时延迟创建新客户端。config
对象的每个字段都是完全可选的。当池创建该客户端时,传递给池的配置也会传递给池内的每个客户端实例。
¥The pool is initially created empty and will create new clients lazily as they are needed. Every field of the config
object is entirely optional. The config passed to the pool is also passed to every client instance within the pool when the pool creates that client.
type Config = {
// all valid client config options are also valid here
// in addition here are the pool specific configuration parameters:
// number of milliseconds to wait before timing out when connecting a new client
// by default this is 0 which means no timeout
connectionTimeoutMillis?: number
// number of milliseconds a client must sit idle in the pool and not be checked out
// before it is disconnected from the backend and discarded
// default is 10000 (10 seconds) - set to 0 to disable auto-disconnection of idle clients
idleTimeoutMillis?: number
// maximum number of clients the pool should contain
// by default this is set to 10.
max?: number
// Default behavior is the pool will keep clients open & connected to the backend
// until idleTimeoutMillis expire for each client and node will maintain a ref
// to the socket on the client, keeping the event loop alive until all clients are closed
// after being idle or the pool is manually shutdown with `pool.end()`.
//
// Setting `allowExitOnIdle: true` in the config will allow the node event loop to exit
// as soon as all clients in the pool are idle, even if their socket is still open
// to the postgres server. This can be handy in scripts & tests
// where you don't want to wait for your clients to go idle before your process exits.
allowExitOnIdle?: boolean
}
使用配置创建新池的示例:
¥example to create a new pool with configuration:
import pg from 'pg'
const { Pool } = pg
const pool = new Pool({
host: 'localhost',
user: 'database-user',
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
})
pool.query
通常我们只需要在数据库上运行单个查询,因此为了方便起见,池有一个方法可以在第一个可用的空闲客户端上运行查询并返回其结果。
¥Often we only need to run a single query on the database, so as convenience the pool has a method to run a query on the first available idle client and return its result.
pool.query(text: string, values?: any[]) => Promise<pg.Result>
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
const result = await pool.query('SELECT $1::text as name', ['brianc'])
console.log(result.rows[0].name) // brianc
请注意,在上面的例子中,无需签出或发布客户端。池正在内部进行获取和释放。我发现 pool.query
在很多情况下都是一个方便的快捷方式,除非我需要事务,否则我会专门使用它。
¥Notice in the example above there is no need to check out or release a client. The pool is doing the acquiring and releasing internally. I find pool.query
to be a handy shortcut many situations and use it exclusively unless I need a transaction.
如果你正在使用事务,not 是否使用 pool.query
。
¥Do not use pool.query
if you are using a transaction.
池将在第一个可用的空闲客户端上分派传递给 pool.query 的每个查询。PostgreSQL 中的事务范围仅限于单个客户端,因此在多个随机客户端之间分派单个事务中的单个查询将导致你的应用出现大问题并且无法正常工作。有关更多信息,请阅读 transactions 。
¥The pool will dispatch every query passed to pool.query on the first available idle client. Transactions within PostgreSQL are scoped to a single client and so dispatching individual queries within a single transaction across multiple, random clients will cause big problems in your app and not work. For more info please read transactions .
pool.connect
pool.connect() => Promise<pg.Client>
从池中获取客户端。
¥Acquires a client from the pool.
-
如果池中有空闲客户端,则将一个客户端返回到
process.nextTick
上的回调。¥If there are idle clients in the pool one will be returned to the callback on
process.nextTick
. -
如果池未满但所有当前客户端都已签出,则将创建一个新客户端并返回到此回调。
¥If the pool is not full but all current clients are checked out a new client will be created & returned to this callback.
-
如果池是 'full' 并且当前已签出所有客户端,则将在 FIFO 队列中等待,直到客户端被释放回池中而变得可用。
¥If the pool is 'full' and all clients are currently checked out will wait in a FIFO queue until a client becomes available by it being released back to the pool.
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
const client = await pool.connect()
await client.query('SELECT NOW()')
client.release()
发布客户端
¥releasing clients
client.release(destroy?: boolean) => void
从 pool.connect
返回的客户端实例将具有 release
方法,该方法会将它们从池中释放出来。
¥Client instances returned from pool.connect
will have a release
method which will release them from the pool.
获取的客户端上的 release
方法将其返回到池。如果你在 destroy
参数中传递了一个真值,而不是将客户端释放到池中,池将被指示断开连接并销毁此客户端,在其内部为新客户端留出空间。
¥The release
method on an acquired client returns it back to the pool. If you pass a truthy value in the destroy
parameter, instead of releasing the client to the pool, the pool will be instructed to disconnect and destroy this client, leaving a space within itself for a new client.
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
// check out a single client
const client = await pool.connect()
// release the client
client.release()
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
assert(pool.totalCount === 0)
assert(pool.idleCount === 0)
const client = await pool.connect()
await client.query('SELECT NOW()')
assert(pool.totalCount === 1)
assert(pool.idleCount === 0)
// tell the pool to destroy this client
await client.release(true)
assert(pool.idleCount === 0)
assert(pool.totalCount === 0)
当你完成客户端后,你可以 must 释放它。
¥You must release a client when you are finished with it.
如果你忘记释放客户端,那么你的应用将很快耗尽池中可用的空闲客户端,并且如果你将 connectionTimeoutMillis
配置为 0,则对 pool.connect
的所有进一步调用都将超时并出现错误或无限期挂起。
¥If you forget to release the client then your application will quickly exhaust available, idle clients in the pool and
all further calls to pool.connect
will timeout with an error or hang indefinitely if you have
connectionTimeoutMillis
configured to 0.
pool.end
调用 pool.end
将耗尽池中的所有活动客户端,断开它们的连接,并关闭池中的所有内部计时器。通常在使用池的脚本末尾或当你的进程试图干净地关闭时调用它。
¥Calling pool.end
will drain the pool of all active clients, disconnect them, and shut down any internal timers in the pool. It is common to call this at the end of a script using the pool or when your process is attempting to shut down cleanly.
// again both promises and callbacks are supported:
import pg from 'pg'
const { Pool } = pg
const pool = new Pool()
await pool.end()
properties
pool.totalCount: number
池中现有的客户端总数。
¥The total number of clients existing within the pool.
pool.idleCount: number
未签出但当前在池中处于空闲状态的客户端数量。
¥The number of clients which are not checked out but are currently idle in the pool.
pool.waitingCount: number
当所有客户端都签出时,等待客户端的排队请求数。监视这个数字以查看是否需要调整池的大小会很有帮助。
¥The number of queued requests waiting on a client when all clients are checked out. It can be helpful to monitor this number to see if you need to adjust the size of the pool.
events
Pool
实例也是 EventEmitter
的实例。
¥Pool
instances are also instances of EventEmitter
.
connect
pool.on('connect', (client: Client) => void) => void
每当池与 PostgreSQL 后端建立新的客户端连接时,它都会使用新连接的客户端发出 connect
事件。这为你提供了在客户端上运行设置命令的机会。
¥Whenever the pool establishes a new client connection to the PostgreSQL backend it will emit the connect
event with the newly connected client. This presents an opportunity for you to run setup commands on a client.
const pool = new Pool()
pool.on('connect', (client) => {
client.query('SET DATESTYLE = iso, mdy')
})
acquire
pool.on('acquire', (client: Client) => void) => void
每当从池中检出客户端时,池都会与获取的客户端一起发出 acquire
事件。
¥Whenever a client is checked out from the pool the pool will emit the acquire
event with the client that was acquired.
error
pool.on('error', (err: Error, client: Client) => void) => void
当客户端闲置在池中时,它仍会触发错误,因为它连接到实时后端。
¥When a client is sitting idly in the pool it can still emit errors because it is connected to a live backend.
如果后端关闭或遇到网络分区,则应用中所有空闲的连接客户端将通过池的错误事件触发器触发错误。
¥If the backend goes down or a network partition is encountered all the idle, connected clients in your application will emit an error through the pool's error event emitter.
错误监听器将错误作为第一个参数传递,将发生错误的客户端作为第二个参数传递。客户端将自动终止并从池中移除,只有在你想要检查它时才会传递给错误处理程序。
¥The error listener is passed the error as the first argument and the client upon which the error occurred as the 2nd argument. The client will be automatically terminated and removed from the pool, it is only passed to the error handler in case you want to inspect it.
error
事件并且没有添加监听器,节点将发出未捕获的错误并可能导致节点进程崩溃。¥
error
event and no listeners are added node will emit an
uncaught error and potentially crash your node process.release
pool.on('release', (err: Error, client: Client) => void) => void
每当客户端被释放回池中时,池就会发出 release
事件。
¥Whenever a client is released back into the pool, the pool will emit the release
event.
remove
pool.on('remove', (client: Client) => void) => void
每当关闭客户端并将其从池中移除时,池都会发出 remove
事件。
¥Whenever a client is closed & removed from the pool the pool will emit the remove
event.