@egi/smart-db
Version:
Unified Smart DB Access
1 lines • 1.46 kB
JavaScript
import _ from"lodash";import Mysql from"mysql";import{SmartDb}from"../smart-db";export class SmartDbMysql extends SmartDb{constructor(t){t.config&&t.connect?(super(t.config),this.db=t):(super(t),this.db=Mysql.createConnection(t))}close(){return new Promise((t=>{this.db.end((r=>{this.isReady=!1,r?(this.lastError=r,t(!1)):t(!0)}))}))}commit(){return new Promise(((t,r)=>{this.db.commit((e=>{e?(this.lastError=e,r(e)):t()}))}))}exec(t){return new Promise(((r,e)=>{try{this.db.query(t,((t,s,o)=>{t?(this.lastError=t,e(t)):r()}))}catch(t){this.lastError=t,e(t)}}))}exists(t,r,e){return new Promise(((r,e)=>{const s=_.isString(t)?t:t.getTableName();this.db.query(`show tables like '${s}'`,((t,s,o)=>{t?(this.lastError=t,e(t)):r(s&&s.length>0)}))}))}getDatabaseType(){return"mysql"}getDbQuote(){return"`"}getTableInfo(t){throw new Error("Method not implemented (getTableInfo)")}rollback(){return new Promise(((t,r)=>{this.db.rollback((e=>{e?(this.lastError=e,r(e)):t()}))}))}statementRun(t){return new Promise(((r,e)=>{this.db.query(t.sql,t.values,((t,s,o)=>{if(t)this.lastError=t,e(t);else{const t={changes:s.changedRows,affected:s.affectedRows,lastId:s.insertId};r(t)}}))}))}statementGet(t){return new Promise(((r,e)=>{try{this.db.query(t.sql,t.values,((t,s,o)=>{t?(this.lastError=t,e(t)):r(s&&s[0])}))}catch(t){this.lastError=t,e(t)}}))}statementGetAll(t){return new Promise(((r,e)=>{this.db.query(t.sql,t.values,((t,s,o)=>{t?(this.lastError=t,e(t)):r(s&&s)}))}))}}