mysql-rewrapped
Version:
A wrapper for MySQL on node to make querying a database as easy as possible
92 lines (91 loc) • 3.36 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var WhereAlreadyPopulatedException_1 = require("./Errors/WhereAlreadyPopulatedException");
var Database_1 = require("./Database");
var Query = /** @class */ (function () {
function Query(type) {
this.whereStatement = "";
this.whereParams = [];
this.queryParams = [];
this.type = type;
}
Query.prototype.table = function (table) {
this.tableName = table;
return this;
};
Query.prototype.where = function (key, value, operator) {
if (this.whereStatement.length > 0) {
throw new WhereAlreadyPopulatedException_1.default();
}
var _a = this.parseWhere(key, value, operator), statement = _a[0], whereParams = _a[1];
statement = " WHERE " + statement;
this.whereStatement = statement;
this.whereParams = whereParams;
return this;
};
Query.prototype.orWhere = function (key, value, operator) {
var _a = this.parseWhere(key, value, operator), statement = _a[0], whereParams = _a[1];
statement = " OR " + statement;
this.whereStatement += statement;
this.whereParams = this.whereParams.concat(whereParams);
return this;
};
Query.prototype.andWhere = function (key, value, operator) {
var _a = this.parseWhere(key, value, operator), statement = _a[0], whereParams = _a[1];
statement = " AND " + statement;
this.whereParams = this.whereParams.concat(whereParams);
this.whereStatement += statement;
return this;
};
Query.prototype.parseWhere = function (key, value, operator) {
if (!(value instanceof Array)) {
value = [value];
}
var whereParams = [];
var statement = "";
if (Query.safeOperators.indexOf(operator.toLowerCase()) > -1) {
statement += key + " " + operator + " ? ";
whereParams.push(value[0]);
}
else if (operator.toLowerCase() === "in") {
statement += key + " IN (";
value.forEach(function (val) {
statement += "?, ";
whereParams.push(val);
});
statement = statement.substr(0, statement.length - 2);
statement += ") ";
}
else if (operator.toLowerCase() === "between") {
statement += key + " BETWEEN ? AND ? ";
whereParams.push(value[0]);
whereParams.push(value[1]);
}
else {
throw "Invalid Comparison Operator";
}
return [statement, whereParams];
};
Query.prototype.exec = function (cback) {
var callback = function (error, results) {
if (error) {
cback(false);
}
else
cback(results);
};
try {
if (this.queryParams !== null) {
Database_1.default.db.connectionPool.query(this.toString(), this.queryParams, callback);
}
else
Database_1.default.db.connectionPool.query(this.toString(), callback);
}
catch (e) {
throw e;
}
};
Query.safeOperators = ["=", "<=>", "<>", "!=", ">", ">=", "<", "<=", "like"];
return Query;
}());
exports.default = Query;