mgm
Version:
My generic modules
137 lines (123 loc) • 4.14 kB
JavaScript
let sql = require('sql.js');
let fs = require('fs');
class MySQLiteDB {
constructor() {
this.db = undefined;
this.location;
}
/**
* Abre uma conexão com o banco de dados. Caso o caminho até o banco de dados não seja informado, o banco de dado será criado em memória
* @returns {this} retorna a instância do MySQLiteDB
*/
connect(location = ':memory:') {
let buffer;
if (location === ':memory:') {
buffer = new Buffer(0);
this.db = new sql.Database(buffer);
} else {
this.location = location;
if (fs.existsSync(this.location)) {
buffer = fs.readFileSync(this.location);
this.db = new sql.Database(buffer);
} else {
buffer = new Buffer(0);
this.db = new sql.Database(buffer);
let data = this.db.export();
buffer = new Buffer(data);
fs.writeFileSync(this.location, buffer);
}
}
return this;
}
/**
* Fecha a conexão com o banco de dados.
*/
close() {
if (this.location) {
let data = this.db.export();
let buffer = new Buffer(data);
fs.writeFileSync(this.location, buffer);
this.db.close();
}
}
/**
* Delimita o ínício da transação que será finalizada através de um COMMIT ou ROLLBACK.
* @returns {this} retorna a instância do MySQLiteDB
*/
openTransaction() {
return this.update('BEGIN TRANSACTION;');
}
/**
* Confirma as alterações feitas no banco de dados.
* @param {String} sql
* @returns {this} retorna a instância do MySQLiteDB
*/
commit() {
return this.update('COMMIT TRANSACTION;');
}
/**
* Desfaz as alterações feitas no banco de dados.
* @param {String} sql
* @returns {this} retorna a instância do MySQLiteDB
*/
rollBack() {
return this.update('ROLLBACK TRANSACTION;');
}
/**
* Executa a query passada.
* @param {String} sql
* @returns {this} retorna a instância do MySQLiteDB
*/
update(sql) {
//this.db.run(sql), poderia ser esse método mas, o método this.db.exec também funciona com a diferença que não retorna nada;
let rs = this.query(sql);
if (rs.length > 0) {
console.log(rs);
}
return this;
}
/**
* Executa a query passada.
* @param {String} sql
* @returns {[]} retorna um array de objetos no formato: [{key:'value'}[,...]
*/
query(sql) {
let query = sql.replace(/[ ]{2,}/g, ' ');
let qrs = this.db.exec(query);
let rs = [];
qrs.forEach(qr => {
qr.values.forEach((value) => {
let result = {};
qr.columns.forEach((column, index) => {
result[column] = value[index];
});
rs.push(result);
});
});
if (query.indexOf('TRANSACTION') === -1) {
console.log(`\t[${query}][${this.getRowsModified()}/${rs.length} record(s) afected/returned]`);
} else {
console.log(`[${query}]`);
}
return rs;
}
/**
* Executa a query passada.
* @param {String} sql
* @returns {{key:'value'}} retorna um objeto no formato: {key:'value'}
* @throws {Error} dispara um erro caso a consulta retorne mais de um valor
*/
queryUnique(sql) {
let result = this.query(sql);
if (result.length > 1) {
throw new Error(`The query [${sql}] return more than one value, ${result.length} precisely.`);
}
}
/**
* @returns {number} retorna a quantidade de registros alterados na última consulta executada
*/
getRowsModified() {
return this.db.getRowsModified();
}
}
module.exports = new MySQLiteDB();