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) => { 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} values - Array containing values replacing the ? in the string (from left to right) * @returns {this} */ where = (string, values=[]) => { this.#where = string; this.#whereValues = values; return this; } /** * Enables deletion of all rows */ force = () => { this.#force = true; return this; } execute = async () => { 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;