0

I am using db_merge() in my code, and I would like to print a status message with drupal_set_message() that reports if the record has been added or updated.

Is it possible?

1

MergeQuery::execute() returns MergeQuery::STATUS_INSERT when the data was inserted in the database table, and MergeQuery::STATUS_UPDATE when a row was updated.

MergeQuery is the class of the object returned from db_merge().

public function execute() {
  if (!count($this->condition)) {
    throw new InvalidMergeQueryException(t('Invalid merge query: no conditions'));
  }
  $select = $this->connection->select($this->conditionTable)
    ->condition($this->condition);
  $select->addExpression('1');
  if (!$select->execute()->fetchField()) {
    try {
      $insert = $this->connection->insert($this->table)->fields($this->insertFields);
      if ($this->defaultFields) {
        $insert->useDefaults($this->defaultFields);
      }
      $insert->execute();
      return self::STATUS_INSERT;
    }
    catch (Exception $e) {
      // The insert query failed, maybe it's because a racing insert query
      // beat us in inserting the same row. Retry the select query, if it
      // returns a row, ignore the error and continue with the update
      // query below.
      if (!$select->execute()->fetchField()) {
        throw $e;
      }
    }
  }
  if ($this->needsUpdate) {
    $update = $this->connection->update($this->table)
      ->fields($this->updateFields)
      ->condition($this->condition);
    if ($this->expressionFields) {
      foreach ($this->expressionFields as $field => $data) {
        $update->expression($field, $data['expression'], $data['arguments']);
      }
    }
    $update->execute();
    return self::STATUS_UPDATE;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.