NativeUpsert.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. namespace Drupal\Core\Database\Driver\pgsql;
  3. use Drupal\Core\Database\Query\Upsert as QueryUpsert;
  4. /**
  5. * PostgreSQL implementation of native \Drupal\Core\Database\Query\Upsert.
  6. *
  7. * @see http://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT
  8. */
  9. class NativeUpsert extends QueryUpsert {
  10. /**
  11. * {@inheritdoc}
  12. */
  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. // Sequences must be greater than or equal to 1.
  44. if ($serial_value === NULL || !$serial_value) {
  45. $serial_value = 1;
  46. }
  47. // Set the sequence to the bigger value of either the passed
  48. // value or the max value of the column. It can happen that another
  49. // thread calls nextval() which could lead to a serial number being
  50. // used twice. However, trying to insert a value into a serial
  51. // column should only be done in very rare cases and is not thread
  52. // safe by definition.
  53. $this->connection->query("SELECT setval('" . $table_information->sequences[$index] . "', GREATEST(MAX(" . $serial_field . "), :serial_value)) FROM {" . $this->table . "}", [':serial_value' => (int) $serial_value]);
  54. }
  55. }
  56. }
  57. }
  58. $options = $this->queryOptions;
  59. if (!empty($table_information->sequences)) {
  60. $options['sequence_name'] = $table_information->sequences[0];
  61. }
  62. // Re-initialize the values array so that we can re-use this query.
  63. $this->insertValues = [];
  64. // Create a savepoint so we can rollback a failed query. This is so we can
  65. // mimic MySQL and SQLite transactions which don't fail if a single query
  66. // fails. This is important for tables that are created on demand. For
  67. // example, \Drupal\Core\Cache\DatabaseBackend.
  68. $this->connection->addSavepoint();
  69. try {
  70. $this->connection->query($stmt, [], $options);
  71. $this->connection->releaseSavepoint();
  72. }
  73. catch (\Exception $e) {
  74. $this->connection->rollbackSavepoint();
  75. throw $e;
  76. }
  77. return TRUE;
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function __toString() {
  83. // Create a sanitized comment string to prepend to the query.
  84. $comments = $this->connection->makeComment($this->comments);
  85. // Default fields are always placed first for consistency.
  86. $insert_fields = array_merge($this->defaultFields, $this->insertFields);
  87. $insert_fields = array_map(function ($f) {
  88. return $this->connection->escapeField($f);
  89. }, $insert_fields);
  90. $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';
  91. $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
  92. $query .= implode(', ', $values);
  93. // Updating the unique / primary key is not necessary.
  94. unset($insert_fields[$this->key]);
  95. $update = [];
  96. foreach ($insert_fields as $field) {
  97. $update[] = "$field = EXCLUDED.$field";
  98. }
  99. $query .= ' ON CONFLICT (' . $this->connection->escapeField($this->key) . ') DO UPDATE SET ' . implode(', ', $update);
  100. return $query;
  101. }
  102. }