Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataStore] Implement delete cascade #167

Merged
merged 1 commit into from
Dec 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ public void queryWithMaliciousPredicates() throws DataStoreException {
}

/**
* Assert that save stores item in the SQLite database correctly.
* Assert that delete deletes item in the SQLite database correctly.
* @throws DataStoreException from possible underlying DataStore exceptions
*/
@Test
Expand All @@ -499,6 +499,39 @@ public void deleteModelDeletesData() throws DataStoreException {
assertFalse(iterator.hasNext());
}

/**
* Assert that delete deletes item in the SQLite database without
* violating foreign key constraints.
* @throws DataStoreException from possible underlying DataStore exceptions
*/
@Test
public void deleteModelCascades() throws DataStoreException {
// Triggers an insert
final BlogOwner raphael = BlogOwner.builder()
.name("Raphael Kim")
.build();
saveModel(raphael);

// Triggers a foreign key constraint check
final Blog raphaelsBlog = Blog.builder()
.name("Raphael's Blog")
.owner(raphael)
.build();
saveModel(raphaelsBlog);

// Triggers a delete
// Deletes Raphael's Blog also to prevent foreign key violation
deleteModel(raphael);

// Get the BlogOwner record from the database
Iterator<BlogOwner> blogOwnerterator = queryModel(BlogOwner.class);
assertFalse(blogOwnerterator.hasNext());

// Get the Blog record from the database
Iterator<Blog> blogIterator = queryModel(Blog.class);
assertFalse(blogIterator.hasNext());
}

private <T extends Model> T saveModel(@NonNull T model) throws DataStoreException {
LatchedResultListener<StorageItemChange.Record> saveListener =
LatchedResultListener.waitFor(SQLITE_OPERATION_TIMEOUT_MS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,9 @@ private StringBuilder parseForeignKeys(SQLiteTable table) {
.append("REFERENCES")
.append(SqlKeyword.DELIMITER)
.append(connectedType)
.append("(" + connectedId + ")");
.append("(" + connectedId + ")")
.append(SqlKeyword.DELIMITER)
.append("ON DELETE CASCADE");

if (foreignKeyIterator.hasNext()) {
builder.append(",").append(SqlKeyword.DELIMITER);
Expand Down