Fix check for existence of parent

When deleting, it's OK to delete entries that are parents of other
entries, as long as all the children will be deleted as well.
Also wrap the original where clause in parentheses to avoid problems
when appending more conditions.

Bug: 31685929
Change-Id: I488c6c732ed1bf252de6160b02900d131731c28f
diff --git a/src/com/android/providers/media/MediaProvider.java b/src/com/android/providers/media/MediaProvider.java
index d5b36da..9cb7d5f 100644
--- a/src/com/android/providers/media/MediaProvider.java
+++ b/src/com/android/providers/media/MediaProvider.java
@@ -4243,7 +4243,10 @@
                     // Do not allow deletion if the file/object is referenced as parent
                     // by some other entries. It could cause database corruption.
                     if (!TextUtils.isEmpty(sGetTableAndWhereParam.where)) {
-                        sGetTableAndWhereParam.where += " AND (" + ID_NOT_PARENT_CLAUSE + ")";
+                        sGetTableAndWhereParam.where =
+                                "(" + sGetTableAndWhereParam.where + ")" +
+                                        " AND (_id NOT IN (SELECT parent FROM files" +
+                                        " WHERE NOT (" + sGetTableAndWhereParam.where + ")))";
                     } else {
                         sGetTableAndWhereParam.where = ID_NOT_PARENT_CLAUSE;
                     }