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