0
# Type Definitions
1
2
Comprehensive type definitions for MariaDB/MySQL data types, field attributes, and type casting functionality. These types provide full type safety and precise control over data handling in the MariaDB connector.
3
4
## Capabilities
5
6
### Column Type Enumerations
7
8
Numeric constants representing MySQL/MariaDB column types as they appear in the protocol.
9
10
```typescript { .api }
11
enum TypeNumbers {
12
DECIMAL = 0,
13
TINY = 1,
14
SHORT = 2,
15
LONG = 3,
16
FLOAT = 4,
17
DOUBLE = 5,
18
NULL = 6,
19
TIMESTAMP = 7,
20
BIGINT = 8,
21
INT24 = 9,
22
DATE = 10,
23
TIME = 11,
24
DATETIME = 12,
25
YEAR = 13,
26
NEWDATE = 14,
27
VARCHAR = 15,
28
BIT = 16,
29
TIMESTAMP2 = 17,
30
DATETIME2 = 18,
31
TIME2 = 19,
32
JSON = 245, // MySQL only
33
NEWDECIMAL = 246,
34
ENUM = 247,
35
SET = 248,
36
TINY_BLOB = 249,
37
MEDIUM_BLOB = 250,
38
LONG_BLOB = 251,
39
BLOB = 252,
40
VAR_STRING = 253,
41
STRING = 254,
42
GEOMETRY = 255
43
}
44
```
45
46
### Column Type Strings
47
48
String constants representing MySQL/MariaDB column types for readable type identification.
49
50
```typescript { .api }
51
enum Types {
52
DECIMAL = 'DECIMAL',
53
TINY = 'TINY',
54
SHORT = 'SHORT',
55
LONG = 'LONG',
56
FLOAT = 'FLOAT',
57
DOUBLE = 'DOUBLE',
58
NULL = 'NULL',
59
TIMESTAMP = 'TIMESTAMP',
60
BIGINT = 'BIGINT',
61
INT24 = 'INT24',
62
DATE = 'DATE',
63
TIME = 'TIME',
64
DATETIME = 'DATETIME',
65
YEAR = 'YEAR',
66
NEWDATE = 'NEWDATE',
67
VARCHAR = 'VARCHAR',
68
BIT = 'BIT',
69
TIMESTAMP2 = 'TIMESTAMP2',
70
DATETIME2 = 'DATETIME2',
71
TIME2 = 'TIME2',
72
JSON = 'JSON',
73
NEWDECIMAL = 'NEWDECIMAL',
74
ENUM = 'ENUM',
75
SET = 'SET',
76
TINY_BLOB = 'TINY_BLOB',
77
MEDIUM_BLOB = 'MEDIUM_BLOB',
78
LONG_BLOB = 'LONG_BLOB',
79
BLOB = 'BLOB',
80
VAR_STRING = 'VAR_STRING',
81
STRING = 'STRING',
82
GEOMETRY = 'GEOMETRY'
83
}
84
```
85
86
### Field Attribute Flags
87
88
Bit flags representing various attributes and constraints of database columns.
89
90
```typescript { .api }
91
enum Flags {
92
/** Field cannot be null */
93
NOT_NULL = 1,
94
95
/** Field is a primary key */
96
PRIMARY_KEY = 2,
97
98
/** Field has a unique constraint */
99
UNIQUE_KEY = 4,
100
101
/** Field is part of a multiple-column key */
102
MULTIPLE_KEY = 8,
103
104
/** Field is a BLOB type */
105
BLOB = 16,
106
107
/** Field is unsigned (numeric types) */
108
UNSIGNED = 32,
109
110
/** Field has ZEROFILL attribute */
111
ZEROFILL_FLAG = 64,
112
113
/** Field has binary collation */
114
BINARY_COLLATION = 128,
115
116
/** Field is an ENUM */
117
ENUM = 256,
118
119
/** Field auto-increments */
120
AUTO_INCREMENT = 512,
121
122
/** Field is a TIMESTAMP */
123
TIMESTAMP = 1024,
124
125
/** Field is a SET */
126
SET = 2048,
127
128
/** Field has no default value */
129
NO_DEFAULT_VALUE_FLAG = 4096,
130
131
/** Field updates to NOW() on UPDATE */
132
ON_UPDATE_NOW_FLAG = 8192,
133
134
/** Field is numeric */
135
NUM_FLAG = 16384
136
}
137
```
138
139
### Type Casting System
140
141
Type casting functionality for customizing how database values are converted to JavaScript types.
142
143
```typescript { .api }
144
/**
145
* Custom type casting function for controlling data type conversion
146
* @param field - Field metadata information
147
* @param next - Function to get default type conversion
148
* @returns Converted value or result of next() for default conversion
149
*/
150
type TypeCastFunction = (field: FieldInfo, next: TypeCastNextFunction) => TypeCastResult;
151
152
/**
153
* Function to get the default type conversion for a field
154
* @returns Default converted value
155
*/
156
type TypeCastNextFunction = () => TypeCastResult;
157
158
/**
159
* Possible return types from type casting functions
160
*/
161
type TypeCastResult = boolean | number | string | symbol | null | Date | Geometry | Buffer;
162
```
163
164
**Type Casting Examples:**
165
166
```typescript
167
import { TypeCastFunction } from "mariadb";
168
169
// Convert TINYINT(1) to boolean, others to default
170
const booleanTypeCast: TypeCastFunction = (field, next) => {
171
if (field.type === 'TINY' && field.columnLength === 1) {
172
return field.string() === '1';
173
}
174
return next(); // Use default conversion
175
};
176
177
// Custom date formatting
178
const dateTypeCast: TypeCastFunction = (field, next) => {
179
if (field.type === 'DATE') {
180
const date = field.date();
181
return date ? date.toISOString().split('T')[0] : null;
182
}
183
return next();
184
};
185
186
// Handle large numbers safely
187
const safeNumberTypeCast: TypeCastFunction = (field, next) => {
188
if (field.type === 'BIGINT') {
189
const str = field.string();
190
const num = str ? BigInt(str) : null;
191
// Keep as BigInt if outside safe integer range
192
return num && num <= Number.MAX_SAFE_INTEGER && num >= Number.MIN_SAFE_INTEGER
193
? Number(num) : num;
194
}
195
return next();
196
};
197
198
// Use in connection config
199
const connection = await mariadb.createConnection({
200
host: "localhost",
201
user: "root",
202
password: "password",
203
database: "test",
204
typeCast: booleanTypeCast
205
});
206
```
207
208
### Collation Interface
209
210
Interface for handling character set collations and encoding information.
211
212
```typescript { .api }
213
interface Collation {
214
/** Collation index number */
215
index: number;
216
217
/** Collation name (e.g., 'utf8mb4_unicode_ci') */
218
name: string;
219
220
/** Character encoding (e.g., 'utf8mb4') */
221
encoding: string;
222
223
/** Maximum bytes per character */
224
maxLength: number;
225
226
/** Get collation by encoding name */
227
fromEncoding(encoding: string): Collation;
228
229
/** Get collation by index number */
230
fromIndex(index: number): Collation;
231
232
/** Get collation by collation name */
233
fromName(name: string): Collation;
234
}
235
```
236
237
### Field Information Interface
238
239
Comprehensive metadata interface for database columns providing type information and value access methods.
240
241
```typescript { .api }
242
interface FieldInfo {
243
/** Collation information for the field */
244
collation: Collation;
245
246
/** Maximum length of the column */
247
columnLength: number;
248
249
/** Numeric type identifier */
250
columnType: TypeNumbers;
251
252
/** Decimal scale for numeric types */
253
scale: number;
254
255
/** String type identifier */
256
type: Types;
257
258
/** Bit flags for field attributes */
259
flags: Flags;
260
261
/** Get database name */
262
db(): string;
263
264
/** Get schema name (alias for db) */
265
schema(): string;
266
267
/** Get table name */
268
table(): string;
269
270
/** Get original table name */
271
orgTable(): string;
272
273
/** Get column name */
274
name(): string;
275
276
/** Get original column name */
277
orgName(): string;
278
279
/** Get field value as string */
280
string(): string | null;
281
282
/** Get field value as Buffer */
283
buffer(): Buffer | null;
284
285
/** Get field value as float */
286
float(): number | null;
287
288
/** Get field value as integer */
289
int(): number | null;
290
291
/** Get field value as long integer */
292
long(): number | null;
293
294
/** Get field value as decimal */
295
decimal(): number | null;
296
297
/** Get field value as Date object */
298
date(): Date | null;
299
300
/** Get field value as GeoJSON Geometry */
301
geometry(): Geometry | null;
302
}
303
```
304
305
**FieldInfo Usage Examples:**
306
307
```typescript
308
// Custom result processing with field metadata
309
const results = await connection.query("SELECT id, name, created_at, location FROM users");
310
311
// Access metadata through meta property
312
const meta = results.meta as FieldInfo[];
313
314
meta.forEach((field, index) => {
315
console.log(`Column ${index}:`);
316
console.log(` Name: ${field.name()}`);
317
console.log(` Type: ${field.type}`);
318
console.log(` Table: ${field.table()}`);
319
console.log(` Nullable: ${!(field.flags & Flags.NOT_NULL)}`);
320
console.log(` Primary Key: ${!!(field.flags & Flags.PRIMARY_KEY)}`);
321
console.log(` Auto Increment: ${!!(field.flags & Flags.AUTO_INCREMENT)}`);
322
});
323
324
// Type-based processing
325
const processRow = (row: any, meta: FieldInfo[]) => {
326
const processed: any = {};
327
328
meta.forEach((field, index) => {
329
const value = row[index];
330
const name = field.name();
331
332
switch (field.type) {
333
case 'TINY':
334
// Convert TINYINT(1) to boolean
335
processed[name] = field.columnLength === 1 ? !!value : value;
336
break;
337
case 'DATETIME':
338
case 'TIMESTAMP':
339
// Ensure dates are Date objects
340
processed[name] = value instanceof Date ? value : new Date(value);
341
break;
342
case 'JSON':
343
// Parse JSON strings
344
processed[name] = typeof value === 'string' ? JSON.parse(value) : value;
345
break;
346
default:
347
processed[name] = value;
348
}
349
});
350
351
return processed;
352
};
353
```
354
355
### Geometry Types
356
357
Support for spatial/geometry data types using GeoJSON format.
358
359
```typescript { .api }
360
import { Geometry } from 'geojson';
361
362
// Geometry types are represented using the standard GeoJSON format
363
interface Point extends Geometry {
364
type: 'Point';
365
coordinates: [number, number] | [number, number, number];
366
}
367
368
interface LineString extends Geometry {
369
type: 'LineString';
370
coordinates: Array<[number, number] | [number, number, number]>;
371
}
372
373
interface Polygon extends Geometry {
374
type: 'Polygon';
375
coordinates: Array<Array<[number, number] | [number, number, number]>>;
376
}
377
```
378
379
**Geometry Usage Example:**
380
381
```typescript
382
// Insert geometry data
383
await connection.execute(
384
"INSERT INTO locations (name, point) VALUES (?, ?)",
385
['Central Park', { type: 'Point', coordinates: [-73.965355, 40.782865] }]
386
);
387
388
// Query geometry data
389
const locations = await connection.query("SELECT name, ST_AsGeoJSON(point) as point FROM locations");
390
391
locations.forEach(row => {
392
const point = JSON.parse(row.point) as Point;
393
console.log(`${row.name}: ${point.coordinates[1]}, ${point.coordinates[0]}`);
394
});
395
```
396
397
### Stream Callback Types
398
399
Type definitions for stream-related callback functions.
400
401
```typescript { .api }
402
/**
403
* Callback function for stream operations
404
* @param err - Error if stream creation failed
405
* @param stream - Duplex stream for database communication
406
*/
407
function StreamCallback(err?: Error, stream?: Duplex): void;
408
```
409
410
### Utility Types
411
412
Additional utility types for working with MariaDB data.
413
414
```typescript { .api }
415
/**
416
* User connection configuration for changeUser operations
417
*/
418
interface UserConnectionConfig {
419
/** Database name to switch to */
420
database?: string;
421
422
/** Connection attributes to send to server */
423
connectAttributes?: any;
424
425
/** Character set for the connection */
426
charset?: string;
427
428
/** Collation for the connection */
429
collation?: string;
430
431
/** Username to authenticate as */
432
user?: string;
433
434
/** Password for authentication */
435
password?: string;
436
}
437
438
/**
439
* Logger configuration for debugging and monitoring
440
*/
441
interface LoggerConfig {
442
/** Network-level logging */
443
network?: (msg: string) => void;
444
445
/** Query-level logging */
446
query?: (msg: string) => void;
447
448
/** Error logging */
449
error?: (err: Error) => void;
450
451
/** Warning logging */
452
warning?: (msg: string) => void;
453
}
454
455
/**
456
* Collation information for character encoding
457
*/
458
interface Collation {
459
/** Collation index number */
460
index: number;
461
462
/** Collation name */
463
name: string;
464
465
/** Character encoding */
466
encoding: string;
467
468
/** Maximum character length in bytes */
469
maxLength: number;
470
471
/** Get collation by encoding name */
472
fromEncoding(encoding: string): Collation;
473
474
/** Get collation by index */
475
fromIndex(index: number): Collation;
476
477
/** Get collation by name */
478
fromName(name: string): Collation;
479
}
480
481
/**
482
* Result structure for INSERT/UPDATE/DELETE operations
483
*/
484
interface UpsertResult {
485
/** Number of rows affected by the operation */
486
affectedRows: number;
487
488
/** Auto-generated ID from INSERT operations */
489
insertId: number | bigint;
490
491
/** Warning status from the server */
492
warningStatus: number;
493
}
494
495
/**
496
* Server version information
497
*/
498
interface ServerVersion {
499
/** Raw version string from server */
500
raw: string;
501
502
/** Whether server is MariaDB (true) or MySQL (false) */
503
mariaDb: boolean;
504
505
/** Major version number */
506
major: number;
507
508
/** Minor version number */
509
minor: number;
510
511
/** Patch version number */
512
patch: number;
513
}
514
515
/**
516
* Connection information and server details
517
*/
518
interface ConnectionInfo {
519
/** Server connection thread ID */
520
threadId: number | null;
521
522
/** Connection status flags */
523
status: number;
524
525
/** Server version information */
526
serverVersion: ServerVersion;
527
528
/** Connection collation */
529
collation: any;
530
531
/** Server capability flags */
532
serverCapabilities: number;
533
534
/** Check if server is MariaDB */
535
isMariaDB(): boolean;
536
537
/** Check if server version meets minimum requirement */
538
hasMinVersion(major: number, minor: number, patch: number): boolean;
539
}
540
```
541
542
### Type System Best Practices
543
544
**Working with Large Numbers:**
545
546
```typescript
547
// Configure safe number handling
548
const connection = await mariadb.createConnection({
549
host: "localhost",
550
user: "root",
551
password: "password",
552
database: "test",
553
554
// Keep BigInt as BigInt, don't convert to number
555
bigIntAsNumber: false,
556
557
// Keep decimals as strings for precision
558
decimalAsNumber: false,
559
560
// Throw error if number conversion would be unsafe
561
checkNumberRange: true,
562
563
// Convert insert IDs to numbers for convenience
564
insertIdAsNumber: true
565
});
566
```
567
568
**Custom Type Validation:**
569
570
```typescript
571
const validateTypeCast: TypeCastFunction = (field, next) => {
572
const value = next();
573
574
// Validate email format for email columns
575
if (field.name() === 'email' && typeof value === 'string') {
576
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
577
if (!emailRegex.test(value)) {
578
throw new Error(`Invalid email format: ${value}`);
579
}
580
}
581
582
// Validate date ranges
583
if (field.type === 'DATE' && value instanceof Date) {
584
const minDate = new Date('1900-01-01');
585
const maxDate = new Date('2100-01-01');
586
if (value < minDate || value > maxDate) {
587
throw new Error(`Date out of valid range: ${value}`);
588
}
589
}
590
591
return value;
592
};
593
```