You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.6 KiB
70 lines
1.6 KiB
import { NodeAdapterError } from "./node_adapter_error.mjs"; |
|
import { QueryWrapper } from "./query_wrapper.mjs"; |
|
import { ResponseWrapper } from "./response_wrapper.mjs"; |
|
import { enableDebug, log } from "./log.mjs"; |
|
|
|
|
|
export class DatabaseWrapper { |
|
constructor(db) { |
|
this.db = db; |
|
} |
|
|
|
close() { |
|
return new Promise((resolve, reject) => { |
|
this.db.close((err) => { |
|
if (err) { |
|
reject(NodeAdapterError.from(err)); |
|
return; |
|
} |
|
resolve(); |
|
}); |
|
}); |
|
} |
|
|
|
sql(sql, ...args) { |
|
const query = new QueryWrapper(sql); |
|
|
|
if (query.isAnyOf("INSERT", "UPDATE", "DELETE")) { |
|
return this.executeRun(query, ...args); |
|
} else { |
|
return this.executeAll(query, ...args); |
|
} |
|
} |
|
|
|
executeRun(query, ...args) { |
|
return new Promise((resolve, reject) => { |
|
log(query.sql); |
|
this.db.run(query.sql, ...args, function (err) { |
|
if (err) { |
|
reject(NodeAdapterError.from(err)); |
|
return; |
|
} |
|
|
|
const result = {}; |
|
|
|
if (query.isAnyOf("INSERT")) { |
|
result.insertId = this.lastID; |
|
} |
|
|
|
if (query.isAnyOf("UPDATE", "DELETE")) { |
|
result.rowsAffected = this.changes; |
|
} |
|
|
|
resolve(ResponseWrapper.success(result)); |
|
}); |
|
}); |
|
} |
|
|
|
executeAll(query, ...args) { |
|
return new Promise((resolve, reject) => { |
|
log(query.sql); |
|
this.db.all(query.sql, ...args, function (err, rows) { |
|
if (err) { |
|
reject(NodeAdapterError.from(err)); |
|
return; |
|
} |
|
resolve(ResponseWrapper.success({rows})); |
|
}); |
|
}); |
|
} |
|
} |