UNPKG

@egi/smart-db

Version:

Unified Smart DB Access

1 lines 1.47 kB
import _ from"lodash";import Mysql from"mysql";import{SmartDb}from"../smart-db";export class SmartDbMysql2 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,e)=>{this.db.end((e=>{this.isReady=!1,e?(this.lastError=e,t(!1)):t(!0)}))}))}commit(){return new Promise(((t,e)=>{this.db.commit((r=>{r?(this.lastError=r,e(r)):t()}))}))}exec(t){return new Promise(((e,r)=>{try{this.db.query(t,((t,s,o)=>{t?(this.lastError=t,r(t)):e()}))}catch(t){r(t)}}))}exists(t,e,r){return new Promise(((e,r)=>{const s=_.isString(t)?t:t.getTableName();this.db.query(`show tables like '${s}'`,((t,s,o)=>{t?(this.lastError=t,r(t)):e(s&&s.length>0)}))}))}getDatabaseType(){return"mysql"}getDbQuote(){return"`"}getTableInfo(t){throw new Error("Method not implemented (getTableInfo)")}rollback(){return new Promise(((t,e)=>{this.db.rollback((r=>{r?(this.lastError=r,e(r)):t()}))}))}statementRun(t){return new Promise(((e,r)=>{this.db.query(t.sql,t.values,((t,s,o)=>{if(t)this.lastError=t,r(t);else{const t={changes:s.changedRows,affected:s.affectedRows,lastId:s.insertId};e(t)}}))}))}statementGet(t){return new Promise(((e,r)=>{try{this.db.query(t.sql,t.values,((t,s,o)=>{t?(this.lastError=t,r(t)):e(s&&s[0])}))}catch(t){this.lastError=t,r(t)}}))}statementGetAll(t){return new Promise(((e,r)=>{this.db.query(t.sql,t.values,((t,s,o)=>{t?(this.lastError=t,r(t)):(console.log(o),e(s&&s))}))}))}}