move from old repository
This commit is contained in:
62
Deletion.php
Normal file
62
Deletion.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
namespace DatabaseHelper;
|
||||
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class Deletion
|
||||
{
|
||||
use Conditionable;
|
||||
|
||||
protected Schema $table;
|
||||
|
||||
public function __construct(Schema $table) {
|
||||
$this->table = $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the SQL statement.
|
||||
* @return string SQL query.
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public function toSql(): string {
|
||||
$table = $this->table->name;
|
||||
$whereClause = $this->combineConditions();
|
||||
|
||||
if (!$this->isConditioned())
|
||||
throw new InvalidArgumentException("Deletions need to be conditioned.");
|
||||
|
||||
return esc_sql("DELETE FROM $table WHERE $whereClause");
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the DELETE query.
|
||||
* @return int Number of affected rows.
|
||||
* @throws Exception
|
||||
*/
|
||||
public function delete(): int {
|
||||
global $wpdb;
|
||||
$query = $this->toSql();
|
||||
$result = $wpdb->query($query);
|
||||
|
||||
if ($result === false)
|
||||
throw new Exception("Deletion failed: " . $wpdb->last_error . ".");
|
||||
return intval($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all entries from the table.
|
||||
* @return int Number of affected rows.
|
||||
* @throws Exception
|
||||
*/
|
||||
public function truncate(): int {
|
||||
global $wpdb;
|
||||
$table = $this->table->name;
|
||||
$query = esc_sql("TRUNCATE TABLE $table");
|
||||
$result = $wpdb->query($query);
|
||||
|
||||
if ($result === false)
|
||||
throw new Exception("Truncation failed: " . $wpdb->last_error . ".");
|
||||
return intval($result);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user