How do I know whether drupal_write_record has done an insert or an update? I use the function to insert or update records in a table, but sometimes I would like to know whether the function has executed an update or an insert. In my scenario I always provide the primary key:

drupal_write_record('mytable',$entry,'key');


The function inserts a record if $entry['key'] does not exists and updates the record with the new information otherwise.

Is there somewhere I can check to see what the function has done ?
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.