UNPKG

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