import DBConnectionManager from "../database/DBConnectionManager"; import CommonDao from "../database/CommonDao"; import {logger} from "../logger/Logger"; import RequestContext from "../scope/RequestContext"; import {CONNECTION_END_TYPE, CONNECTIONS, DB_TYPE} from "../@types/types"; import Bean from "../decorators/Bean"; @Bean() export default class SqlSession{ public dao!:CommonDao|null; private context: RequestContext|undefined; constructor(_context?:RequestContext) { this.setContext(_context); } public setContext(_context?:RequestContext) { this.context = _context; } public async createDao(type?:DB_TYPE):Promise{ if(this.dao) await this.destroy(); // if(this.dao) return this.dao; const dbManager:DBConnectionManager = DBConnectionManager.getInstance(type); const conn:CONNECTIONS = await dbManager.getConnection(); if (conn) { try{ const dbconfig:any = eval('conn.conn.config'); logger.debug(`Context[${this.context?.id}] connection [host:${dbconfig.host}:${dbconfig.port}]`); }catch(e){ console.log(e); } }else{ logger.error(`Context[${this.context?.id}] db connection failed.`); } this.dao = new CommonDao(); this.dao.connection = conn; // transaction start await this.dao.connection.beginTransaction(); return this.dao; } public async rollback() { if(this.dao && this.dao.connection) await this.dao.connection.rollback(); } public async commit() { if(this.dao && this.dao.connection) await this.dao.connection.commit(); } public async destroy(mode?:CONNECTION_END_TYPE) { try{ if(!this.dao || !this.dao.connection) return; switch (mode) { case CONNECTION_END_TYPE.COMMIT: await this.dao.connection.commit() break; case CONNECTION_END_TYPE.ROLLBACK: await this.dao.connection.rollback() break; } this.dao.connection.release(); }catch(e){ logger.error("sql session destroy failed : "+e); } this.dao = null; } public release() { if(!this.dao || !this.dao.connection) return; this.dao.connection.release(); } }