Insert.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. <?php
  2. namespace Drupal\Core\Database\Driver\pgsql;
  3. use Drupal\Core\Database\Database;
  4. use Drupal\Core\Database\Query\Insert as QueryInsert;
  5. /**
  6. * @ingroup database
  7. * @{
  8. */
  9. /**
  10. * PostgreSQL implementation of \Drupal\Core\Database\Query\Insert.
  11. */
  12. class Insert extends QueryInsert {
  13. public function execute() {
  14. if (!$this->preExecute()) {
  15. return NULL;
  16. }
  17. $stmt = $this->connection->prepareQuery((string) $this);
  18. // Fetch the list of blobs and sequences used on that table.
  19. $table_information = $this->connection->schema()->queryTableInformation($this->table);
  20. $max_placeholder = 0;
  21. $blobs = [];
  22. $blob_count = 0;
  23. foreach ($this->insertValues as $insert_values) {
  24. foreach ($this->insertFields as $idx => $field) {
  25. if (isset($table_information->blob_fields[$field])) {
  26. $blobs[$blob_count] = fopen('php://memory', 'a');
  27. fwrite($blobs[$blob_count], $insert_values[$idx]);
  28. rewind($blobs[$blob_count]);
  29. $stmt->bindParam(':db_insert_placeholder_' . $max_placeholder++, $blobs[$blob_count], \PDO::PARAM_LOB);
  30. // Pre-increment is faster in PHP than increment.
  31. ++$blob_count;
  32. }
  33. else {
  34. $stmt->bindParam(':db_insert_placeholder_' . $max_placeholder++, $insert_values[$idx]);
  35. }
  36. }
  37. // Check if values for a serial field has been passed.
  38. if (!empty($table_information->serial_fields)) {
  39. foreach ($table_information->serial_fields as $index => $serial_field) {
  40. $serial_key = array_search($serial_field, $this->insertFields);
  41. if ($serial_key !== FALSE) {
  42. $serial_value = $insert_values[$serial_key];
  43. // Force $last_insert_id to the specified value. This is only done
  44. // if $index is 0.
  45. if ($index == 0) {
  46. $last_insert_id = $serial_value;
  47. }
  48. // Sequences must be greater than or equal to 1.
  49. if ($serial_value === NULL || !$serial_value) {
  50. $serial_value = 1;
  51. }
  52. // Set the sequence to the bigger value of either the passed
  53. // value or the max value of the column. It can happen that another
  54. // thread calls nextval() which could lead to a serial number being
  55. // used twice. However, trying to insert a value into a serial
  56. // column should only be done in very rare cases and is not thread
  57. // safe by definition.
  58. $this->connection->query("SELECT setval('" . $table_information->sequences[$index] . "', GREATEST(MAX(" . $serial_field . "), :serial_value)) FROM {" . $this->table . "}", [':serial_value' => (int) $serial_value]);
  59. }
  60. }
  61. }
  62. }
  63. if (!empty($this->fromQuery)) {
  64. // bindParam stores only a reference to the variable that is followed when
  65. // the statement is executed. We pass $arguments[$key] instead of $value
  66. // because the second argument to bindParam is passed by reference and
  67. // the foreach statement assigns the element to the existing reference.
  68. $arguments = $this->fromQuery->getArguments();
  69. foreach ($arguments as $key => $value) {
  70. $stmt->bindParam($key, $arguments[$key]);
  71. }
  72. }
  73. // PostgreSQL requires the table name to be specified explicitly
  74. // when requesting the last insert ID, so we pass that in via
  75. // the options array.
  76. $options = $this->queryOptions;
  77. if (!empty($table_information->sequences)) {
  78. $options['sequence_name'] = $table_information->sequences[0];
  79. }
  80. // If there are no sequences then we can't get a last insert id.
  81. elseif ($options['return'] == Database::RETURN_INSERT_ID) {
  82. $options['return'] = Database::RETURN_NULL;
  83. }
  84. // Create a savepoint so we can rollback a failed query. This is so we can
  85. // mimic MySQL and SQLite transactions which don't fail if a single query
  86. // fails. This is important for tables that are created on demand. For
  87. // example, \Drupal\Core\Cache\DatabaseBackend.
  88. $this->connection->addSavepoint();
  89. try {
  90. // Only use the returned last_insert_id if it is not already set.
  91. if (!empty($last_insert_id)) {
  92. $this->connection->query($stmt, [], $options);
  93. }
  94. else {
  95. $last_insert_id = $this->connection->query($stmt, [], $options);
  96. }
  97. $this->connection->releaseSavepoint();
  98. }
  99. catch (\Exception $e) {
  100. $this->connection->rollbackSavepoint();
  101. throw $e;
  102. }
  103. // Re-initialize the values array so that we can re-use this query.
  104. $this->insertValues = [];
  105. return $last_insert_id;
  106. }
  107. public function __toString() {
  108. // Create a sanitized comment string to prepend to the query.
  109. $comments = $this->connection->makeComment($this->comments);
  110. // Default fields are always placed first for consistency.
  111. $insert_fields = array_merge($this->defaultFields, $this->insertFields);
  112. $insert_fields = array_map(function ($f) {
  113. return $this->connection->escapeField($f);
  114. }, $insert_fields);
  115. // If we're selecting from a SelectQuery, finish building the query and
  116. // pass it back, as any remaining options are irrelevant.
  117. if (!empty($this->fromQuery)) {
  118. $insert_fields_string = $insert_fields ? ' (' . implode(', ', $insert_fields) . ') ' : ' ';
  119. return $comments . 'INSERT INTO {' . $this->table . '}' . $insert_fields_string . $this->fromQuery;
  120. }
  121. $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
  122. $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
  123. $query .= implode(', ', $values);
  124. return $query;
  125. }
  126. }