0
# Connection Management
1
2
Core connection management functionality for establishing and maintaining PostgreSQL database connections using native libpq bindings.
3
4
## Capabilities
5
6
### Client Constructor
7
8
Creates a new PostgreSQL client instance with optional configuration.
9
10
```javascript { .api }
11
/**
12
* Creates a new PostgreSQL client instance
13
* @param config - Optional configuration object
14
* @returns New Client instance
15
*/
16
const Client = require('pg-native');
17
18
// Constructor pattern (recommended)
19
const client = new Client(config);
20
21
// Factory pattern (also supported - no 'new' required)
22
const client = Client(config);
23
24
interface ClientConfig {
25
/** Custom type conversion parser (defaults to pg-types) */
26
types?: TypeParser;
27
/** Return results as arrays instead of objects */
28
arrayMode?: boolean;
29
}
30
```
31
32
**Usage Examples:**
33
34
```javascript
35
const Client = require('pg-native');
36
37
// Basic client
38
const client = new Client();
39
40
// Client with array mode enabled
41
const arrayClient = new Client({ arrayMode: true });
42
43
// Client with custom type parsing
44
const customClient = new Client({
45
types: customTypeParser,
46
arrayMode: false
47
});
48
```
49
50
### Asynchronous Connection
51
52
Establishes a connection to the PostgreSQL server asynchronously.
53
54
```javascript { .api }
55
/**
56
* Connect to PostgreSQL server asynchronously
57
* @param params - Optional connection string in libpq format
58
* @param callback - Required callback function
59
*/
60
client.connect(params?: string, callback: (err: Error | null) => void): void;
61
```
62
63
**Connection String Formats:**
64
65
The `params` string supports any format accepted by libpq:
66
67
- URI format: `postgresql://user:password@host:5432/database`
68
- Key-value format: `host=localhost port=5432 dbname=mydb user=myuser`
69
- If omitted, uses PostgreSQL environment variables
70
71
**Usage Examples:**
72
73
```javascript
74
const client = new Client();
75
76
// Connect using environment variables
77
client.connect(function(err) {
78
if (err) throw err;
79
console.log('Connected!');
80
});
81
82
// Connect with connection string
83
client.connect('postgresql://user:pass@localhost:5432/mydb', function(err) {
84
if (err) throw err;
85
console.log('Connected with URI!');
86
});
87
88
// Connect with key-value parameters
89
client.connect('host=localhost port=5432 dbname=test', function(err) {
90
if (err) throw err;
91
console.log('Connected with key-value params!');
92
});
93
```
94
95
### Synchronous Connection
96
97
Establishes a connection to the PostgreSQL server synchronously.
98
99
```javascript { .api }
100
/**
101
* Connect to PostgreSQL server synchronously
102
* @param params - Optional connection string in libpq format
103
* @throws Error if connection fails
104
*/
105
client.connectSync(params?: string): void;
106
```
107
108
**Usage Examples:**
109
110
```javascript
111
const client = new Client();
112
113
try {
114
// Connect using environment variables
115
client.connectSync();
116
console.log('Connected synchronously!');
117
} catch (err) {
118
console.error('Connection failed:', err.message);
119
}
120
121
try {
122
// Connect with connection string
123
client.connectSync('postgresql://user:pass@localhost:5432/mydb');
124
console.log('Connected with URI!');
125
} catch (err) {
126
console.error('Connection failed:', err.message);
127
}
128
```
129
130
### Connection Termination
131
132
Ends the connection to the PostgreSQL server.
133
134
```javascript { .api }
135
/**
136
* End the connection to PostgreSQL server
137
* @param callback - Optional callback called when connection ends
138
*/
139
client.end(callback?: () => void): void;
140
```
141
142
**Usage Examples:**
143
144
```javascript
145
// End connection with callback
146
client.end(function() {
147
console.log('Connection ended');
148
});
149
150
// End connection without callback
151
client.end();
152
```
153
154
### Connection Events
155
156
The client emits events for connection-related activities.
157
158
```javascript { .api }
159
// Client extends EventEmitter
160
client.on('error', (error: Error) => void);
161
client.on('readyForQuery', () => void);
162
```
163
164
**Usage Examples:**
165
166
```javascript
167
const client = new Client();
168
169
client.on('error', function(err) {
170
console.error('Connection error:', err.message);
171
});
172
173
client.on('readyForQuery', function() {
174
console.log('Client ready for queries');
175
});
176
177
client.connect(function(err) {
178
if (err) throw err;
179
// Connection successful
180
});
181
```
182
183
## Environment Variables
184
185
PG Native respects standard PostgreSQL environment variables when no connection parameters are provided:
186
187
- `PGHOST` - Database server host
188
- `PGPORT` - Database server port
189
- `PGDATABASE` - Database name
190
- `PGUSER` - Database user
191
- `PGPASSWORD` - Database password
192
- `PGCONNECT_TIMEOUT` - Connection timeout
193
- And other standard libpq environment variables