How to debug merge query? I have a simple merge query, with one key and three fields, something like:

$query = db_merge('product')
-&gt;key(array(
  'id' =&gt; $id_product,
))
-&gt;fields(array(
  'name'   =&gt; $form_state['values']['name'],
  'symbol' =&gt; $form_state['values']['symbol'],
  'weight' =&gt; $form_state['values']['weight'],
));


Usually it works all right, but some combinations of data passed to it and data already in database cause me headache. I'm sure I would be able to know what's wrong and why, if only I could grab actual SQL query that goes to my database.

Usually I would do:

  kpr((string)$query);


It works well for insert for example, because insert has __toString() well implemented. Sadly, implementation of MergeQuery::__toString is somewhat nonexistent:

public function __toString() {
}


It isn't even a proper implementation of this magic method, as it should always return string, but OK, I can assume it was on purpose. Anyway, this changes nothing: I can't simply cast it to see it.

What other options do I have, to see queries generated by db_merge() / MergeQuery for database interaction debugging?
A MergeQuery just runs a SELECT and INSERT internally - there isn't a single query string available, so the __toString() method doesn't make sense (which is probably why it's short-circuited).

SelectQuery and InsertQuery both implement __toString() fully, so your best bet for debugging would be to temporarily add some code to MergeQuery::execute() to dump the $select and/or $insert query before they're run, so you can inspect the query string.