0
# Configuration
1
2
Comprehensive configuration system covering connection parameters, timeouts, data formatting, SSL settings, and performance tuning options. The MariaDB connector provides extensive customization capabilities for different deployment scenarios.
3
4
## Capabilities
5
6
### Connection Configuration
7
8
Core connection configuration options for database connectivity.
9
10
```typescript { .api }
11
interface ConnectionConfig {
12
/** Database hostname (default: 'localhost') */
13
host?: string;
14
15
/** Database port (default: 3306) */
16
port?: number;
17
18
/** Database username */
19
user?: string;
20
21
/** Database password */
22
password?: string;
23
24
/** Database name to connect to */
25
database?: string;
26
27
/** Unix domain socket path (overrides host/port) */
28
socketPath?: string;
29
}
30
```
31
32
### SSL Configuration
33
34
Secure connection options for encrypted database communication.
35
36
```typescript { .api }
37
interface ConnectionConfig {
38
/** SSL configuration - boolean or detailed options */
39
ssl?: boolean | SSLConfig;
40
}
41
42
interface SSLConfig extends SecureContextOptions {
43
/** Reject connections with invalid certificates (default: true) */
44
rejectUnauthorized?: boolean;
45
}
46
```
47
48
**SSL Examples:**
49
50
```typescript
51
// Enable SSL with default settings
52
const connection = await mariadb.createConnection({
53
host: "secure.db.com",
54
user: "app",
55
password: "secret",
56
ssl: true
57
});
58
59
// Custom SSL configuration
60
const connection2 = await mariadb.createConnection({
61
host: "secure.db.com",
62
user: "app",
63
password: "secret",
64
ssl: {
65
ca: fs.readFileSync('./ca-cert.pem'),
66
cert: fs.readFileSync('./client-cert.pem'),
67
key: fs.readFileSync('./client-key.pem'),
68
rejectUnauthorized: true
69
}
70
});
71
```
72
73
### Timeout Configuration
74
75
Timeout settings for various connection and query operations.
76
77
```typescript { .api }
78
interface ConnectionConfig {
79
/** Connection establishment timeout (default: 1000ms) */
80
connectTimeout?: number;
81
82
/** Socket timeout after connection established */
83
socketTimeout?: number;
84
85
/** Query execution timeout */
86
queryTimeout?: number;
87
}
88
```
89
90
### Authentication Configuration
91
92
Advanced authentication options including RSA keys and plugin settings.
93
94
```typescript { .api }
95
interface ConnectionConfig {
96
/** Path/content to MySQL server RSA public key */
97
rsaPublicKey?: string;
98
99
/** Path/content to MySQL server caching RSA public key */
100
cachingRsaPublicKey?: string;
101
102
/** Allow client to request public key from server (default: false) */
103
allowPublicKeyRetrieval?: boolean;
104
105
/** Allow connection with expired password (default: false) */
106
permitConnectionWhenExpired?: boolean;
107
108
/** Allow connection redirection (default: false) */
109
permitRedirect?: boolean;
110
111
/** Restricted authentication plugins */
112
restrictedAuth?: string[];
113
114
/** Custom stream factory for creating socket connections */
115
stream?: (callback?: typeof StreamCallback) => void;
116
}
117
```
118
119
### Character Set and Collation
120
121
Character encoding and collation configuration.
122
123
```typescript { .api }
124
interface ConnectionConfig {
125
/** Protocol character set (default: 'UTF8MB4') */
126
charset?: string;
127
128
/** Connection collation (default: 'UTF8MB4_UNICODE_CI') */
129
collation?: string;
130
}
131
```
132
133
**Character Set Examples:**
134
135
```typescript
136
// UTF8MB4 with Unicode collation (recommended)
137
const config1 = {
138
charset: 'UTF8MB4',
139
collation: 'UTF8MB4_UNICODE_CI'
140
};
141
142
// Case-insensitive collation
143
const config2 = {
144
charset: 'UTF8MB4',
145
collation: 'UTF8MB4_GENERAL_CI'
146
};
147
148
// Binary collation for exact matching
149
const config3 = {
150
charset: 'UTF8MB4',
151
collation: 'UTF8MB4_BIN'
152
};
153
```
154
155
### Data Format Configuration
156
157
Options controlling how query results are formatted and returned.
158
159
```typescript { .api }
160
interface ConnectionConfig {
161
/** Return result rows as arrays instead of objects (default: false) */
162
rowsAsArray?: boolean;
163
164
/** Return metadata as array [rows, metadata] (default: false) */
165
metaAsArray?: boolean;
166
167
/** Make metadata properties enumerable (default: false) */
168
metaEnumerable?: boolean;
169
170
/** Nest tables to avoid column name conflicts */
171
nestTables?: boolean | string;
172
173
/** Return dates as strings instead of Date objects (default: false) */
174
dateStrings?: boolean;
175
176
/** Force specific timezone usage (default: 'local') */
177
timezone?: string;
178
}
179
```
180
181
**Data Format Examples:**
182
183
```typescript
184
// Return rows as arrays for better performance
185
const fastConfig = {
186
rowsAsArray: true,
187
metaAsArray: false
188
};
189
190
// Comprehensive metadata access
191
const debugConfig = {
192
metaAsArray: true,
193
metaEnumerable: true,
194
dateStrings: true
195
};
196
197
// Handle timezone-sensitive data
198
const utcConfig = {
199
timezone: 'Z', // UTC
200
dateStrings: false
201
};
202
```
203
204
### Type Handling Configuration
205
206
Control how different MySQL/MariaDB data types are handled in JavaScript.
207
208
```typescript { .api }
209
interface ConnectionConfig {
210
/** Return BIGINT as Number instead of BigInt (default: false) */
211
bigIntAsNumber?: boolean;
212
213
/** Return insertId as Number instead of BigInt (default: false) */
214
insertIdAsNumber?: boolean;
215
216
/** Return DECIMAL as Number instead of string (default: false) */
217
decimalAsNumber?: boolean;
218
219
/** Throw error if number conversion is unsafe (default: false) */
220
checkNumberRange?: boolean;
221
222
/** Support big numbers (deprecated, use specific options) */
223
supportBigNumbers?: boolean;
224
225
/** Always return big numbers as strings (deprecated) */
226
bigNumberStrings?: boolean;
227
228
/** Custom type casting function */
229
typeCast?: TypeCastFunction;
230
}
231
232
type TypeCastFunction = (field: FieldInfo, next: TypeCastNextFunction) => TypeCastResult;
233
type TypeCastNextFunction = () => TypeCastResult;
234
type TypeCastResult = boolean | number | string | symbol | null | Date | Geometry | Buffer;
235
```
236
237
**Type Handling Examples:**
238
239
```typescript
240
// Handle large numbers safely
241
const safeNumberConfig = {
242
bigIntAsNumber: false, // Keep as BigInt
243
decimalAsNumber: false, // Keep as string
244
checkNumberRange: true, // Throw if unsafe conversion
245
insertIdAsNumber: true // Convert insertId for convenience
246
};
247
248
// Custom type casting
249
const customTypeCast: TypeCastFunction = (field, next) => {
250
if (field.type === 'TINY' && field.columnLength === 1) {
251
// Convert TINYINT(1) to boolean
252
return field.string() === '1';
253
}
254
if (field.type === 'DATE') {
255
// Custom date formatting
256
const date = field.date();
257
return date ? date.toISOString().split('T')[0] : null;
258
}
259
return next(); // Use default conversion
260
};
261
```
262
263
### Query Behavior Configuration
264
265
Options controlling SQL query execution and parsing behavior.
266
267
```typescript { .api }
268
interface ConnectionConfig {
269
/** Allow multiple SQL statements per query (default: false) */
270
multipleStatements?: boolean;
271
272
/** Use named placeholders (:name) instead of ? (default: false) */
273
namedPlaceholders?: boolean;
274
275
/** Allow setting multiple values with object placeholders (default: false) */
276
permitSetMultiParamEntries?: boolean;
277
278
/** Enable LOAD DATA LOCAL INFILE statements (default: false) */
279
permitLocalInfile?: boolean;
280
281
/** Enable query pipelining for better performance (default: true) */
282
pipelining?: boolean;
283
284
/** Enable bulk operations in batch commands (default: true) */
285
bulk?: boolean;
286
287
/** Return FOUND_ROWS() instead of affected rows (default: true) */
288
foundRows?: boolean;
289
}
290
```
291
292
### Performance Configuration
293
294
Settings for optimizing connection and query performance.
295
296
```typescript { .api }
297
interface ConnectionConfig {
298
/** Enable compression for network traffic (default: false) */
299
compress?: boolean;
300
301
/** Server max_allowed_packet value for batch optimization (default: 4MB) */
302
maxAllowedPacket?: number;
303
304
/** Socket keep-alive delay in milliseconds (default: 0 - disabled) */
305
keepAliveDelay?: number;
306
307
/** Force server version check using SELECT VERSION() (default: false) */
308
forceVersionCheck?: boolean;
309
310
/** Prepared statement cache size (default: 256) */
311
prepareCacheLength?: number;
312
}
313
```
314
315
### Debug Configuration
316
317
Debugging and logging options for development and troubleshooting.
318
319
```typescript { .api }
320
interface ConnectionConfig {
321
/** Enable debug mode - log all packets (default: false) */
322
debug?: boolean;
323
324
/** Enable compression debug logging (default: false) */
325
debugCompress?: boolean;
326
327
/** Maximum packet length to log when debugging (default: 256) */
328
debugLen?: number;
329
330
/** Add query creation stack trace to errors (default: false) */
331
trace?: boolean;
332
333
/** Log query parameters in logger (default: false) */
334
logParam?: boolean;
335
336
/** Save last exchanged packets for error messages (default: false) */
337
logPackets?: boolean;
338
339
/** Logger configuration */
340
logger?: LoggerConfig;
341
}
342
343
interface LoggerConfig {
344
/** Network operation logger */
345
network?: (msg: string) => void;
346
347
/** Query execution logger */
348
query?: (msg: string) => void;
349
350
/** Error logger */
351
error?: (err: Error) => void;
352
353
/** Warning logger */
354
warning?: (msg: string) => void;
355
}
356
357
interface SSLConfig extends SecureContextOptions {
358
/** Reject connections with invalid certificates (default: true) */
359
rejectUnauthorized?: boolean;
360
}
361
```
362
363
**Debug Configuration Example:**
364
365
```typescript
366
const debugConnection = await mariadb.createConnection({
367
host: "localhost",
368
user: "root",
369
password: "password",
370
database: "test",
371
372
// Enable comprehensive debugging
373
debug: true,
374
trace: true,
375
logParam: true,
376
logPackets: true,
377
378
// Custom logger
379
logger: {
380
query: (sql) => console.log('Query:', sql),
381
error: (err) => console.error('DB Error:', err),
382
network: (msg) => console.log('Network:', msg)
383
}
384
});
385
```
386
387
### Session Configuration
388
389
Options for initializing database session state.
390
391
```typescript { .api }
392
interface ConnectionConfig {
393
/** Initial SQL commands to execute after connection */
394
initSql?: string | string[];
395
396
/** Session variables to set on connection */
397
sessionVariables?: Record<string, any>;
398
399
/** Connection attributes sent to server */
400
connectAttributes?: Record<string, any>;
401
}
402
```
403
404
**Session Configuration Example:**
405
406
```typescript
407
const connection = await mariadb.createConnection({
408
host: "localhost",
409
user: "app",
410
password: "secret",
411
database: "production",
412
413
// Initialize session
414
initSql: [
415
"SET sql_mode = 'STRICT_TRANS_TABLES'",
416
"SET time_zone = '+00:00'"
417
],
418
419
// Set session variables
420
sessionVariables: {
421
idle_transaction_timeout: 300,
422
wait_timeout: 28800,
423
autocommit: 1
424
},
425
426
// Connection attributes for monitoring
427
connectAttributes: {
428
application: 'myapp',
429
version: '1.2.3',
430
environment: 'production'
431
}
432
});
433
```
434
435
### File Import Configuration
436
437
Configuration for SQL file import operations.
438
439
```typescript { .api }
440
interface ConnectionConfig {
441
/** Custom stream factory for LOAD LOCAL INFILE */
442
infileStreamFactory?: (filepath: string) => Readable;
443
}
444
445
interface ImportFileConfig extends ConnectionConfig {
446
/** Path to SQL file to import */
447
file: string;
448
}
449
450
interface SqlImportOptions {
451
/** Path to SQL file */
452
file: string;
453
454
/** Target database name (optional) */
455
database?: string;
456
}
457
```
458
459
### JSON and Data Processing
460
461
Advanced options for JSON handling and data processing.
462
463
```typescript { .api }
464
interface ConnectionConfig {
465
/** Auto-map JSON fields to JavaScript objects (default: true) */
466
autoJsonMap?: boolean;
467
468
/** Include array values in parentheses for compatibility (default: false) */
469
arrayParenthesis?: boolean;
470
471
/** Check for duplicate column names in results (default: true) */
472
checkDuplicate?: boolean;
473
}
474
```
475
476
### Default Options Function
477
478
Retrieve and customize default configuration values.
479
480
```typescript { .api }
481
/**
482
* Get default connection options
483
* @param opts - Optional overrides for default values
484
* @returns Configuration object with defaults applied
485
*/
486
function defaultOptions(opts?: ConnectionConfig): any;
487
```
488
489
**Usage Examples:**
490
491
```typescript
492
// Get all defaults
493
const defaults = mariadb.defaultOptions();
494
console.log(defaults.host); // 'localhost'
495
console.log(defaults.port); // 3306
496
console.log(defaults.acquireTimeout); // undefined (pool-specific)
497
498
// Override specific defaults
499
const customDefaults = mariadb.defaultOptions({
500
host: 'myserver.com',
501
connectTimeout: 5000,
502
charset: 'latin1'
503
});
504
505
// Use defaults as base for configuration
506
const config = {
507
...mariadb.defaultOptions(),
508
user: 'myuser',
509
password: 'mypass',
510
database: 'mydb'
511
};
512
```
513
514
### Configuration Best Practices
515
516
**Production Configuration:**
517
518
```typescript
519
const productionConfig = {
520
// Connection basics
521
host: process.env.DB_HOST,
522
port: parseInt(process.env.DB_PORT || '3306'),
523
user: process.env.DB_USER,
524
password: process.env.DB_PASSWORD,
525
database: process.env.DB_NAME,
526
527
// Security
528
ssl: {
529
ca: fs.readFileSync('./ca-cert.pem'),
530
rejectUnauthorized: true
531
},
532
533
// Performance
534
compress: true,
535
pipelining: true,
536
prepareCacheLength: 512,
537
538
// Reliability
539
connectTimeout: 5000,
540
queryTimeout: 30000,
541
acquireTimeout: 10000,
542
543
// Data handling
544
charset: 'UTF8MB4',
545
collation: 'UTF8MB4_UNICODE_CI',
546
bigIntAsNumber: false,
547
checkNumberRange: true,
548
549
// Monitoring
550
trace: false, // Only in development
551
logger: {
552
error: (err) => logger.error('Database error', err),
553
warning: (msg) => logger.warn('Database warning', msg)
554
}
555
};
556
```
557
558
**Development Configuration:**
559
560
```typescript
561
const developmentConfig = {
562
host: 'localhost',
563
user: 'dev',
564
password: 'dev',
565
database: 'app_dev',
566
567
// Debug settings
568
debug: true,
569
trace: true,
570
logParam: true,
571
572
// Permissive settings for testing
573
multipleStatements: true,
574
permitLocalInfile: true,
575
576
// Fast feedback
577
connectTimeout: 2000,
578
queryTimeout: 10000
579
};
580
```