UNPKG

22.8 kBTypeScriptView Raw
1// Type definitions for mysql 2.15
2// Project: https://github.com/mysqljs/mysql
3// Definitions by: William Johnston <https://github.com/wjohnsto>
4// Kacper Polak <https://github.com/kacepe>
5// Krittanan Pingclasai <https://github.com/kpping>
6// James Munro <https://github.com/jdmunro>
7// Sanders DeNardi <https://github.com/sedenardi>
8// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
9// TypeScript Version: 2.1
10
11/// <reference types="node" />
12
13import stream = require('stream');
14import tls = require('tls');
15import events = require('events');
16
17export interface EscapeFunctions {
18 /**
19 * Escape an untrusted string to be used as a SQL value. Use this on user
20 * provided data.
21 * @param value Value to escape
22 * @param stringifyObjects If true, don't convert objects into SQL lists
23 * @param timeZone Convert dates from UTC to the given timezone.
24 */
25 escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
26
27 /**
28 * Escape an untrusted string to be used as a SQL identifier (database,
29 * table, or column name). Use this on user provided data.
30 * @param value Value to escape.
31 * @param forbidQualified Don't allow qualified identifiers (eg escape '.')
32 */
33 escapeId(value: string, forbidQualified?: boolean): string;
34
35 /**
36 * Safely format a SQL query containing multiple untrusted values.
37 * @param sql Query, with insertion points specified with ? (for values) or
38 * ?? (for identifiers)
39 * @param values Array of objects to insert.
40 * @param stringifyObjects If true, don't convert objects into SQL lists
41 * @param timeZone Convert dates from UTC to the given timezone.
42 */
43 format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string;
44}
45
46/**
47 * Escape an untrusted string to be used as a SQL value. Use this on user
48 * provided data.
49 * @param value Value to escape
50 * @param stringifyObjects If true, don't convert objects into SQL lists
51 * @param timeZone Convert dates from UTC to the given timezone.
52 */
53export function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
54
55/**
56 * Escape an untrusted string to be used as a SQL identifier (database,
57 * table, or column name). Use this on user provided data.
58 * @param value Value to escape.
59 * @param forbidQualified Don't allow qualified identifiers (eg escape '.')
60 */
61export function escapeId(value: string, forbidQualified?: boolean): string;
62
63/**
64 * Safely format a SQL query containing multiple untrusted values.
65 * @param sql Query, with insertion points specified with ? (for values) or
66 * ?? (for identifiers)
67 * @param values Array of objects to insert.
68 * @param stringifyObjects If true, don't convert objects into SQL lists
69 * @param timeZone Convert dates from UTC to the given timezone.
70 */
71export function format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string;
72
73export function createConnection(connectionUri: string | ConnectionConfig): Connection;
74
75export function createPool(config: PoolConfig | string): Pool;
76
77export function createPoolCluster(config?: PoolClusterConfig): PoolCluster;
78
79/**
80 * Create a string that will be inserted unescaped with format(), escape().
81 * Note: the value will still be escaped if used as an identifier (??) by
82 * format().
83 * @param sql
84 */
85export function raw(sql: string): {
86 toSqlString: () => string
87};
88
89export interface Connection extends EscapeFunctions, events.EventEmitter {
90 config: ConnectionConfig;
91
92 state: 'connected' | 'authenticated' | 'disconnected' | 'protocol_error' | string;
93
94 threadId: number | null;
95
96 createQuery: QueryFunction;
97
98 connect(callback?: (err: MysqlError, ...args: any[]) => void): void;
99
100 connect(options: any, callback?: (err: MysqlError, ...args: any[]) => void): void;
101
102 changeUser(options: ConnectionOptions, callback?: (err: MysqlError) => void): void;
103 changeUser(callback: (err: MysqlError) => void): void;
104
105 beginTransaction(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
106
107 beginTransaction(callback: (err: MysqlError) => void): void;
108
109 commit(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
110 commit(callback: (err: MysqlError) => void): void;
111
112 rollback(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
113 rollback(callback: (err: MysqlError) => void): void;
114
115 query: QueryFunction;
116
117 ping(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
118 ping(callback: (err: MysqlError) => void): void;
119
120 statistics(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
121 statistics(callback: (err: MysqlError) => void): void;
122
123 /**
124 * Close the connection. Any queued data (eg queries) will be sent first. If
125 * there are any fatal errors, the connection will be immediately closed.
126 * @param callback Handler for any fatal error
127 */
128 end(callback?: (err?: MysqlError) => void): void;
129 end(options: any, callback: (err?: MysqlError) => void): void;
130
131 /**
132 * Close the connection immediately, without waiting for any queued data (eg
133 * queries) to be sent. No further events or callbacks will be triggered.
134 */
135 destroy(): void;
136
137 /**
138 * Pause the connection. No more 'result' events will fire until resume() is
139 * called.
140 */
141 pause(): void;
142
143 /**
144 * Resume the connection.
145 */
146 resume(): void;
147}
148
149export interface PoolConnection extends Connection {
150 release(): void;
151
152 /**
153 * Close the connection. Any queued data (eg queries) will be sent first. If
154 * there are any fatal errors, the connection will be immediately closed.
155 * @param callback Handler for any fatal error
156 */
157 end(): void;
158
159 /**
160 * Close the connection immediately, without waiting for any queued data (eg
161 * queries) to be sent. No further events or callbacks will be triggered.
162 */
163 destroy(): void;
164}
165
166export interface Pool extends EscapeFunctions, events.EventEmitter {
167 config: PoolActualConfig;
168
169 getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void;
170
171 acquireConnection(
172 connection: PoolConnection,
173 callback: (err: MysqlError, connection: PoolConnection) => void,
174 ): void;
175
176 /**
177 * Close the connection. Any queued data (eg queries) will be sent first. If
178 * there are any fatal errors, the connection will be immediately closed.
179 * @param callback Handler for any fatal error
180 */
181 end(callback?: (err: MysqlError) => void): void;
182
183 query: QueryFunction;
184}
185
186export interface PoolCluster extends events.EventEmitter {
187 config: PoolClusterConfig;
188
189 add(config: PoolConfig): void;
190
191 add(id: string, config: PoolConfig): void;
192
193 /**
194 * Close the connection. Any queued data (eg queries) will be sent first. If
195 * there are any fatal errors, the connection will be immediately closed.
196 * @param callback Handler for any fatal error
197 */
198 end(callback?: (err: MysqlError) => void): void;
199
200 of(pattern: string, selector?: string): Pool;
201 of(pattern: undefined | null | false, selector: string): Pool;
202
203 /**
204 * remove all pools which match pattern
205 */
206 remove(pattern: string): void;
207
208 getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void;
209
210 getConnection(pattern: string, callback: (err: MysqlError, connection: PoolConnection) => void): void;
211
212 getConnection(
213 pattern: string,
214 selector: string,
215 callback: (err: MysqlError, connection: PoolConnection) => void,
216 ): void;
217}
218
219// related to Query
220export type packetCallback = (packet: any) => void;
221
222export interface Query {
223 /**
224 * Template query
225 */
226 sql: string;
227
228 /**
229 * Values for template query
230 */
231 values?: string[] | undefined;
232
233 /**
234 * Default true
235 */
236 typeCast?: TypeCast | undefined;
237
238 /**
239 * Default false
240 */
241 nestedTables: boolean;
242
243 /**
244 * Emits a query packet to start the query
245 */
246 start(): void;
247
248 /**
249 * Determines the packet class to use given the first byte of the packet.
250 *
251 * @param byte The first byte of the packet
252 * @param parser The packet parser
253 */
254 determinePacket(byte: number, parser: any): any;
255
256 OkPacket: packetCallback;
257 ErrorPacket: packetCallback;
258 ResultSetHeaderPacket: packetCallback;
259 FieldPacket: packetCallback;
260 EofPacket: packetCallback;
261
262 RowDataPacket(packet: any, parser: any, connection: Connection): void;
263
264 /**
265 * Creates a Readable stream with the given options
266 *
267 * @param options The options for the stream. (see readable-stream package)
268 */
269 stream(options?: stream.ReadableOptions): stream.Readable;
270
271 on(ev: string, callback: (...args: any[]) => void): Query;
272
273 on(ev: 'result', callback: (row: any, index: number) => void): Query;
274
275 on(ev: 'error', callback: (err: MysqlError) => void): Query;
276
277 on(ev: 'fields', callback: (fields: FieldInfo[], index: number) => void): Query;
278
279 on(ev: 'packet', callback: (packet: any) => void): Query;
280
281 on(ev: 'end', callback: () => void): Query;
282}
283
284export interface GeometryType extends Array<{ x: number; y: number } | GeometryType> {
285 x: number;
286 y: number;
287}
288
289export type TypeCast =
290 | boolean
291 | ((
292 field: UntypedFieldInfo & {
293 type: string;
294 length: number;
295 string(): null | string;
296 buffer(): null | Buffer;
297 geometry(): null | GeometryType;
298 },
299 next: () => void,
300 ) => any);
301
302export type queryCallback = (err: MysqlError | null, results?: any, fields?: FieldInfo[]) => void;
303
304// values can be non [], see custom format (https://github.com/mysqljs/mysql#custom-format)
305export interface QueryFunction {
306 (query: Query): Query;
307
308 (options: string | QueryOptions, callback?: queryCallback): Query;
309
310 (options: string | QueryOptions, values: any, callback?: queryCallback): Query;
311}
312
313export interface QueryOptions {
314 /**
315 * The SQL for the query
316 */
317 sql: string;
318
319 /**
320 * Values for template query
321 */
322 values?: any;
323
324 /**
325 * Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for
326 * operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout
327 * operations through the client. This means that when a timeout is reached, the connection it occurred on will be
328 * destroyed and no further operations can be performed.
329 */
330 timeout?: number | undefined;
331
332 /**
333 * Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be
334 * nested as tableName_fieldName
335 */
336 nestTables?: any;
337
338 /**
339 * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
340 * to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
341 *
342 * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
343 *
344 * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
345 *
346 * field.string()
347 * field.buffer()
348 * field.geometry()
349 *
350 * are aliases for
351 *
352 * parser.parseLengthCodedString()
353 * parser.parseLengthCodedBuffer()
354 * parser.parseGeometryValue()
355 *
356 * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
357 */
358 typeCast?: TypeCast | undefined;
359}
360
361export interface ConnectionOptions {
362 /**
363 * The MySQL user to authenticate as
364 */
365 user?: string | undefined;
366
367 /**
368 * The password of that MySQL user
369 */
370 password?: string | undefined;
371
372 /**
373 * Name of the database to use for this connection
374 */
375 database?: string | undefined;
376
377 /**
378 * The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci).
379 * If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used.
380 * (Default: 'UTF8_GENERAL_CI')
381 */
382 charset?: string | undefined;
383
384 /**
385 * Number of milliseconds
386 */
387 timeout?: number | undefined;
388}
389
390export interface ConnectionConfig extends ConnectionOptions {
391 /**
392 * The hostname of the database you are connecting to. (Default: localhost)
393 */
394 host?: string | undefined;
395
396 /**
397 * The port number to connect to. (Default: 3306)
398 */
399 port?: number | undefined;
400
401 /**
402 * The source IP address to use for TCP connection
403 */
404 localAddress?: string | undefined;
405
406 /**
407 * The path to a unix domain socket to connect to. When used host and port are ignored
408 */
409 socketPath?: string | undefined;
410
411 /**
412 * The timezone used to store local dates. (Default: 'local')
413 */
414 timezone?: string | undefined;
415
416 /**
417 * The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default: 10 seconds)
418 */
419 connectTimeout?: number | undefined;
420
421 /**
422 * Stringify objects instead of converting to values. (Default: 'false')
423 */
424 stringifyObjects?: boolean | undefined;
425
426 /**
427 * Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: false)
428 */
429 insecureAuth?: boolean | undefined;
430
431 /**
432 * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
433 * to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
434 *
435 * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
436 *
437 * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
438 *
439 * field.string()
440 * field.buffer()
441 * field.geometry()
442 *
443 * are aliases for
444 *
445 * parser.parseLengthCodedString()
446 * parser.parseLengthCodedBuffer()
447 * parser.parseGeometryValue()
448 *
449 * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
450 */
451 typeCast?: TypeCast | undefined;
452
453 /**
454 * A custom query format function
455 */
456 queryFormat?(query: string, values: any): string;
457
458 /**
459 * When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option
460 * (Default: false)
461 */
462 supportBigNumbers?: boolean | undefined;
463
464 /**
465 * Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be
466 * always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving
467 * bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately
468 * represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)
469 * (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects.
470 * This option is ignored if supportBigNumbers is disabled.
471 */
472 bigNumberStrings?: boolean | undefined;
473
474 /**
475 * Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript
476 * Date objects. Can be true/false or an array of type names to keep as strings. (Default: false)
477 */
478 dateStrings?: boolean | Array<'TIMESTAMP' | 'DATETIME' | 'DATE'> | undefined;
479
480 /**
481 * This will print all incoming and outgoing packets on stdout.
482 * You can also restrict debugging to packet types by passing an array of types (strings) to debug;
483 *
484 * (Default: false)
485 */
486 debug?: boolean | string[] | Types[] | undefined;
487
488 /**
489 * Generates stack traces on errors to include call site of library entrance ("long stack traces"). Slight
490 * performance penalty for most calls. (Default: true)
491 */
492 trace?: boolean | undefined;
493
494 /**
495 * Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false)
496 */
497 multipleStatements?: boolean | undefined;
498
499 /**
500 * List of connection flags to use other than the default ones. It is also possible to blacklist default ones
501 */
502 flags?: string | string[] | undefined;
503
504 /**
505 * object with ssl parameters or a string containing name of ssl profile
506 */
507 ssl?: string | (tls.SecureContextOptions & { rejectUnauthorized?: boolean | undefined }) | undefined;
508}
509
510export interface PoolSpecificConfig {
511 /**
512 * The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout,
513 * because acquiring a pool connection does not always involve making a connection. (Default: 10 seconds)
514 */
515 acquireTimeout?: number | undefined;
516
517 /**
518 * Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue
519 * the connection request and call it when one becomes available. If false, the pool will immediately call back with an error.
520 * (Default: true)
521 */
522 waitForConnections?: boolean | undefined;
523
524 /**
525 * The maximum number of connections to create at once. (Default: 10)
526 */
527 connectionLimit?: number | undefined;
528
529 /**
530 * The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there
531 * is no limit to the number of queued connection requests. (Default: 0)
532 */
533 queueLimit?: number | undefined;
534}
535
536export interface PoolConfig extends PoolSpecificConfig, ConnectionConfig {
537}
538
539export interface PoolActualConfig extends PoolSpecificConfig {
540 connectionConfig: ConnectionConfig;
541}
542
543export interface PoolClusterConfig {
544 /**
545 * If true, PoolCluster will attempt to reconnect when connection fails. (Default: true)
546 */
547 canRetry?: boolean | undefined;
548
549 /**
550 * If connection fails, node's errorCount increases. When errorCount is greater than removeNodeErrorCount,
551 * remove a node in the PoolCluster. (Default: 5)
552 */
553 removeNodeErrorCount?: number | undefined;
554
555 /**
556 * If connection fails, specifies the number of milliseconds before another connection attempt will be made.
557 * If set to 0, then node will be removed instead and never re-used. (Default: 0)
558 */
559 restoreNodeTimeout?: number | undefined;
560
561 /**
562 * The default selector. (Default: RR)
563 * RR: Select one alternately. (Round-Robin)
564 * RANDOM: Select the node by random function.
565 * ORDER: Select the first node available unconditionally.
566 */
567 defaultSelector?: string | undefined;
568}
569
570export interface MysqlError extends Error {
571 /**
572 * Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'),
573 * a node.js error (e.g. 'ECONNREFUSED') or an internal error
574 * (e.g. 'PROTOCOL_CONNECTION_LOST').
575 */
576 code: string;
577
578 /**
579 * The error number for the error code
580 */
581 errno: number;
582
583 /**
584 * The sql state marker
585 */
586 sqlStateMarker?: string | undefined;
587
588 /**
589 * The sql state
590 */
591 sqlState?: string | undefined;
592
593 /**
594 * The field count
595 */
596 fieldCount?: number | undefined;
597
598 /**
599 * The stack trace for the error
600 */
601 stack?: string | undefined;
602
603 /**
604 * Boolean, indicating if this error is terminal to the connection object.
605 */
606 fatal: boolean;
607
608 /**
609 * SQL of failed query
610 */
611 sql?: string | undefined;
612
613 /**
614 * Error message from MySQL
615 */
616 sqlMessage?: string | undefined;
617}
618
619// Result from an insert, update, or delete statement.
620export interface OkPacket {
621 fieldCount: number;
622 /**
623 * The number of affected rows from an insert, update, or delete statement.
624 */
625 affectedRows: number;
626 /**
627 * The insert id after inserting a row into a table with an auto increment primary key.
628 */
629 insertId: number;
630 serverStatus?: number | undefined;
631 warningCount?: number | undefined;
632 /**
633 * The server result message from an insert, update, or delete statement.
634 */
635 message: string;
636 /**
637 * The number of changed rows from an update statement. "changedRows" differs from "affectedRows" in that it does not count updated rows whose values were not changed.
638 */
639 changedRows: number;
640 protocol41: boolean;
641}
642
643export const enum Types {
644 DECIMAL = 0x00, // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html)
645 TINY = 0x01, // aka TINYINT, 1 byte
646 SHORT = 0x02, // aka SMALLINT, 2 bytes
647 LONG = 0x03, // aka INT, 4 bytes
648 FLOAT = 0x04, // aka FLOAT, 4-8 bytes
649 DOUBLE = 0x05, // aka DOUBLE, 8 bytes
650 NULL = 0x06, // NULL (used for prepared statements, I think)
651 TIMESTAMP = 0x07, // aka TIMESTAMP
652 LONGLONG = 0x08, // aka BIGINT, 8 bytes
653 INT24 = 0x09, // aka MEDIUMINT, 3 bytes
654 DATE = 0x0a, // aka DATE
655 TIME = 0x0b, // aka TIME
656 DATETIME = 0x0c, // aka DATETIME
657 YEAR = 0x0d, // aka YEAR, 1 byte (don't ask)
658 NEWDATE = 0x0e, // aka ?
659 VARCHAR = 0x0f, // aka VARCHAR (?)
660 BIT = 0x10, // aka BIT, 1-8 byte
661 TIMESTAMP2 = 0x11, // aka TIMESTAMP with fractional seconds
662 DATETIME2 = 0x12, // aka DATETIME with fractional seconds
663 TIME2 = 0x13, // aka TIME with fractional seconds
664 JSON = 0xf5, // aka JSON
665 NEWDECIMAL = 0xf6, // aka DECIMAL
666 ENUM = 0xf7, // aka ENUM
667 SET = 0xf8, // aka SET
668 TINY_BLOB = 0xf9, // aka TINYBLOB, TINYTEXT
669 MEDIUM_BLOB = 0xfa, // aka MEDIUMBLOB, MEDIUMTEXT
670 LONG_BLOB = 0xfb, // aka LONGBLOG, LONGTEXT
671 BLOB = 0xfc, // aka BLOB, TEXT
672 VAR_STRING = 0xfd, // aka VARCHAR, VARBINARY
673 STRING = 0xfe, // aka CHAR, BINARY
674 GEOMETRY = 0xff, // aka GEOMETRY
675}
676
677export interface UntypedFieldInfo {
678 catalog: string;
679 db: string;
680 table: string;
681 orgTable: string;
682 name: string;
683 orgName: string;
684 charsetNr: number;
685 length: number;
686 flags: number;
687 decimals: number;
688 default?: string | undefined;
689 zeroFill: boolean;
690 protocol41: boolean;
691}
692
693export interface FieldInfo extends UntypedFieldInfo {
694 type: Types;
695}