Delete unreferenced phone numbers

Bug 5375782. Bug 5172594
The canonical_addresses table in mmssms.db is used to keep a reference
between recipientIds and phone numbers/email addresses. The threads
table contains references to these recipient ids. When a thread is
deleted, the recipients are orphaned. With this change, whenever a
thread is deleted, we delete unreferenced numbers.

Change-Id: I7e1b7a11317d2e6662fab3f434239fe21ca313ec
diff --git a/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java b/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
index 80d5d8f..4188233 100644
--- a/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
+++ b/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
@@ -250,7 +250,9 @@
                   "           UNION SELECT thread_id FROM pdu)",
                   new String[] { String.valueOf(thread_id) });
         if (rows > 0) {
-            // If this deleted a row, we have no more work to do.
+            // If this deleted a row, let's remove orphaned canonical_addresses and get outta here
+            db.delete("canonical_addresses",
+                    "_id NOT IN (SELECT DISTINCT recipient_ids FROM threads)", null);
             return;
         }
         // Update the message count in the threads table as the sum
@@ -344,10 +346,16 @@
                 c.close();
             }
         }
+        // TODO: there are several db operations in this function. Lets wrap them in a
+        // transaction to make it faster.
         // remove orphaned threads
         db.delete("threads",
                 "_id NOT IN (SELECT DISTINCT thread_id FROM sms " +
                 "UNION SELECT DISTINCT thread_id FROM pdu)", null);
+
+        // remove orphaned canonical_addresses
+        db.delete("canonical_addresses",
+                "_id NOT IN (SELECT DISTINCT recipient_ids FROM threads)", null);
     }
 
     public static int deleteOneSms(SQLiteDatabase db, int message_id) {