or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-pg-native

A slightly nicer interface to Postgres over node-libpq providing both sync and async operations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/pg-native@3.5.x

To install, run

npx @tessl/cli install tessl/npm-pg-native@3.5.0

0

# PG Native

1

2

PG Native provides a high-performance native interface to PostgreSQL databases through libpq bindings, offering both asynchronous and synchronous operations for connecting, querying, and executing prepared statements. It serves as a lower-level alternative to the main 'pg' package, delivering direct access to native PostgreSQL client functionality with minimal overhead.

3

4

## Package Information

5

6

- **Package Name**: pg-native

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install pg-native`

10

11

## Core Imports

12

13

```javascript

14

const Client = require('pg-native');

15

```

16

17

For ES modules:

18

19

```javascript

20

import Client from 'pg-native';

21

```

22

23

## Basic Usage

24

25

```javascript

26

const Client = require('pg-native');

27

28

// Constructor pattern (recommended)

29

const client = new Client();

30

31

// Factory pattern (also supported)

32

const client2 = Client();

33

client.connect(function(err) {

34

if(err) throw err

35

36

// Simple query

37

client.query('SELECT NOW() AS the_date', function(err, rows) {

38

if(err) throw err

39

40

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

41

42

// Parameterized query

43

client.query('SELECT $1::text as message', ['Hello World'], function(err, rows) {

44

if(err) throw err

45

46

console.log(rows[0].message); // 'Hello World'

47

client.end();

48

});

49

});

50

});

51

```

52

53

## Architecture

54

55

PG Native is built around several key components:

56

57

- **Client Class**: Main interface providing both async and sync operations

58

- **Event System**: EventEmitter-based notifications for PostgreSQL LISTEN/NOTIFY

59

- **Stream Support**: Duplex streams for PostgreSQL COPY operations

60

- **Type Conversion**: Integrated with pg-types for proper data type handling

61

- **libpq Integration**: Direct bindings to the native PostgreSQL client library

62

63

## Capabilities

64

65

### Client Connection

66

67

Core connection management functionality for establishing and maintaining PostgreSQL database connections. Supports both asynchronous and synchronous connection patterns.

68

69

```javascript { .api }

70

const Client = require('pg-native');

71

72

// Constructor patterns (both supported)

73

const client = new Client(config?: ClientConfig);

74

const client = Client(config?: ClientConfig); // Factory pattern

75

```

76

77

[Connection Management](./connection.md)

78

79

### Query Operations

80

81

Query execution functionality supporting both text queries and parameterized statements. Provides async and sync interfaces for maximum flexibility.

82

83

```javascript { .api }

84

// Asynchronous query execution

85

client.query(

86

text: string,

87

values?: any[],

88

callback: (err: Error | null, rows: any[], results?: QueryResult | QueryResult[]) => void

89

): void;

90

91

// Synchronous query execution

92

client.querySync(text: string, values?: any[]): any[];

93

```

94

95

[Query Operations](./queries.md)

96

97

### Prepared Statements

98

99

Prepared statement functionality for optimized repeated query execution. Supports both preparation and execution phases with proper parameter binding.

100

101

```javascript { .api }

102

// Prepare a statement

103

client.prepare(

104

statementName: string,

105

text: string,

106

nParams: number,

107

callback: (err: Error | null) => void

108

): void;

109

110

// Execute prepared statement

111

client.execute(

112

statementName: string,

113

parameters: any[],

114

callback: (err: Error | null, rows: any[], results?: any) => void

115

): void;

116

```

117

118

[Prepared Statements](./prepared-statements.md)

119

120

### COPY Operations

121

122

PostgreSQL COPY operation support through Node.js streams. Enables high-performance bulk data import and export operations.

123

124

```javascript { .api }

125

// Get a duplex stream for COPY operations

126

client.getCopyStream(): CopyStream;

127

128

interface CopyStream extends Duplex {

129

// Stream methods for reading/writing COPY data

130

write(chunk: Buffer, encoding?: string, callback?: Function): boolean;

131

end(): void;

132

}

133

```

134

135

[COPY Operations](./copy-operations.md)

136

137

### Version Export

138

139

The module exports its version string for compatibility checking.

140

141

```javascript { .api }

142

// Module version export

143

Client.version: string;

144

```

145

146

**Usage Examples:**

147

148

```javascript

149

const Client = require('pg-native');

150

console.log('pg-native version:', Client.version);

151

```

152

153

## Types

154

155

```javascript { .api }

156

interface ClientConfig {

157

/** Custom type conversion parser (defaults to pg-types) */

158

types?: TypeParser;

159

/** Return results as arrays instead of objects */

160

arrayMode?: boolean;

161

}

162

163

// Constructor/Factory function

164

interface ClientConstructor {

165

/** Create new Client instance */

166

new (config?: ClientConfig): Client;

167

/** Factory function to create Client (no 'new' required) */

168

(config?: ClientConfig): Client;

169

/** Module version string */

170

version: string;

171

}

172

173

interface Client extends EventEmitter {

174

/** Connect to PostgreSQL server */

175

connect(params?: string, callback: (err: Error | null) => void): void;

176

/** Synchronously connect to PostgreSQL server */

177

connectSync(params?: string): void;

178

/** Execute a query */

179

query(text: string, callback: (err: Error | null, rows: any[]) => void): void;

180

query(text: string, values: any[], callback: (err: Error | null, rows: any[]) => void): void;

181

/** Synchronously execute a query */

182

querySync(text: string, values?: any[]): any[];

183

/** Prepare a statement */

184

prepare(name: string, text: string, nParams: number, callback: (err: Error | null) => void): void;

185

/** Synchronously prepare a statement */

186

prepareSync(name: string, text: string, nParams: number): void;

187

/** Execute a prepared statement */

188

execute(name: string, params: any[], callback: (err: Error | null, rows: any[]) => void): void;

189

/** Synchronously execute a prepared statement */

190

executeSync(name: string, params: any[]): any[];

191

/** Cancel current query */

192

cancel(callback: (err: Error | null) => void): void;

193

/** End the connection */

194

end(callback?: () => void): void;

195

/** Escape a string literal */

196

escapeLiteral(value: string): string;

197

/** Escape an identifier */

198

escapeIdentifier(value: string): string;

199

/** Get a COPY stream */

200

getCopyStream(): CopyStream;

201

}

202

203

// Events emitted by Client

204

interface ClientEvents {

205

/** PostgreSQL notification received */

206

'notification': (message: NotificationMessage) => void;

207

/** Query result received */

208

'result': (result: QueryResult) => void;

209

/** Client ready for next query */

210

'readyForQuery': () => void;

211

/** Error occurred */

212

'error': (error: Error) => void;

213

}

214

215

interface NotificationMessage {

216

/** Notification channel name */

217

channel: string;

218

/** Notification payload */

219

payload: string;

220

/** Process ID of the notifying backend */

221

pid: number;

222

}

223

224

interface QueryResult {

225

/** SQL command that was executed */

226

command: string;

227

/** Number of rows affected by the command */

228

rowCount: number;

229

/** Column information for the result set */

230

fields: Array<{ name: string; dataTypeID: number }>;

231

/** Result rows (same as the rows parameter in callbacks) */

232

rows: any[];

233

}

234

```