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