Truncate.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Drupal\Core\Database\Query;
  3. use Drupal\Core\Database\Database;
  4. use Drupal\Core\Database\Connection;
  5. /**
  6. * General class for an abstracted TRUNCATE operation.
  7. */
  8. class Truncate extends Query {
  9. /**
  10. * The table to truncate.
  11. *
  12. * @var string
  13. */
  14. protected $table;
  15. /**
  16. * Constructs a Truncate query object.
  17. *
  18. * @param \Drupal\Core\Database\Connection $connection
  19. * A Connection object.
  20. * @param string $table
  21. * Name of the table to associate with this query.
  22. * @param array $options
  23. * Array of database options.
  24. */
  25. public function __construct(Connection $connection, $table, array $options = []) {
  26. $options['return'] = Database::RETURN_AFFECTED;
  27. parent::__construct($connection, $options);
  28. $this->table = $table;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function compile(Connection $connection, PlaceholderInterface $queryPlaceholder) {
  34. return $this->condition->compile($connection, $queryPlaceholder);
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function compiled() {
  40. return $this->condition->compiled();
  41. }
  42. /**
  43. * Executes the TRUNCATE query.
  44. *
  45. * @return
  46. * Return value is dependent on the database type.
  47. */
  48. public function execute() {
  49. return $this->connection->query((string) $this, [], $this->queryOptions);
  50. }
  51. /**
  52. * Implements PHP magic __toString method to convert the query to a string.
  53. *
  54. * @return string
  55. * The prepared statement.
  56. */
  57. public function __toString() {
  58. // Create a sanitized comment string to prepend to the query.
  59. $comments = $this->connection->makeComment($this->comments);
  60. // In most cases, TRUNCATE is not a transaction safe statement as it is a
  61. // DDL statement which results in an implicit COMMIT. When we are in a
  62. // transaction, fallback to the slower, but transactional, DELETE.
  63. // PostgreSQL also locks the entire table for a TRUNCATE strongly reducing
  64. // the concurrency with other transactions.
  65. if ($this->connection->inTransaction()) {
  66. return $comments . 'DELETE FROM {' . $this->connection->escapeTable($this->table) . '}';
  67. }
  68. else {
  69. return $comments . 'TRUNCATE {' . $this->connection->escapeTable($this->table) . '} ';
  70. }
  71. }
  72. }