SQLite Forum

set/get last_insert_rowid - To mutex or not mutex?
Login
Hi. I'm doing an UPSERT, and to figure out (after the fact) whether it did an INSERT or an UPDATE  
I decided to force a `sqlite3_set_last_insert_rowid(db, -1)` so I can be sure (?)  
`sqlite3_last_insert_rowid` returns a positive ROWID on INSERTs only.

So first, any holes in the above scheme?

But what prompted this new thread was the fact the *set* is mutex-protected, while the *get* is not.  
I'm no thread-safety expert, but both reads and writes must be mutex-protected to avoid data-races, no?

So am I missing something, or there's a weird mismatch here?  
Either neither is mutexed; or both are mutexed. But a mix like this feels wrong.

Thoughts?

```
*
** Return the ROWID of the most recent insert
*/
SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
  if( !sqlite3SafetyCheckOk(db) ){
    (void)SQLITE_MISUSE_BKPT;
    return 0;
  }
#endif
  return db->lastRowid;
}

/*
** Set the value returned by the sqlite3_last_insert_rowid() API function.
*/
SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
#ifdef SQLITE_ENABLE_API_ARMOR
  if( !sqlite3SafetyCheckOk(db) ){
    (void)SQLITE_MISUSE_BKPT;
    return;
  }
#endif
  sqlite3_mutex_enter(db->mutex);
  db->lastRowid = iRowid;
  sqlite3_mutex_leave(db->mutex);
}
```