|
|
|
import { NodeAdapterError } from "./node_adapter_error.mjs";
|
|
|
|
import { ResponseWrapper } from "./response_wrapper.mjs";
|
|
|
|
import { log } from "./log.mjs";
|
|
|
|
|
|
|
|
|
|
|
|
export class QueryWrapper {
|
|
|
|
constructor(sql, ...args) {
|
|
|
|
this.sql = sql.trim();
|
|
|
|
this.args = args;
|
|
|
|
this.operation = sql.replace(/[^a-z].*/i, "").toUpperCase();
|
|
|
|
}
|
|
|
|
|
|
|
|
isAnyOf(...operations) {
|
|
|
|
for (const op of operations) {
|
|
|
|
if(op.toUpperCase() === this.operation) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
execute(db) {
|
|
|
|
if (this.isAnyOf("INSERT", "UPDATE", "DELETE")) {
|
|
|
|
return this.executeRun(db);
|
|
|
|
} else {
|
|
|
|
return this.executeAll(db);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
executeRun(db) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const self = this;
|
|
|
|
|
|
|
|
log(this.sql);
|
|
|
|
db.run(this.sql, ...this.args, function (err) {
|
|
|
|
if (err) {
|
|
|
|
reject(NodeAdapterError.from(err));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = {};
|
|
|
|
|
|
|
|
if (self.isAnyOf("INSERT")) {
|
|
|
|
result.insertId = this.lastID;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (self.isAnyOf("UPDATE", "DELETE")) {
|
|
|
|
result.rowsAffected = this.changes;
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve(ResponseWrapper.success(result));
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
executeAll(db) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
log(this.sql);
|
|
|
|
db.all(this.sql, ...this.args, function (err, rows) {
|
|
|
|
if (err) {
|
|
|
|
reject(NodeAdapterError.from(err));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
resolve(ResponseWrapper.success({rows}));
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|