Created
January 19, 2015 21:06
-
-
Save tleyden/f346749f649e9495a870 to your computer and use it in GitHub Desktop.
SQLiteDatabase nested transaction behavior test case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void testNestedSQLTransactionRollback() throws Exception { | |
String schema = "CREATE TABLE docs ( " + | |
" doc_id INTEGER PRIMARY KEY, " + | |
" val TEXT UNIQUE NOT NULL); "; | |
LiteTestContext context = new LiteTestContext(); | |
String dbName = "testNestedSQLTransactionRollback" + System.currentTimeMillis(); | |
String path = context.getFilesDir() + File.separator + dbName + Manager.DATABASE_SUFFIX; | |
SQLiteDatabase sqlDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.CREATE_IF_NECESSARY); | |
// install schema | |
sqlDatabase.execSQL(schema); | |
// start outer transaction | |
sqlDatabase.beginTransaction(); | |
// add a doc -- inner transaction 1: COMMITTED | |
sqlDatabase.beginTransaction(); | |
android.content.ContentValues args = new android.content.ContentValues(); | |
args.put("doc_id", 1); | |
args.put("val", "hello"); | |
long id = sqlDatabase.insert("docs", null, args); | |
sqlDatabase.setTransactionSuccessful(); | |
sqlDatabase.endTransaction(); | |
// add a doc -- inner transaction 2: CANCELLED | |
sqlDatabase.beginTransaction(); | |
args = new android.content.ContentValues(); | |
args.put("doc_id", 2); | |
args.put("val", "hello2"); | |
id = sqlDatabase.insert("docs", null, args); | |
sqlDatabase.endTransaction(); // CANCELLED since we don't call setTransactionSuccessful() | |
// finish outer transaction | |
sqlDatabase.setTransactionSuccessful(); | |
sqlDatabase.endTransaction(); | |
CountDownLatch doc1Persisted = new CountDownLatch(1); | |
// query db to make sure both docs are there | |
android.database.Cursor cursor = sqlDatabase.rawQuery( | |
"SELECT * FROM docs", null); | |
while (cursor.moveToNext()) { | |
int docId = cursor.getInt(0); | |
byte[] val = cursor.getBlob(1); | |
String.format("docid: %s val: %s", docId, new String(val)); | |
if (docId == 1) { | |
doc1Persisted.countDown(); | |
} | |
} | |
assertEquals(0, doc1Persisted.getCount()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment