Upsert.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Drupal\Core\Database\Driver\pgsql;
  3. use Drupal\Core\Database\Query\Upsert as QueryUpsert;
  4. /**
  5. * PostgreSQL implementation of \Drupal\Core\Database\Query\Upsert.
  6. */
  7. class Upsert extends QueryUpsert {
  8. /**
  9. * {@inheritdoc}
  10. */
  11. public function execute() {
  12. if (!$this->preExecute()) {
  13. return NULL;
  14. }
  15. // Default options for upsert queries.
  16. $this->queryOptions += [
  17. 'throw_exception' => TRUE,
  18. ];
  19. // Default fields are always placed first for consistency.
  20. $insert_fields = array_merge($this->defaultFields, $this->insertFields);
  21. $table = $this->connection->escapeTable($this->table);
  22. // We have to execute multiple queries, therefore we wrap everything in a
  23. // transaction so that it is atomic where possible.
  24. $transaction = $this->connection->startTransaction();
  25. try {
  26. // First, lock the table we're upserting into.
  27. $this->connection->query('LOCK TABLE {' . $table . '} IN SHARE ROW EXCLUSIVE MODE', [], $this->queryOptions);
  28. // Second, delete all items first so we can do one insert.
  29. $unique_key_position = array_search($this->key, $insert_fields);
  30. $delete_ids = [];
  31. foreach ($this->insertValues as $insert_values) {
  32. $delete_ids[] = $insert_values[$unique_key_position];
  33. }
  34. // Delete in chunks when a large array is passed.
  35. foreach (array_chunk($delete_ids, 1000) as $delete_ids_chunk) {
  36. $this->connection->delete($this->table, $this->queryOptions)
  37. ->condition($this->key, $delete_ids_chunk, 'IN')
  38. ->execute();
  39. }
  40. // Third, insert all the values.
  41. $insert = $this->connection->insert($this->table, $this->queryOptions)
  42. ->fields($insert_fields);
  43. foreach ($this->insertValues as $insert_values) {
  44. $insert->values($insert_values);
  45. }
  46. $insert->execute();
  47. }
  48. catch (\Exception $e) {
  49. // One of the queries failed, rollback the whole batch.
  50. $transaction->rollBack();
  51. // Rethrow the exception for the calling code.
  52. throw $e;
  53. }
  54. // Re-initialize the values array so that we can re-use this query.
  55. $this->insertValues = [];
  56. // Transaction commits here where $transaction looses scope.
  57. return TRUE;
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function __toString() {
  63. // Nothing to do.
  64. }
  65. }