How do I know whether drupal_write_record has done an insert or an update?
Turns out that in order to know if the operation was an UPDATE or an INSERT you need to know whether the record existed or not before committing the transaction. This is not what drupal_write_record() does. This function just checks it's arguments and issues an update or an insert accordingly. So there is really no way to tell if the function did an INSERT or an UPDATE.

The solution is using db_merge() query, it is a relatively new SQL ANSI standard that does exactly what I needed (and in the case of MySQL does it in an atomic transaction).

$return_value = db_merge('mytable')
            -&gt;key(array('id' =&gt; $key))
            -&gt;fields($fields)
            -&gt;updateFields(array(
                'updatedon' =&gt; $now,
            ))
            -&gt;execute();


The return value is an integer returning 1 for inserts and 2 for updates.