| 23 | }; |
| 24 | |
| 25 | export default class MySqlDatabase implements DatabaseInterface { |
| 26 | public readonly connection: Pool|PoolConnection; |
| 27 | |
| 28 | constructor(connection: PoolConfig|Pool|PoolConnection) { |
| 29 | if (isPoolOrPoolConnection(connection)) { |
| 30 | this.connection = <Pool|PoolConnection>connection; |
| 31 | } else { |
| 32 | this.connection = createPool(<PoolConfig>connection); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | async disconnect(): Promise<void> { |
| 37 | if (isPool(this.connection)) { |
| 38 | return new Promise((resolve, reject) => { |
| 39 | this.connection.end(err => { |
| 40 | if (err) { |
| 41 | reject(err); |
| 42 | } else { |
| 43 | resolve(); |
| 44 | } |
| 45 | }); |
| 46 | }); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | indexToPlaceholder (i: number): string { |
| 51 | return '?'; |
| 52 | } |
| 53 | |
| 54 | async query(query: SqlQuery): Promise<any[]> { |
| 55 | return new Promise((resolve, reject) => { |
| 56 | const compiledQuery = query.compile(this.indexToPlaceholder, formatIdentifier); |
| 57 | |
| 58 | this.connection.query( |
| 59 | compiledQuery.sql, |
| 60 | <any[]><any>compiledQuery.params, |
| 61 | (error, rows) => { |
| 62 | if (error) { |
| 63 | reject(error); |
| 64 | } else { |
| 65 | resolve(rows); |
| 66 | } |
| 67 | }, |
| 68 | ); |
| 69 | }); |
| 70 | } |
| 71 | |
| 72 | async sequence<T>( |
| 73 | sequence: (sequenceDb: MySqlDatabase) => Promise<T>, |
| 74 | ): Promise<T> { |
| 75 | if (!isPool(this.connection)) { |
| 76 | // Already in a sequence, so another call changes nothing but works for conveniency |
| 77 | return sequence(this); |
| 78 | } |
| 79 | |
| 80 | const client: PoolConnection = await new Promise((resolve, reject) => { |
| 81 | (<Pool>this.connection).getConnection((error: MysqlError, connection: PoolConnection) => { |
| 82 | if (error) { |
nothing calls this directly
no outgoing calls
no test coverage detected