or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client.mdconnection-string.mdcursor.mdindex.mdpool.mdquery-stream.mdquery.mdtypes.mdutilities.md

client.mddocs/

0

# Client Management

1

2

The Client class provides core PostgreSQL connection management and query execution functionality. It extends EventEmitter to provide asynchronous event-driven operations for database interactions.

3

4

## Capabilities

5

6

### Client Constructor

7

8

Creates a new PostgreSQL client instance with connection configuration.

9

10

```javascript { .api }

11

/**

12

* Creates a new PostgreSQL client instance

13

* @param config - Connection configuration object

14

*/

15

class Client extends EventEmitter {

16

constructor(config?: ClientConfig);

17

}

18

19

interface ClientConfig {

20

/** Database user name */

21

user?: string;

22

/** Database password */

23

password?: string;

24

/** Database host (default: 'localhost') */

25

host?: string;

26

/** Database name */

27

database?: string;

28

/** Database port (default: 5432) */

29

port?: number;

30

/** PostgreSQL connection string */

31

connectionString?: string;

32

/** SSL configuration */

33

ssl?: boolean | SSLConfig;

34

/** Binary result mode */

35

binary?: boolean;

36

/** Client encoding */

37

client_encoding?: string;

38

/** Application name for logging */

39

application_name?: string;

40

/** Fallback application name for logging */

41

fallback_application_name?: string;

42

/** Connection options */

43

options?: string;

44

/** Statement timeout in milliseconds */

45

statement_timeout?: number | false;

46

/** Query timeout in milliseconds */

47

query_timeout?: number | false;

48

/** Lock timeout in milliseconds */

49

lock_timeout?: number | false;

50

/** Idle in transaction session timeout in milliseconds */

51

idle_in_transaction_session_timeout?: number | false;

52

/** Connection timeout in milliseconds */

53

connectionTimeoutMillis?: number;

54

/** Enable TCP keep-alive */

55

keepAlive?: boolean;

56

/** Initial delay for keep-alive probes */

57

keepAliveInitialDelayMillis?: number;

58

/** Enable SCRAM-SHA-256-PLUS authentication */

59

enableChannelBinding?: boolean;

60

/** Custom stream for connection */

61

stream?: any;

62

/** Custom connection object */

63

connection?: any;

64

/** Custom types configuration */

65

types?: TypeOverrides;

66

/** Promise constructor to use */

67

Promise?: typeof Promise;

68

/** Replication mode */

69

replication?: string;

70

}

71

72

interface SSLConfig {

73

rejectUnauthorized?: boolean;

74

ca?: string | Buffer;

75

key?: string | Buffer;

76

cert?: string | Buffer;

77

passphrase?: string;

78

servername?: string;

79

checkServerIdentity?: (servername: string, cert: any) => Error | undefined;

80

}

81

```

82

83

**Usage Examples:**

84

85

```javascript

86

const { Client } = require('pg');

87

88

// Basic connection

89

const client = new Client({

90

user: 'postgres',

91

host: 'localhost',

92

database: 'myapp',

93

password: 'secret',

94

port: 5432,

95

});

96

97

// Connection string

98

const client2 = new Client({

99

connectionString: 'postgresql://user:password@host:5432/database'

100

});

101

102

// SSL connection

103

const client3 = new Client({

104

host: 'secure-host.com',

105

ssl: {

106

rejectUnauthorized: false

107

}

108

});

109

```

110

111

### Connect

112

113

Establishes connection to the PostgreSQL database.

114

115

```javascript { .api }

116

/**

117

* Connect to the PostgreSQL database

118

* @param callback - Optional callback for connection result

119

* @returns Promise that resolves when connected

120

*/

121

connect(callback?: (err: Error | null) => void): Promise<void>;

122

```

123

124

**Usage Examples:**

125

126

```javascript

127

// Promise-based

128

await client.connect();

129

130

// Callback-based

131

client.connect((err) => {

132

if (err) {

133

console.error('Connection error', err.stack);

134

} else {

135

console.log('Connected');

136

}

137

});

138

```

139

140

### Query Execution

141

142

Execute SQL queries with optional parameters and callbacks.

143

144

```javascript { .api }

145

/**

146

* Execute a SQL query with text and optional parameters

147

* @param text - SQL query string

148

* @param values - Optional parameter values

149

* @param callback - Optional callback for query result

150

* @returns Promise resolving to query result

151

*/

152

query(text: string, values?: any[], callback?: QueryCallback): Promise<QueryResult>;

153

154

/**

155

* Execute a SQL query with configuration object

156

* @param config - Query configuration

157

* @param callback - Optional callback for query result

158

* @returns Promise resolving to query result

159

*/

160

query(config: QueryConfig, callback?: QueryCallback): Promise<QueryResult>;

161

162

type QueryCallback = (err: Error | null, result: QueryResult) => void;

163

```

164

165

**Usage Examples:**

166

167

```javascript

168

// Simple query

169

const res = await client.query('SELECT NOW()');

170

console.log(res.rows[0]);

171

172

// Parameterized query

173

const res2 = await client.query('SELECT * FROM users WHERE id = $1', [123]);

174

175

// Named prepared statement

176

const res3 = await client.query({

177

name: 'fetch-user',

178

text: 'SELECT * FROM users WHERE id = $1',

179

values: [123]

180

});

181

182

// Callback style

183

client.query('SELECT * FROM users', (err, result) => {

184

if (err) throw err;

185

console.log(result.rows);

186

});

187

```

188

189

### End Connection

190

191

Closes the database connection.

192

193

```javascript { .api }

194

/**

195

* Close the database connection

196

* @param callback - Optional callback for close result

197

* @returns Promise that resolves when connection is closed

198

*/

199

end(callback?: (err: Error | null) => void): Promise<void>;

200

```

201

202

**Usage Examples:**

203

204

```javascript

205

// Promise-based

206

await client.end();

207

208

// Callback-based

209

client.end((err) => {

210

if (err) {

211

console.error('Error ending client', err.stack);

212

}

213

});

214

```

215

216

### Type Parser Management

217

218

Manage custom type parsers for PostgreSQL data types.

219

220

```javascript { .api }

221

/**

222

* Set a custom type parser for a PostgreSQL type

223

* @param oid - PostgreSQL type OID

224

* @param format - Format ('text' or 'binary')

225

* @param parseFn - Parser function

226

*/

227

setTypeParser(oid: number, format: string, parseFn: (value: string) => any): void;

228

setTypeParser(oid: number, parseFn: (value: string) => any): void;

229

230

/**

231

* Get the type parser for a PostgreSQL type

232

* @param oid - PostgreSQL type OID

233

* @param format - Format ('text' or 'binary')

234

* @returns Parser function

235

*/

236

getTypeParser(oid: number, format?: string): (value: string) => any;

237

```

238

239

**Usage Examples:**

240

241

```javascript

242

// Custom date parser

243

client.setTypeParser(1082, (val) => new Date(val));

244

245

// Custom JSON parser with reviver

246

client.setTypeParser(114, (val) => JSON.parse(val, customReviver));

247

248

// Get existing parser

249

const dateParser = client.getTypeParser(1082);

250

```

251

252

### SQL Escaping

253

254

Escape SQL identifiers and literals for safe query construction.

255

256

```javascript { .api }

257

/**

258

* Escape a SQL identifier (table/column name)

259

* @param str - String to escape

260

* @returns Escaped identifier

261

*/

262

escapeIdentifier(str: string): string;

263

264

/**

265

* Escape a SQL literal value

266

* @param str - String to escape

267

* @returns Escaped literal

268

*/

269

escapeLiteral(str: string): string;

270

```

271

272

**Usage Examples:**

273

274

```javascript

275

const tableName = client.escapeIdentifier('user-table');

276

const userInput = client.escapeLiteral("O'Reilly");

277

const query = `SELECT * FROM ${tableName} WHERE name = ${userInput}`;

278

```

279

280

### Connection Management

281

282

Control connection reference counting for process lifecycle management.

283

284

```javascript { .api }

285

/**

286

* Keep the Node.js process alive while client is active

287

*/

288

ref(): void;

289

290

/**

291

* Allow Node.js process to exit even with active client

292

*/

293

unref(): void;

294

```

295

296

### Query Cancellation

297

298

Cancel running queries on the database server.

299

300

```javascript { .api }

301

/**

302

* Cancel a running query

303

* @param client - Client with running query to cancel

304

* @param query - Query to cancel

305

*/

306

cancel(client: Client, query: Query): void;

307

```

308

309

## Client Properties

310

311

```javascript { .api }

312

interface Client {

313

/** Database user */

314

readonly user: string;

315

/** Database name */

316

readonly database: string;

317

/** Database host */

318

readonly host: string;

319

/** Database port */

320

readonly port: number;

321

/** Replication mode */

322

readonly replication: string;

323

/** Server process ID */

324

readonly processID: number | null;

325

/** Server secret key */

326

readonly secretKey: number | null;

327

/** Connection parameters */

328

readonly connectionParameters: ConnectionParameters;

329

/** SSL configuration */

330

readonly ssl: boolean | SSLConfig;

331

/** Binary mode setting */

332

readonly binary: boolean;

333

/** Underlying connection object */

334

readonly connection: Connection;

335

}

336

```

337

338

## Events

339

340

Client emits various events during its lifecycle:

341

342

```javascript { .api }

343

// Connection events

344

client.on('connect', () => {});

345

client.on('end', () => {});

346

client.on('error', (err) => {});

347

348

// Query events

349

client.on('drain', () => {});

350

351

// Notification events

352

client.on('notification', (msg) => {});

353

client.on('notice', (msg) => {});

354

```

355

356

## Connection Parameters

357

358

```javascript { .api }

359

interface ConnectionParameters {

360

user: string;

361

database: string;

362

port: number;

363

host: string;

364

password: string;

365

ssl: boolean | SSLConfig;

366

client_encoding: string;

367

application_name: string;

368

fallback_application_name: string;

369

options: string;

370

statement_timeout: number | false;

371

lock_timeout: number | false;

372

idle_in_transaction_session_timeout: number | false;

373

replication: string;

374

}

375

```