PostgreSQL client library for Node.js with both pure JavaScript and optional native libpq bindings
npx @tessl/cli install tessl/npm-pg@8.16.00
# pg
1
2
pg is a comprehensive PostgreSQL client library for Node.js that provides both pure JavaScript and optional native libpq bindings with a unified API. It features connection pooling, extensible data-type coercion, parameterized queries with query plan caching, asynchronous notifications, and bulk data operations with full transaction support.
3
4
## Package Information
5
6
- **Package Name**: pg
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install pg`
10
- **Optional Native Bindings**: `npm install pg pg-native`
11
12
## Core Imports
13
14
```javascript
15
const { Client, Pool, Query } = require('pg');
16
```
17
18
For ESM:
19
20
```javascript
21
import { Client, Pool, Query } from 'pg';
22
```
23
24
For native bindings:
25
26
```javascript
27
const { Client } = require('pg').native;
28
// or
29
import pg from 'pg';
30
const Client = pg.native.Client;
31
```
32
33
## Basic Usage
34
35
### Simple Client Connection
36
37
```javascript
38
const { Client } = require('pg');
39
40
const client = new Client({
41
user: 'dbuser',
42
host: 'database.server.com',
43
database: 'mydb',
44
password: 'secretpassword',
45
port: 5432,
46
});
47
48
await client.connect();
49
50
const res = await client.query('SELECT $1::text as message', ['Hello world!']);
51
console.log(res.rows[0].message); // Hello world!
52
53
await client.end();
54
```
55
56
### Connection Pool Usage
57
58
```javascript
59
const { Pool } = require('pg');
60
61
const pool = new Pool({
62
user: 'dbuser',
63
host: 'database.server.com',
64
database: 'mydb',
65
password: 'secretpassword',
66
port: 5432,
67
});
68
69
const res = await pool.query('SELECT NOW()');
70
console.log(res.rows[0]);
71
72
await pool.end();
73
```
74
75
## Architecture
76
77
pg is built around several key components:
78
79
- **Client**: Core connection management and query execution
80
- **Pool**: Connection pooling for resource optimization
81
- **Query**: Query configuration and execution handling
82
- **Connection**: Low-level PostgreSQL protocol implementation
83
- **Type System**: Extensible type conversion between JavaScript and PostgreSQL
84
- **Utilities**: Helper functions for escaping and query normalization
85
86
## Capabilities
87
88
### Client Management
89
90
Core PostgreSQL client functionality for establishing connections, executing queries, and managing database transactions.
91
92
```javascript { .api }
93
class Client extends EventEmitter {
94
constructor(config?: ClientConfig);
95
connect(callback?: (err: Error) => void): Promise<void>;
96
query(text: string, values?: any[], callback?: QueryCallback): Promise<QueryResult>;
97
query(config: QueryConfig, callback?: QueryCallback): Promise<QueryResult>;
98
end(callback?: (err: Error) => void): Promise<void>;
99
}
100
101
interface ClientConfig {
102
user?: string;
103
password?: string;
104
host?: string;
105
database?: string;
106
port?: number;
107
connectionString?: string;
108
ssl?: boolean | object;
109
binary?: boolean;
110
client_encoding?: string;
111
application_name?: string;
112
statement_timeout?: number | false;
113
query_timeout?: number | false;
114
connectionTimeoutMillis?: number;
115
keepAlive?: boolean;
116
keepAliveInitialDelayMillis?: number;
117
}
118
```
119
120
[Client Management](./client.md)
121
122
### Connection Pooling
123
124
Connection pool management for optimizing database resource usage and handling concurrent connections.
125
126
```javascript { .api }
127
class Pool extends EventEmitter {
128
constructor(config?: PoolConfig);
129
connect(): Promise<PoolClient>;
130
query(text: string, values?: any[], callback?: QueryCallback): Promise<QueryResult>;
131
query(config: QueryConfig, callback?: QueryCallback): Promise<QueryResult>;
132
end(): Promise<void>;
133
}
134
135
interface PoolConfig extends ClientConfig {
136
max?: number;
137
min?: number;
138
idleTimeoutMillis?: number;
139
connectionTimeoutMillis?: number;
140
maxUses?: number;
141
allowExitOnIdle?: boolean;
142
}
143
```
144
145
[Connection Pooling](./pool.md)
146
147
### Query Execution
148
149
Query configuration, parameter binding, and result handling with support for prepared statements and streaming.
150
151
```javascript { .api }
152
class Query extends EventEmitter {
153
constructor(config: QueryConfig, values?: any[], callback?: QueryCallback);
154
}
155
156
interface QueryConfig {
157
text: string;
158
values?: any[];
159
name?: string;
160
rowMode?: 'array' | 'object';
161
types?: TypeOverrides;
162
binary?: boolean;
163
portal?: string;
164
rows?: number;
165
}
166
167
interface QueryResult {
168
command: string;
169
rowCount: number;
170
oid: number;
171
rows: any[];
172
fields: FieldDef[];
173
}
174
```
175
176
[Query Execution](./query.md)
177
178
### Type System
179
180
Type conversion system for handling data transformations between JavaScript and PostgreSQL types.
181
182
```javascript { .api }
183
interface types {
184
getTypeParser(oid: number, format?: string): (value: string) => any;
185
setTypeParser(oid: number, format: string, parseFn: (value: string) => any): void;
186
setTypeParser(oid: number, parseFn: (value: string) => any): void;
187
}
188
189
class TypeOverrides {
190
constructor(userTypes?: types);
191
setTypeParser(oid: number, format: string, parseFn: (value: string) => any): void;
192
getTypeParser(oid: number, format?: string): (value: string) => any;
193
}
194
```
195
196
[Type System](./types.md)
197
198
### Utilities
199
200
Utility functions for SQL escaping, parameter normalization, and configuration management.
201
202
```javascript { .api }
203
function escapeIdentifier(str: string): string;
204
function escapeLiteral(str: string): string;
205
206
const defaults: {
207
host: string;
208
user: string;
209
database: string;
210
password: string;
211
port: number;
212
rows: number;
213
binary: boolean;
214
max: number;
215
idleTimeoutMillis: number;
216
client_encoding: string;
217
ssl: boolean;
218
application_name: string;
219
statement_timeout: number | false;
220
query_timeout: number | false;
221
connect_timeout: number;
222
};
223
```
224
225
[Utilities](./utilities.md)
226
227
### Connection String Parsing
228
229
Parse and normalize PostgreSQL connection strings with comprehensive SSL and configuration support.
230
231
```javascript { .api }
232
function parse(connectionString: string, options?: ParseOptions): ConnectionOptions;
233
function toClientConfig(config: ConnectionOptions): ClientConfig;
234
function parseIntoClientConfig(connectionString: string): ClientConfig;
235
```
236
237
[Connection String Parsing](./connection-string.md)
238
239
### Query Cursors
240
241
Server-side cursors for memory-efficient processing of large result sets without loading all rows into memory.
242
243
```javascript { .api }
244
class Cursor extends EventEmitter {
245
constructor(text: string, values?: any[], config?: CursorConfig);
246
read(rows: number, callback?: QueryCallback): Promise<any[]>;
247
close(callback?: (err: Error | null) => void): Promise<void>;
248
}
249
```
250
251
[Query Cursors](./cursor.md)
252
253
### Query Streaming
254
255
Node.js Readable stream interface for PostgreSQL query results, enabling streaming processing with standard stream APIs.
256
257
```javascript { .api }
258
class QueryStream extends Readable {
259
constructor(text: string, values?: any[], config?: QueryStreamConfig);
260
}
261
```
262
263
[Query Streaming](./query-stream.md)
264
265
## Error Handling
266
267
pg provides comprehensive error handling through the DatabaseError class and standard EventEmitter patterns:
268
269
```javascript { .api }
270
class DatabaseError extends Error {
271
severity: string;
272
code: string;
273
detail: string;
274
hint: string;
275
position: string;
276
internalPosition: string;
277
internalQuery: string;
278
where: string;
279
schema: string;
280
table: string;
281
column: string;
282
dataType: string;
283
constraint: string;
284
file: string;
285
line: string;
286
routine: string;
287
}
288
```
289
290
## Additional Exported Classes
291
292
### Result
293
294
Query result container with metadata and row data.
295
296
```javascript { .api }
297
class Result {
298
constructor(rowMode?: string, types?: TypeOverrides);
299
addCommandComplete(msg: any): void;
300
command: string | null;
301
rowCount: number | null;
302
oid: number | null;
303
rows: any[];
304
fields: FieldDef[];
305
}
306
```
307
308
### Connection
309
310
Low-level PostgreSQL protocol connection handler (advanced usage).
311
312
```javascript { .api }
313
class Connection extends EventEmitter {
314
constructor(config?: ConnectionConfig);
315
connect(port: number, host: string): void;
316
query(text: string): void;
317
end(): void;
318
}
319
```
320
321
## Common Types
322
323
```javascript { .api }
324
type QueryCallback = (err: Error | null, result: QueryResult) => void;
325
326
interface FieldDef {
327
name: string;
328
tableID: number;
329
columnID: number;
330
dataTypeID: number;
331
dataTypeSize: number;
332
dataTypeModifier: number;
333
format: string;
334
}
335
336
interface PoolClient extends Client {
337
release(err?: Error | boolean): void;
338
}
339
```