@smallprod/models
Version:
176 lines (175 loc) • 7.84 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const global_sql_1 = __importDefault(require("./global.sql"));
const mssql_1 = __importDefault(require("mssql"));
class GlobalMicrosoftModel extends global_sql_1.default {
constructor() {
super(...arguments);
this.pool = null;
this.transactionConnection = null;
this.disconnect = async () => {
var _a;
await ((_a = this.pool) === null || _a === void 0 ? void 0 : _a.close());
};
this.query = async (query, params, throwErrors = false) => {
if (!this.pool) {
if (throwErrors)
throw Error('No pool');
if (GlobalMicrosoftModel.debug)
console.error('No pool');
return null;
}
let request;
if (this.transactionConnection) {
request = new mssql_1.default.Request(this.transactionConnection);
}
else {
request = new mssql_1.default.Request(this.pool);
}
if (params) {
params.forEach((param, index) => {
request.input(index.toString(), param);
});
}
try {
return await request.query(query);
}
catch (err) {
if (GlobalMicrosoftModel.debug)
console.error(err);
}
return null;
};
this.insert = async (tableName, attributes) => {
const columns = attributes.map((a) => `\`${a.column}\``).join(', ');
const params = attributes.map((a, index) => `@${index + 1}`).join(', ');
const query = `INSERT INTO \`${tableName}\` (${columns}) VALUES (${params})`;
return await this.query(query, attributes.map((a) => a.value));
};
this.select = async (tableName, distinct = false, attributes = [], wheres = [], sorts = [], tableAlias = '', limit = -1, offset = 0, joins = [], groups = [], havings = []) => {
const query = `SELECT${distinct ? ' DISTINCT' : ''}${this.computeAttributes(attributes, '`')} FROM \`${tableName}\` ${tableAlias ? `AS ${tableAlias}` : ''} ${this.computeJoins(joins, '`', 'AS')}${this.computeWhere(wheres, '@', true, '`')}${this.computeGroupBy(groups)}${this.computeWhere(havings, '?', false, '`', 'HAVING')}${this.computeSort(sorts, '`')}${limit !== -1
? ` OFFSET ${offset} ROWS FETCH NEXT ${offset} ROWS ONLY`
: ''}`;
const havingAttr = this.getWhereAttributes(havings);
return await this.query(query, havingAttr.concat(this.getWhereAttributes(wheres)));
};
this.update = async (tableName, attributes, wheres) => {
var _a;
const columns = attributes.map((a) => `\`${a.column}\` = ?`).join(', ');
const query = `UPDATE \`${tableName}\` SET ${columns} ${this.computeWhere(wheres, '@', true, '`')}`;
return (_a = (await this.query(query, attributes.map((a) => a.value).concat(this.getWhereAttributes(wheres))))) === null || _a === void 0 ? void 0 : _a.rowsAffected.length;
};
this.delete = async (tableName, wheres) => {
var _a;
const query = `DELETE FROM \`${tableName}\` ${this.computeWhere(wheres, '@', true, '`')}`;
return (_a = (await this.query(query, this.getWhereAttributes(wheres)))) === null || _a === void 0 ? void 0 : _a.rowsAffected.length;
};
this.createTable = async (tableName, fields) => {
const query = `CREATE TABLE ${tableName} (${fields
.map((f) => this.formatFieldForTableManagement(f))
.join(', ')})`;
return await this.query(query);
};
this.removeTable = async (tableName) => {
const query = `DROP TABLE ${tableName}`;
return await this.query(query);
};
this.alterTable = async (tableName, fieldsToAdd, fieldsToRemove) => {
await fieldsToRemove.reduce(async (prev, cur) => {
await prev;
const query = `ALTER TABLE ${tableName} DROP COLUMN ${cur}`;
await this.query(query);
}, Promise.resolve());
await fieldsToAdd.reduce(async (prev, cur) => {
await prev;
const query = `ALTER TABLE ${tableName} ADD ${this.formatFieldForTableManagement(cur)}`;
await this.query(query);
}, Promise.resolve());
};
this.startTransaction = async () => {
if (this.transactionConnection) {
if (GlobalMicrosoftModel.debug)
console.error('Already in a transaction');
return false;
}
if (!this.pool) {
if (GlobalMicrosoftModel.debug)
console.error('No pool');
return false;
}
const transaction = new mssql_1.default.Transaction(this.pool);
try {
await transaction.begin();
this.transactionConnection = transaction;
return true;
}
catch (err) {
if (GlobalMicrosoftModel.debug)
console.error(err);
return false;
}
};
this.commit = async () => {
if (!this.transactionConnection) {
if (GlobalMicrosoftModel.debug)
console.error('Not in a transaction');
return;
}
try {
await this.transactionConnection.commit();
}
catch (err) {
if (GlobalMicrosoftModel.debug)
console.error(err);
}
};
this.rollback = async () => {
if (!this.transactionConnection) {
if (GlobalMicrosoftModel.debug)
console.error('Not in a transaction');
return;
}
try {
await this.transactionConnection.rollback();
}
catch (err) {
if (GlobalMicrosoftModel.debug)
console.error(err);
}
};
this.checkMigrationTable = async () => {
const res = await this.query('SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = "migration"');
return res && res.output ? true : false;
};
this.setPool = async (config) => {
const p = await getPool(config);
if (p) {
this.pool = p;
}
};
this.formatFieldForTableManagement = (field) => {
const fInfos = field.getAll();
return `\`${fInfos.name}\` ${fInfos.type}${fInfos.len !== 0 ? `(${fInfos.len})` : ''}${fInfos.null ? '' : ' NOT NULL'}${fInfos.mustBeUnique || fInfos.primaryKey ? ' UNIQUE' : ''}${fInfos.ai ? ' AUTO_INCREMENT' : ''}${fInfos.defaultValue
? ` DEFAULT ${fInfos.defaultValue.isSystem
? `${fInfos.defaultValue.value}()`
: `'${fInfos.defaultValue.value}'`}`
: ''}${fInfos.checkValue ? ` CHECK (${fInfos.name}${fInfos.checkValue})` : ''}`;
};
}
}
exports.default = GlobalMicrosoftModel;
const getPool = async (config) => {
try {
const pool = new mssql_1.default.ConnectionPool(config);
await pool.connect();
return pool;
}
catch (err) {
if (GlobalMicrosoftModel.debug)
console.error(err);
}
return null;
};