Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Database / Query / Truncate.php
1 <?php
2
3 namespace Drupal\Core\Database\Query;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Connection;
7
8
9 /**
10  * General class for an abstracted TRUNCATE operation.
11  */
12 class Truncate extends Query {
13
14   /**
15    * The table to truncate.
16    *
17    * @var string
18    */
19   protected $table;
20
21   /**
22    * Constructs a Truncate query object.
23    *
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.
30    */
31   public function __construct(Connection $connection, $table, array $options = []) {
32     $options['return'] = Database::RETURN_AFFECTED;
33     parent::__construct($connection, $options);
34     $this->table = $table;
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   public function compile(Connection $connection, PlaceholderInterface $queryPlaceholder) {
41     return $this->condition->compile($connection, $queryPlaceholder);
42   }
43
44   /**
45    * {@inheritdoc}
46    */
47   public function compiled() {
48     return $this->condition->compiled();
49   }
50
51   /**
52    * Executes the TRUNCATE query.
53    *
54    * @return
55    *   Return value is dependent on the database type.
56    */
57   public function execute() {
58     return $this->connection->query((string) $this, [], $this->queryOptions);
59   }
60
61   /**
62    * Implements PHP magic __toString method to convert the query to a string.
63    *
64    * @return string
65    *   The prepared statement.
66    */
67   public function __toString() {
68     // Create a sanitized comment string to prepend to the query.
69     $comments = $this->connection->makeComment($this->comments);
70
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) . '}';
78     }
79     else {
80       return $comments . 'TRUNCATE {' . $this->connection->escapeTable($this->table) . '} ';
81     }
82   }
83
84 }