0
# Query Operations
1
2
Query execution functionality supporting both text queries and parameterized statements with async and sync interfaces for maximum flexibility.
3
4
## Capabilities
5
6
### Asynchronous Query Execution
7
8
Execute SQL queries asynchronously with optional parameter binding.
9
10
```javascript { .api }
11
/**
12
* Execute a SQL query asynchronously
13
* @param text - SQL query text
14
* @param callback - Callback function receiving results
15
*/
16
client.query(
17
text: string,
18
callback: (err: Error | null, rows: any[], results?: QueryResult | QueryResult[]) => void
19
): void;
20
21
/**
22
* Execute a parameterized SQL query asynchronously
23
* @param text - SQL query text with $1, $2, etc. placeholders
24
* @param values - Array of parameter values
25
* @param callback - Callback function receiving results
26
*/
27
client.query(
28
text: string,
29
values: any[],
30
callback: (err: Error | null, rows: any[], results?: QueryResult | QueryResult[]) => void
31
): void;
32
```
33
34
**Usage Examples:**
35
36
```javascript
37
const client = new Client();
38
client.connectSync();
39
40
// Simple text query
41
client.query('SELECT NOW() AS current_time', function(err, rows) {
42
if (err) throw err;
43
console.log('Current time:', rows[0].current_time);
44
});
45
46
// Parameterized query for safety
47
client.query(
48
'SELECT * FROM users WHERE age > $1 AND city = $2',
49
[25, 'New York'],
50
function(err, rows) {
51
if (err) throw err;
52
console.log('Found users:', rows);
53
}
54
);
55
56
// Query with multiple result sets
57
client.query(
58
'SELECT 1 as first; SELECT 2 as second',
59
function(err, rows, results) {
60
if (err) throw err;
61
console.log('Multiple results:', results);
62
// rows will be an array of arrays: [[{first: 1}], [{second: 2}]]
63
// results will be an array of QueryResult objects
64
}
65
);
66
```
67
68
**Multiple Result Sets:**
69
70
When a query contains multiple statements (separated by semicolons), the callback receives arrays:
71
- `rows`: Array of row arrays, one for each statement
72
- `results`: Array of QueryResult objects, one for each statement
73
74
For single statements:
75
- `rows`: Simple array of row objects
76
- `results`: Single QueryResult object (or undefined for simple queries)
77
78
### Synchronous Query Execution
79
80
Execute SQL queries synchronously, returning results directly.
81
82
```javascript { .api }
83
/**
84
* Execute a SQL query synchronously
85
* @param text - SQL query text
86
* @param values - Optional array of parameter values
87
* @returns Array of result rows
88
* @throws Error if query fails
89
*/
90
client.querySync(text: string, values?: any[]): any[];
91
```
92
93
**Usage Examples:**
94
95
```javascript
96
const client = new Client();
97
client.connectSync();
98
99
try {
100
// Simple text query
101
const rows = client.querySync('SELECT NOW() AS current_time');
102
console.log('Current time:', rows[0].current_time);
103
104
// Parameterized query
105
const users = client.querySync(
106
'SELECT name, email FROM users WHERE age > $1',
107
[25]
108
);
109
console.log('Users over 25:', users);
110
111
// Data modification query
112
const insertResult = client.querySync(
113
'INSERT INTO logs (message, created_at) VALUES ($1, NOW()) RETURNING id',
114
['Application started']
115
);
116
console.log('Inserted log ID:', insertResult[0].id);
117
118
} catch (err) {
119
console.error('Query failed:', err.message);
120
}
121
```
122
123
### Query Result Format
124
125
Query results are returned as arrays of objects by default, with each row as an object with column names as keys.
126
127
```javascript { .api }
128
// Default object mode results
129
interface QueryResultRow {
130
[columnName: string]: any;
131
}
132
133
// Array mode results (when arrayMode: true in constructor)
134
type QueryResultRowArray = any[];
135
```
136
137
**Object Mode (Default):**
138
139
```javascript
140
const client = new Client();
141
const rows = client.querySync('SELECT id, name, age FROM users LIMIT 2');
142
console.log(rows);
143
// [
144
// { id: 1, name: 'Alice', age: 30 },
145
// { id: 2, name: 'Bob', age: 25 }
146
// ]
147
```
148
149
**Array Mode:**
150
151
```javascript
152
const client = new Client({ arrayMode: true });
153
const rows = client.querySync('SELECT id, name, age FROM users LIMIT 2');
154
console.log(rows);
155
// [
156
// [1, 'Alice', 30],
157
// [2, 'Bob', 25]
158
// ]
159
```
160
161
### Query Cancellation
162
163
Cancel a currently executing query.
164
165
```javascript { .api }
166
/**
167
* Cancel the currently executing query
168
* @param callback - Required callback function
169
*/
170
client.cancel(callback: (err: Error | null) => void): void;
171
```
172
173
**Usage Examples:**
174
175
```javascript
176
const client = new Client();
177
client.connectSync();
178
179
// Start a long-running query
180
client.query('SELECT pg_sleep(60)', function(err, rows) {
181
if (err) {
182
console.log('Query was cancelled:', err.message);
183
} else {
184
console.log('Query completed');
185
}
186
});
187
188
// Cancel it after 1 second
189
setTimeout(function() {
190
client.cancel(function(err) {
191
if (err) {
192
console.error('Cancel failed:', err.message);
193
} else {
194
console.log('Cancel request sent');
195
}
196
});
197
}, 1000);
198
```
199
200
### String Escaping Utilities
201
202
Safely escape strings and identifiers for SQL queries.
203
204
```javascript { .api }
205
/**
206
* Escape a string literal for safe inclusion in SQL
207
* @param value - String value to escape
208
* @returns Escaped string literal with quotes
209
*/
210
client.escapeLiteral(value: string): string;
211
212
/**
213
* Escape an identifier for safe inclusion in SQL
214
* @param value - Identifier to escape
215
* @returns Escaped identifier with quotes if needed
216
*/
217
client.escapeIdentifier(value: string): string;
218
```
219
220
**Usage Examples:**
221
222
```javascript
223
const client = new Client();
224
client.connectSync();
225
226
const userInput = "Robert'; DROP TABLE students; --";
227
const tableName = "user data";
228
229
// Escape string literal
230
const escapedValue = client.escapeLiteral(userInput);
231
console.log(escapedValue); // 'Robert''; DROP TABLE students; --'
232
233
// Escape identifier
234
const escapedTable = client.escapeIdentifier(tableName);
235
console.log(escapedTable); // "user data"
236
237
// Use in queries (although parameterized queries are preferred)
238
const query = `SELECT * FROM ${escapedTable} WHERE name = ${escapedValue}`;
239
```
240
241
## Error Handling
242
243
All query operations can throw or return PostgreSQL errors:
244
245
```javascript
246
// Async error handling
247
client.query('INVALID SQL', function(err, rows) {
248
if (err) {
249
console.error('Query error:', err.message);
250
// err.message contains PostgreSQL error details
251
}
252
});
253
254
// Sync error handling
255
try {
256
client.querySync('INVALID SQL');
257
} catch (err) {
258
console.error('Query error:', err.message);
259
// err.message contains PostgreSQL error details
260
}
261
```
262
263
## Best Practices
264
265
1. **Use parameterized queries** to prevent SQL injection
266
2. **Use async methods** in web servers and event-driven applications
267
3. **Use sync methods** in scripts and command-line tools
268
4. **Always handle errors** appropriately for your use case
269
5. **Consider arrayMode** for memory efficiency with large result sets