• API
  • pg.Client

新客户端

¥new Client

new Client(config: Config)

config 对象的每个字段都是完全可选的。Client 实例将使用 环境变量 来处理所有缺失值。

¥Every field of the config object is entirely optional. A Client instance will use environment variables for all missing values.

type Config = {
  user?: string, // default process.env.PGUSER || process.env.USER
  password?: string or function, //default process.env.PGPASSWORD
  host?: string, // default process.env.PGHOST
  port?: number, // default process.env.PGPORT
  database?: string, // default process.env.PGDATABASE || user
  connectionString?: string, // e.g. postgres://user:password@host:5432/database
  ssl?: any, // passed directly to node.TLSSocket, supports all tls.connect options
  types?: any, // custom type parsers
  statement_timeout?: number, // number of milliseconds before a statement in query will time out, default is no timeout
  query_timeout?: number, // number of milliseconds before a query call will timeout, default is no timeout
  lock_timeout?: number, // number of milliseconds a query is allowed to be en lock state before it's cancelled due to lock timeout
  application_name?: string, // The name of the application that created this Client instance
  connectionTimeoutMillis?: number, // number of milliseconds to wait for connection, default is no timeout
  idle_in_transaction_session_timeout?: number // number of milliseconds before terminating any session with an open idle transaction, default is no timeout
}

使用特定连接信息创建客户端的示例:

¥example to create a client with specific connection information:

import pg from 'pg'
const { Client } = pg
 
const client = new Client({
  user: 'database-user',
  password: 'secretpassword!!',
  host: 'my.database-server.com',
  port: 5334,
  database: 'database-name',
})

client.connect

import pg from 'pg'
const { Client } = pg
const client = new Client()
 
await client.connect()

client.query

QueryConfig

你可以将对象传递给 client.query,签名如下:

¥You can pass an object to client.query with the signature of:

type QueryConfig {
  // the raw query text
  text: string;
 
  // an array of query parameters
  values?: Array<any>;
 
  // name of the query - used for prepared statements
  name?: string;
 
  // by default rows come out as a key/value pair for each row
  // pass the string 'array' here to receive rows as an array of values
  rowMode?: string;
 
  // custom type parsers just for this query result
  types?: Types;
 
  // TODO: document
  queryMode?: string;
}
client.query(text: string, values?: any[]) => Promise<Result>

纯文本查询

¥Plain text query

import pg from 'pg'
const { Client } = pg
const client = new Client()
 
await client.connect()
 
const result = await client.query('SELECT NOW()')
console.log(result)
 
await client.end()

参数化查询

¥Parameterized query

import pg from 'pg'
const { Client } = pg
const client = new Client()
 
await client.connect()
 
const result = await client.query('SELECT $1::text as name', ['brianc'])
console.log(result)
 
await client.end()
client.query(config: QueryConfig) => Promise<Result>

带有 QueryConfig 的 client.query

¥client.query with a QueryConfig

如果你将 name 参数传递给 client.query 方法,客户端将创建 准备好的声明

¥If you pass a name parameter to the client.query method, the client will create a prepared statement.

const query = {
  name: 'get-name',
  text: 'SELECT $1::text',
  values: ['brianc'],
  rowMode: 'array',
}
 
const result = await client.query(query)
console.log(result.rows) // ['brianc']
 
await client.end()

带有 Submittable 的 client.query

¥client.query with a Submittable

如果你将一个对象传递给 client.query,并且该对象上有一个 .submit 函数,客户端将把它的 PostgreSQL 服务器连接传递给该对象,并将查询分派委托给提供的对象。这是一个高级功能,主要面向库作者。顺便说一下,这也是目前上述回调和基于 promise 的查询在内部处理的方式,但这可能会发生变化。这也是 pg-cursorpg-query-stream 的工作方式。

¥If you pass an object to client.query and the object has a .submit function on it, the client will pass it's PostgreSQL server connection to the object and delegate query dispatching to the supplied object. This is an advanced feature mostly intended for library authors. It is incidentally also currently how the callback and promise based queries above are handled internally, but this is subject to change. It is also how pg-cursor and pg-query-stream work.

import pg from 'pg'
const { Query } = pg
const query = new Query('select $1::text as name', ['brianc'])
 
const result = client.query(query)
 
assert(query === result) // true
 
query.on('row', (row) => {
  console.log('row!', row) // { name: 'brianc' }
})
 
query.on('end', () => {
  console.log('query done')
})
 
query.on('error', (err) => {
  console.error(err.stack)
})

client.end

断开客户端与 PostgreSQL 服务器的连接。

¥Disconnects the client from the PostgreSQL server.

await client.end()
console.log('client has disconnected')

events

error

client.on('error', (err: Error) => void) => void

当客户端正在连接、分派查询或断开连接时,它将捕获并将错误从 PostgreSQL 服务器转发到相应的 client.connect client.queryclient.end promise;但是,客户端与 PostgreSQL 后端保持长期连接,并且由于网络分区、后端崩溃、故障转移等原因,客户端最终可能会(并且在足够长的时间内)在空闲时断开连接。要处理此问题,你可能需要将错误监听器附加到客户端以捕获错误。这是一个人为的例子:

¥When the client is in the process of connecting, dispatching a query, or disconnecting it will catch and forward errors from the PostgreSQL server to the respective client.connect client.query or client.end promise; however, the client maintains a long-lived connection to the PostgreSQL back-end and due to network partitions, back-end crashes, fail-overs, etc the client can (and over a long enough time period will) eventually be disconnected while it is idle. To handle this you may want to attach an error listener to a client to catch errors. Here's a contrived example:

const client = new pg.Client()
client.connect()
 
client.on('error', (err) => {
  console.error('something bad has happened!', err.stack)
})
 
// walk over to server, unplug network cable
 
// process output: 'something bad has happened!' followed by stacktrace :P

end

client.on('end') => void

当客户端与 PostgreSQL 服务器断开连接时,它将发出一次结束事件。

¥When the client disconnects from the PostgreSQL server it will emit an end event once.

notification

用于 listen/notify 事件:

¥Used for listen/notify events:

type Notification {
  processId: number,
  channel: string,
  payload?: string
}
const client = new pg.Client()
await client.connect()
 
client.query('LISTEN foo')
 
client.on('notification', (msg) => {
  console.log(msg.channel) // foo
  console.log(msg.payload) // bar!
})
 
client.query(`NOTIFY foo, 'bar!'`)

notice

client.on('notice', (notice: Error) => void) => void

用于从 PostgreSQL 服务器注销 通知消息

¥Used to log out notice messages from the PostgreSQL server.

client.on('notice', (msg) => console.warn('notice:', msg))
Last updated on August 24, 2024