slim-node-mysql
Version:
MySQL database class to abstract pooling and prepared statements
46 lines • 1.82 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.MySQLPreparedStatement = void 0;
const PreparedStatementError_1 = require("./errors/PreparedStatementError");
/**
* A MySQL prepared statement. Parses a SQL query with variables and returns the prepared SQL string and variable to value map.
*/
class MySQLPreparedStatement {
constructor(sqlString, parameters) {
this.replaceValuesWith = '?';
this.sqlString = sqlString;
this.parameters = parameters;
}
/**
* Set the string to replace SQL variables with (? for MySQL).
* Defaults to '?'.
* @param replaceValuesWith the string to replace variables with.
*/
setReplaceValuesWith(replaceValuesWith) {
this.replaceValuesWith = replaceValuesWith;
}
/**
* Prepare the SQL string and values for execution.
* @returns the prepared SQL string and values.
*/
prepare() {
let preparedSQL = this.sqlString;
const preparedValues = [];
let match;
while ((match = preparedSQL.match(/@([A-Za-z_]+)/))) {
const variableName = match[0];
const baseVariableName = match[1];
if (!(baseVariableName in this.parameters)) {
throw new PreparedStatementError_1.PreparedStatementError(`Missing prepared statement value for SQL variable '${variableName}'`);
}
preparedSQL = preparedSQL.replace(variableName, this.replaceValuesWith);
preparedValues.push(this.parameters[baseVariableName]);
}
return {
preparedSQL,
preparedValues: preparedValues.length > 0 ? preparedValues : null,
};
}
}
exports.MySQLPreparedStatement = MySQLPreparedStatement;
//# sourceMappingURL=MySQLPreparedStatement.js.map
;