You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1003 lines
34 KiB

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