3 namespace Drupal\Core\Database\Query;
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Connection;
10 * General class for an abstracted TRUNCATE operation.
12 class Truncate extends Query {
15 * The table to truncate.
22 * Constructs a Truncate query object.
24 * @param \Drupal\Core\Database\Connection $connection
25 * A Connection object.
26 * @param string $table
27 * Name of the table to associate with this query.
28 * @param array $options
29 * Array of database options.
31 public function __construct(Connection $connection, $table, array $options = []) {
32 $options['return'] = Database::RETURN_AFFECTED;
33 parent::__construct($connection, $options);
34 $this->table = $table;
40 public function compile(Connection $connection, PlaceholderInterface $queryPlaceholder) {
41 return $this->condition->compile($connection, $queryPlaceholder);
47 public function compiled() {
48 return $this->condition->compiled();
52 * Executes the TRUNCATE query.
55 * Return value is dependent on the database type.
57 public function execute() {
58 return $this->connection->query((string) $this, [], $this->queryOptions);
62 * Implements PHP magic __toString method to convert the query to a string.
65 * The prepared statement.
67 public function __toString() {
68 // Create a sanitized comment string to prepend to the query.
69 $comments = $this->connection->makeComment($this->comments);
71 // In most cases, TRUNCATE is not a transaction safe statement as it is a
72 // DDL statement which results in an implicit COMMIT. When we are in a
73 // transaction, fallback to the slower, but transactional, DELETE.
74 // PostgreSQL also locks the entire table for a TRUNCATE strongly reducing
75 // the concurrency with other transactions.
76 if ($this->connection->inTransaction()) {
77 return $comments . 'DELETE FROM {' . $this->connection->escapeTable($this->table) . '}';
80 return $comments . 'TRUNCATE {' . $this->connection->escapeTable($this->table) . '} ';