awSQL/lib/Delete.js
2025-03-27 09:58:54 +01:00

78 lines
2.4 KiB
JavaScript

const { throwTypeError } = require("./Errors");
/**
* Prepares a new Deletion
*/
class Delete {
#instance;
#database;
#from;
#where;
#whereValues;
#force;
constructor(instance, defaultDatabase, from){
this.#instance = instance;
this.#database = defaultDatabase;
this.#from = from;
}
/**
* Selects a database for this query
* @param {String} database - Name of the database
* @returns {this}
*/
selectDatabase(database){
if (!database) throw new Error("database must not be empty");
if (typeof database !== "string") throwTypeError("string", database);
this.#database = database;
return this;
}
/**
* Adds a where-clause to the query
* - Values should be set as ? in the string and given in left-to-right order via the 'values'-array to minimize the risk of sql-injection
* @param {String} string - The where-clause as a string with ? representing each values.
* @param {Array<Any>} values - Array containing values replacing the ? in the string (from left to right)
* @returns {this}
*/
where(string, values=[]){
if (!string) throw new Error("string must not be empty");
if (typeof string !== "string") throwTypeError("string", string);
if (!Array.isArray(values)) throwTypeError("array", values);
this.#where = string;
this.#whereValues = values;
return this;
}
/**
* Enables deletion of all rows
*/
force(){
this.#force = true;
return this;
}
/**
* Executes the prepared querry
* @returns {import("../index").OkPacket}
*/
async execute(){
if (!this.#instance.isConnected()) throw new Error(`Can't execute query: Instance has no connection`);
if (!this.#database) throw new Error(`Can't execute query: Database not selected`);
if (!this.#where && !this.#force) throw new Error("Delete: Tried to delete all rows. If this was intentional, use .force() on Delete");
const values = [];
const whereString = this.#where?` WHERE ${this.#where}`:"";
this.#where&&values.push(...this.#whereValues);
const queryString = `DELETE FROM ${this.#database}.${this.#from}${whereString}`;
return await this.#instance.queryRaw(queryString, values);
}
}
module.exports = Delete;