Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [TestMethod]
- public void TestTransactions() {
- SQLiteConnection connection = ...;
- // Create a test table.
- using (SQLiteCommand command = new SQLiteCommand("CREATE TABLE test(column TEXT);", connection)) {
- command.ExecuteNonQuery();
- }
- // Insert a single row.
- using (SQLiteCommand command = new SQLiteCommand("INSERT INTO test VALUES ('no transaction');", connection)) {
- command.ExecuteNonQuery();
- }
- // Assert that the table contains a single row. Test PASSES.
- using (SQLiteCommand command = new SQLiteCommand("SELECT COUNT(*) FROM test;", connection)) {
- Assert.AreEqual((long)1, command.ExecuteScalar());
- }
- // Begin a transaction.
- using (SQLiteTransaction transaction = connection.BeginTransaction()) {
- // Insert another row into the table.
- using (SQLiteCommand command = new SQLiteCommand("INSERT INTO test VALUES ('in transaction');", connection)) {
- command.ExecuteNonQuery();
- }
- // Assert that the table contains two rows. Test PASSES.
- using (SQLiteCommand command = new SQLiteCommand("SELECT COUNT(*) FROM test;", connection)) {
- Assert.AreEqual((long)2, command.ExecuteScalar());
- }
- // Begin another transaction. System.Data.SQLite apparently allows me to do this, as it doesn't throw any exception.
- // Also, the implementation of SQLiteTransaction suggests that transactions can actually be nested.
- using (SQLiteTransaction nestedTransaction = connection.BeginTransaction()) {
- // Insert another row into the table.
- using (SQLiteCommand command = new SQLiteCommand("INSERT INTO test VALUES ('in nested transaction');", connection)) {
- command.ExecuteNonQuery();
- }
- // Assert that the table contains three rows. Test PASSES.
- using (SQLiteCommand command = new SQLiteCommand("SELECT COUNT(*) FROM test;", connection)) {
- Assert.AreEqual((long)3, command.ExecuteScalar());
- }
- // Note: the nested transaction goes out of scope here without a call to Commit(), so an implicit Rollback() is done.
- }
- // The nested transaction has been rolled back again. Assert that the table now contains two rows again. Test FAILS,
- // since actual row count == 1.
- using (SQLiteCommand command = new SQLiteCommand("SELECT COUNT(*) FROM test;", connection)) {
- Assert.AreEqual((long)2, command.ExecuteScalar());
- }
- // Note: transaction goes out of scope here without a call to Commit(), so an implicit Rollback() is done.
- }
- // All transactions have been rolled back again. Assert that the table now contains a single row again. Test PASSES.
- using (SQLiteCommand command = new SQLiteCommand("SELECT COUNT(*) FROM test;", connection)) {
- Assert.AreEqual((long)1, command.ExecuteScalar());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement