import SqlParse from "./SqlParse" import {MysqlError, PoolConnection} from "mysql" import { PojoType } from "../../../../type/type" import {IDao} from "../../../interface" import DataSource from "./DataSource" export default class MysqlDao{ private dataSource = new DataSource() public connection?: PoolConnection = undefined private keepAlive: boolean = false public async getConnection(): Promise{ if(!this.connection){ this.connection = await this.dataSource.getConnection(); } return this.connection } protected async query(sql: SqlParse): Promise>{ const conn: PoolConnection = await this.getConnection() return new Promise((resolve, reject) => { conn.query(sql.toString(), (err: MysqlError, data: any) => { if(err){ this.releaseConnection() reject(err.message) }else{ resolve(data) } if(!this.keepAlive){ this.releaseConnection() } }) }) } protected async execute(sql: SqlParse): Promise{ const conn: PoolConnection = await this.getConnection() return new Promise((resolve, reject) => { conn.query(sql.toString(), (err: MysqlError, data: any) => { if(err){ this.releaseConnection() reject(err.message) }else{ resolve(data) } }) if(!this.keepAlive){ this.releaseConnection() } }) } public setAlive(): void{ this.keepAlive = true } private releaseConnection(): void{ this.connection && this.connection.release() this.connection = undefined } }