0
# Callback API
1
2
The MariaDB Node.js connector provides a complete callback-based API that mirrors the Promise-based API. All async methods use Node.js-style callbacks with the signature `(err, result, meta?) => void`.
3
4
## Core Imports
5
6
```javascript
7
const mariadb = require("mariadb/callback");
8
const { createConnection, createPool, createPoolCluster, importFile, SqlError, version } = require("mariadb/callback");
9
```
10
11
## Capabilities
12
13
### Create Connection (Callback)
14
15
Creates a new database connection using callback-based API.
16
17
```javascript { .api }
18
/**
19
* Create a new database connection (Callback-based API)
20
* @param config - Connection configuration object or connection string
21
* @returns Connection instance (callback-based)
22
*/
23
function createConnection(config: string | ConnectionConfig): Connection;
24
```
25
26
**Usage Example:**
27
28
```javascript
29
const mariadb = require("mariadb/callback");
30
31
// Create connection - connection is returned immediately
32
const connection = mariadb.createConnection({
33
host: "localhost",
34
user: "root",
35
password: "password",
36
database: "test"
37
});
38
39
// Listen for connection events
40
connection.on('connect', () => {
41
console.log('Connected to database');
42
43
// Now you can use the connection
44
connection.query("SELECT * FROM users", (err, rows, meta) => {
45
if (err) {
46
console.error('Query failed:', err);
47
return;
48
}
49
console.log('Query results:', rows);
50
console.log('Query metadata:', meta);
51
});
52
});
53
54
connection.on('error', (err) => {
55
console.error('Connection error:', err);
56
});
57
```
58
59
### Connection Interface (Callback-based)
60
61
Main connection interface providing callback-based database operations.
62
63
```javascript { .api }
64
interface Connection extends EventEmitter {
65
/** Connection information */
66
info: ConnectionInfo | null;
67
/** Connection thread identifier */
68
readonly threadId: number | null;
69
70
/** Change connection user and reset session */
71
changeUser(options: UserConnectionConfig, callback: (err: SqlError | null) => void): void;
72
73
/** Start transaction */
74
beginTransaction(callback: (err: SqlError | null) => void): void;
75
76
/** Commit a transaction */
77
commit(callback: (err: SqlError | null) => void): void;
78
79
/** Roll back a transaction */
80
rollback(callback: (err: SqlError | null) => void): void;
81
82
/** Execute query using text protocol */
83
query<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
84
query<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
85
86
/** Prepare statement */
87
prepare(sql: string | QueryOptions, callback: (err: SqlError | null, prepare?: Prepare) => void): void;
88
89
/** Execute query using binary (prepare) protocol */
90
execute<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
91
execute<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
92
93
/** Execute batch operations */
94
batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;
95
batch<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T) => void): void;
96
97
/** Execute query returning a Readable stream */
98
queryStream(sql: string | QueryOptions, values?: any): Readable;
99
100
/** Send ping to server */
101
ping(callback: (err: SqlError | null) => void): void;
102
103
/** Reset connection state */
104
reset(callback: (err: SqlError | null) => void): void;
105
106
/** Import SQL file */
107
importFile(config: SqlImportOptions, callback: (err: SqlError | null) => void): void;
108
109
/** Check if connection is valid */
110
isValid(): boolean;
111
112
/** Close connection gracefully */
113
end(callback: (err: SqlError | null) => void): void;
114
115
/** Alias for end() */
116
close(callback: (err: SqlError | null) => void): void;
117
118
/** Force connection termination */
119
destroy(): void;
120
121
/** Connection control methods */
122
pause(): void;
123
resume(): void;
124
125
/** Get server version */
126
serverVersion(): string;
127
128
/** Debug control */
129
debug(value: boolean): void;
130
debugCompress(value: boolean): void;
131
132
/** Escape utilities */
133
escape(value: any): string;
134
escapeId(identifier: string): string;
135
}
136
```
137
138
**Usage Examples:**
139
140
```javascript
141
const mariadb = require("mariadb/callback");
142
143
const connection = mariadb.createConnection({
144
host: "localhost",
145
user: "root",
146
password: "password",
147
database: "test"
148
});
149
150
connection.on('connect', () => {
151
// Basic query with parameters
152
connection.query("SELECT * FROM users WHERE age > ?", [18], (err, rows, meta) => {
153
if (err) {
154
console.error('Query error:', err);
155
return;
156
}
157
console.log('Users:', rows);
158
console.log('Field info:', meta);
159
});
160
161
// Transaction example
162
connection.beginTransaction((err) => {
163
if (err) {
164
console.error('Begin transaction error:', err);
165
return;
166
}
167
168
connection.query("INSERT INTO users (name, age) VALUES (?, ?)", ["Alice", 25], (err, result) => {
169
if (err) {
170
return connection.rollback((rollbackErr) => {
171
console.error('Insert error:', err);
172
console.error('Rollback error:', rollbackErr);
173
});
174
}
175
176
connection.commit((err) => {
177
if (err) {
178
return connection.rollback((rollbackErr) => {
179
console.error('Commit error:', err);
180
console.error('Rollback error:', rollbackErr);
181
});
182
}
183
console.log('Transaction committed successfully');
184
console.log('Insert ID:', result.insertId);
185
});
186
});
187
});
188
});
189
```
190
191
### Prepared Statements (Callback)
192
193
Prepared statement interface for callback-based API.
194
195
```javascript { .api }
196
interface Prepare {
197
id: number;
198
199
/** Execute prepared statement */
200
execute<T>(values: any, callback: (err: SqlError | null, result?: T, meta?: any) => void): void;
201
202
/** Execute prepared statement returning a stream */
203
executeStream(values: any): Readable;
204
205
/** Close prepared statement */
206
close(): void;
207
}
208
```
209
210
**Usage Example:**
211
212
```javascript
213
connection.prepare("SELECT * FROM users WHERE age > ?", (err, prepare) => {
214
if (err) {
215
console.error('Prepare error:', err);
216
return;
217
}
218
219
// Execute multiple times with different values
220
prepare.execute([18], (err, result) => {
221
if (err) {
222
console.error('Execute error:', err);
223
return;
224
}
225
console.log('Adults:', result);
226
});
227
228
prepare.execute([65], (err, result) => {
229
if (err) {
230
console.error('Execute error:', err);
231
return;
232
}
233
console.log('Seniors:', result);
234
235
// Close when done
236
prepare.close();
237
});
238
});
239
```
240
241
### Pool Connection (Callback)
242
243
Pool connection interface extending the base connection with release functionality.
244
245
```javascript { .api }
246
interface PoolConnection extends Connection {
247
/** Release connection back to pool */
248
release(callback: (err: SqlError | null) => void): void;
249
}
250
```
251
252
### Pool Interface (Callback)
253
254
Connection pool interface for callback-based API.
255
256
```javascript { .api }
257
interface Pool {
258
closed: boolean;
259
260
/** Get connection from pool */
261
getConnection(callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
262
263
/** Execute query on pool connection */
264
query<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
265
query<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
266
267
/** Execute batch on pool connection */
268
batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;
269
batch<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T) => void): void;
270
271
/** Execute using prepared statement on pool connection */
272
execute<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
273
execute<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
274
275
/** Close all pool connections */
276
end(callback: (err: SqlError | null) => void): void;
277
278
/** Import SQL file using pool connection */
279
importFile(config: SqlImportOptions, callback: (err: SqlError | null) => void): void;
280
281
/** Pool statistics */
282
activeConnections(): number;
283
totalConnections(): number;
284
idleConnections(): number;
285
taskQueueSize(): number;
286
287
/** Escape utilities */
288
escape(value: any): string;
289
escapeId(identifier: string): string;
290
}
291
```
292
293
**Usage Example:**
294
295
```javascript
296
const mariadb = require("mariadb/callback");
297
298
const pool = mariadb.createPool({
299
host: "localhost",
300
user: "root",
301
password: "password",
302
database: "test",
303
connectionLimit: 5
304
});
305
306
// Get connection from pool
307
pool.getConnection((err, conn) => {
308
if (err) {
309
console.error('Pool connection error:', err);
310
return;
311
}
312
313
conn.query("SELECT * FROM users", (err, rows) => {
314
if (err) {
315
console.error('Query error:', err);
316
} else {
317
console.log('Query result:', rows);
318
}
319
320
// Always release connection back to pool
321
conn.release((err) => {
322
if (err) {
323
console.error('Release error:', err);
324
}
325
});
326
});
327
});
328
329
// Direct pool query (automatically manages connection)
330
pool.query("SELECT COUNT(*) as total FROM users", (err, result) => {
331
if (err) {
332
console.error('Pool query error:', err);
333
return;
334
}
335
console.log('Total users:', result[0].total);
336
});
337
```
338
339
### Pool Cluster (Callback)
340
341
Pool cluster interface for managing multiple pools with callback-based API.
342
343
```javascript { .api }
344
interface PoolCluster {
345
/** Add pool to cluster */
346
add(id: string, config: PoolConfig): void;
347
348
/** Close all pools in cluster */
349
end(callback: (err: SqlError | null) => void): void;
350
351
/** Get filtered cluster interface */
352
of(pattern: string, selector?: string): FilteredPoolCluster;
353
of(pattern: undefined | null | false, selector: string): FilteredPoolCluster;
354
355
/** Remove pools matching pattern */
356
remove(pattern: string): void;
357
358
/** Get connection from cluster */
359
getConnection(pattern: string | undefined | null, selector: string | undefined | null, callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
360
getConnection(pattern: string | undefined | null, callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
361
getConnection(callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
362
}
363
364
interface FilteredPoolCluster {
365
/** Get connection from filtered cluster */
366
getConnection(callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
367
368
/** Execute query on filtered cluster */
369
query<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
370
query<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
371
372
/** Execute batch on filtered cluster */
373
batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;
374
batch<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T) => void): void;
375
376
/** Execute prepared statement on filtered cluster */
377
execute<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
378
execute<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
379
}
380
```
381
382
### Import File (Callback)
383
384
Import SQL files using callback-based API.
385
386
```javascript { .api }
387
/**
388
* Import SQL file (Callback-based)
389
* @param config - Import configuration including file path and connection options
390
* @param callback - Callback function (err) => void
391
*/
392
function importFile(config: ImportFileConfig, callback: (err: SqlError | null) => void): void;
393
```
394
395
**Usage Example:**
396
397
```javascript
398
const mariadb = require("mariadb/callback");
399
400
mariadb.importFile({
401
host: "localhost",
402
user: "root",
403
password: "password",
404
database: "test",
405
file: "./schema.sql"
406
}, (err) => {
407
if (err) {
408
console.error('Import failed:', err);
409
return;
410
}
411
console.log('SQL file imported successfully');
412
});
413
```
414
415
## Event Handling
416
417
All callback-based connections and pools are EventEmitters and support the same events as their Promise-based counterparts:
418
419
```javascript
420
// Connection events
421
connection.on('error', (err) => {
422
console.error('Connection error:', err);
423
});
424
425
connection.on('end', () => {
426
console.log('Connection ended');
427
});
428
429
// Pool events
430
pool.on('acquire', (conn) => {
431
console.log('Connection acquired from pool');
432
});
433
434
pool.on('release', (conn) => {
435
console.log('Connection released to pool');
436
});
437
438
pool.on('connection', (conn) => {
439
console.log('New connection created in pool');
440
});
441
442
pool.on('enqueue', () => {
443
console.log('Connection request queued');
444
});
445
```
446
447
## Error Handling
448
449
All callback functions follow Node.js conventions with error as the first parameter:
450
451
```javascript
452
connection.query("SELECT * FROM users", (err, result, meta) => {
453
if (err) {
454
// Handle error
455
console.error('Query failed:', err.message);
456
console.error('SQL State:', err.sqlState);
457
console.error('Error Code:', err.errno);
458
console.error('Fatal:', err.fatal);
459
return;
460
}
461
462
// Process successful result
463
console.log('Query succeeded:', result);
464
console.log('Metadata:', meta);
465
});
466
```