Skip to content

Commit

Permalink
Merge pull request #866 from ElteHupkes/fix-insert-nre-761
Browse files Browse the repository at this point in the history
Fix to #761, preventing returning a disposed command object
  • Loading branch information
praeclarum authored Sep 20, 2019
2 parents 20aa06f + 3826756 commit cf7652e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
21 changes: 10 additions & 11 deletions src/SQLite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1710,21 +1710,20 @@ PreparedSqlLiteInsertCommand GetInsertCommand (TableMapping map, string extra)
var key = Tuple.Create (map.MappedType.FullName, extra);

lock (_insertCommandMap) {
_insertCommandMap.TryGetValue (key, out prepCmd);
if (_insertCommandMap.TryGetValue (key, out prepCmd)) {
return prepCmd;
}
}

if (prepCmd == null) {
prepCmd = CreateInsertCommand (map, extra);
var added = false;
lock (_insertCommandMap) {
if (!_insertCommandMap.ContainsKey (key)) {
_insertCommandMap.Add (key, prepCmd);
added = true;
}
}
if (!added) {
prepCmd = CreateInsertCommand (map, extra);

lock (_insertCommandMap) {
if (_insertCommandMap.TryGetValue (key, out var existing)) {
prepCmd.Dispose ();
return existing;
}

_insertCommandMap.Add (key, prepCmd);
}

return prepCmd;
Expand Down
23 changes: 22 additions & 1 deletion tests/ConcurrencyTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,28 @@ public void TestLoad()
}
}


/// <summary>
/// Test for issue #761. Because the nature of this test is a race condition,
/// it is not guaranteed to fail if the issue is present. It does appear to
/// fail most of the time, though.
/// </summary>
[Test]
public void TestInsertCommandCreation ()
{
using (var dbConnection =
new DbConnection (SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create)) {
var obj1 = new TestObj ();
var obj2 = new TestObj ();
var taskA = Task.Run (() => {
dbConnection.Insert (obj1);
});
var taskB = Task.Run (() => {
dbConnection.Insert (obj2);
});

Task.WhenAll (taskA, taskB).Wait ();
}
}
}
}

0 comments on commit cf7652e

Please sign in to comment.