EmailProvider.java revision 2736c1a11ce3ecdcd9d19aa9c324fb9ce0910c7b
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.email.provider;
18
19import android.accounts.AccountManager;
20import android.content.ContentProvider;
21import android.content.ContentProviderOperation;
22import android.content.ContentProviderResult;
23import android.content.ContentResolver;
24import android.content.ContentUris;
25import android.content.ContentValues;
26import android.content.Context;
27import android.content.OperationApplicationException;
28import android.content.UriMatcher;
29import android.database.ContentObserver;
30import android.database.Cursor;
31import android.database.MatrixCursor;
32import android.database.SQLException;
33import android.database.sqlite.SQLiteDatabase;
34import android.database.sqlite.SQLiteException;
35import android.database.sqlite.SQLiteOpenHelper;
36import android.net.Uri;
37import android.provider.ContactsContract;
38import android.text.TextUtils;
39import android.util.Log;
40
41import com.android.email.Email;
42import com.android.email.Preferences;
43import com.android.email.provider.ContentCache.CacheToken;
44import com.android.email.service.AttachmentDownloadService;
45import com.android.emailcommon.AccountManagerTypes;
46import com.android.emailcommon.CalendarProviderStub;
47import com.android.emailcommon.Logging;
48import com.android.emailcommon.provider.Account;
49import com.android.emailcommon.provider.EmailContent;
50import com.android.emailcommon.provider.EmailContent.AccountColumns;
51import com.android.emailcommon.provider.EmailContent.Attachment;
52import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
53import com.android.emailcommon.provider.EmailContent.Body;
54import com.android.emailcommon.provider.EmailContent.BodyColumns;
55import com.android.emailcommon.provider.EmailContent.HostAuthColumns;
56import com.android.emailcommon.provider.EmailContent.MailboxColumns;
57import com.android.emailcommon.provider.EmailContent.Message;
58import com.android.emailcommon.provider.EmailContent.MessageColumns;
59import com.android.emailcommon.provider.EmailContent.PolicyColumns;
60import com.android.emailcommon.provider.EmailContent.QuickResponseColumns;
61import com.android.emailcommon.provider.EmailContent.SyncColumns;
62import com.android.emailcommon.provider.HostAuth;
63import com.android.emailcommon.provider.Mailbox;
64import com.android.emailcommon.provider.Policy;
65import com.android.emailcommon.provider.QuickResponse;
66import com.android.emailcommon.service.LegacyPolicySet;
67import com.google.common.annotations.VisibleForTesting;
68
69import java.io.File;
70import java.util.ArrayList;
71import java.util.Arrays;
72import java.util.Collection;
73import java.util.HashMap;
74import java.util.List;
75import java.util.Map;
76
77public class EmailProvider extends ContentProvider {
78
79    private static final String TAG = "EmailProvider";
80
81    protected static final String DATABASE_NAME = "EmailProvider.db";
82    protected static final String BODY_DATABASE_NAME = "EmailProviderBody.db";
83    protected static final String BACKUP_DATABASE_NAME = "EmailProviderBackup.db";
84
85    public static final String ACTION_ATTACHMENT_UPDATED = "com.android.email.ATTACHMENT_UPDATED";
86    public static final String ATTACHMENT_UPDATED_EXTRA_FLAGS =
87        "com.android.email.ATTACHMENT_UPDATED_FLAGS";
88
89    public static final String EMAIL_MESSAGE_MIME_TYPE =
90        "vnd.android.cursor.item/email-message";
91    public static final String EMAIL_ATTACHMENT_MIME_TYPE =
92        "vnd.android.cursor.item/email-attachment";
93
94    public static final Uri INTEGRITY_CHECK_URI =
95        Uri.parse("content://" + EmailContent.AUTHORITY + "/integrityCheck");
96    public static final Uri ACCOUNT_BACKUP_URI =
97        Uri.parse("content://" + EmailContent.AUTHORITY + "/accountBackup");
98
99    /** Appended to the notification URI for delete operations */
100    public static final String NOTIFICATION_OP_DELETE = "delete";
101    /** Appended to the notification URI for insert operations */
102    public static final String NOTIFICATION_OP_INSERT = "insert";
103    /** Appended to the notification URI for update operations */
104    public static final String NOTIFICATION_OP_UPDATE = "update";
105
106    // Definitions for our queries looking for orphaned messages
107    private static final String[] ORPHANS_PROJECTION
108        = new String[] {MessageColumns.ID, MessageColumns.MAILBOX_KEY};
109    private static final int ORPHANS_ID = 0;
110    private static final int ORPHANS_MAILBOX_KEY = 1;
111
112    private static final String WHERE_ID = EmailContent.RECORD_ID + "=?";
113
114    // This is not a hard limit on accounts, per se, but beyond this, we can't guarantee that all
115    // critical mailboxes, host auth's, accounts, and policies are cached
116    private static final int MAX_CACHED_ACCOUNTS = 16;
117    // Inbox, Drafts, Sent, Outbox, Trash, and Search (these boxes are cached when possible)
118    private static final int NUM_ALWAYS_CACHED_MAILBOXES = 6;
119
120    // We'll cache the following four tables; sizes are best estimates of effective values
121    private final ContentCache mCacheAccount =
122        new ContentCache("Account", Account.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
123    private final ContentCache mCacheHostAuth =
124        new ContentCache("HostAuth", HostAuth.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS * 2);
125    /*package*/ final ContentCache mCacheMailbox =
126        new ContentCache("Mailbox", Mailbox.CONTENT_PROJECTION,
127                MAX_CACHED_ACCOUNTS * (NUM_ALWAYS_CACHED_MAILBOXES + 2));
128    private final ContentCache mCacheMessage =
129        new ContentCache("Message", Message.CONTENT_PROJECTION, 8);
130    private final ContentCache mCachePolicy =
131        new ContentCache("Policy", Policy.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
132
133    // Any changes to the database format *must* include update-in-place code.
134    // Original version: 3
135    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
136    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
137    // Version 6: Adding Message.mServerTimeStamp column
138    // Version 7: Replace the mailbox_delete trigger with a version that removes orphaned messages
139    //            from the Message_Deletes and Message_Updates tables
140    // Version 8: Add security flags column to accounts table
141    // Version 9: Add security sync key and signature to accounts table
142    // Version 10: Add meeting info to message table
143    // Version 11: Add content and flags to attachment table
144    // Version 12: Add content_bytes to attachment table. content is deprecated.
145    // Version 13: Add messageCount to Mailbox table.
146    // Version 14: Add snippet to Message table
147    // Version 15: Fix upgrade problem in version 14.
148    // Version 16: Add accountKey to Attachment table
149    // Version 17: Add parentKey to Mailbox table
150    // Version 18: Copy Mailbox.displayName to Mailbox.serverId for all IMAP & POP3 mailboxes.
151    //             Column Mailbox.serverId is used for the server-side pathname of a mailbox.
152    // Version 19: Add Policy table; add policyKey to Account table and trigger to delete an
153    //             Account's policy when the Account is deleted
154    // Version 20: Add new policies to Policy table
155    // Version 21: Add lastSeenMessageKey column to Mailbox table
156    // Version 22: Upgrade path for IMAP/POP accounts to integrate with AccountManager
157    // Version 23: Add column to mailbox table for time of last access
158    // Version 24: Add column to hostauth table for client cert alias
159    // Version 25: Added QuickResponse table
160    // Version 26: Update IMAP accounts to add FLAG_SUPPORTS_SEARCH flag
161    // Version 27: Add protocolSearchInfo to Message table
162    // Version 28: Add notifiedMessageId and notifiedMessageCount to Account
163    // Version 29: Add protocolPoliciesEnforced and protocolPoliciesUnsupported to Policy
164
165    public static final int DATABASE_VERSION = 29;
166
167    // Any changes to the database format *must* include update-in-place code.
168    // Original version: 2
169    // Version 3: Add "sourceKey" column
170    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
171    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
172    // Version 6: Adding Body.mIntroText column
173    public static final int BODY_DATABASE_VERSION = 6;
174
175    private static final int ACCOUNT_BASE = 0;
176    private static final int ACCOUNT = ACCOUNT_BASE;
177    private static final int ACCOUNT_ID = ACCOUNT_BASE + 1;
178    private static final int ACCOUNT_ID_ADD_TO_FIELD = ACCOUNT_BASE + 2;
179    private static final int ACCOUNT_RESET_NEW_COUNT = ACCOUNT_BASE + 3;
180    private static final int ACCOUNT_RESET_NEW_COUNT_ID = ACCOUNT_BASE + 4;
181    private static final int ACCOUNT_DEFAULT_ID = ACCOUNT_BASE + 5;
182
183    private static final int MAILBOX_BASE = 0x1000;
184    private static final int MAILBOX = MAILBOX_BASE;
185    private static final int MAILBOX_ID = MAILBOX_BASE + 1;
186    private static final int MAILBOX_ID_FROM_ACCOUNT_AND_TYPE = MAILBOX_BASE + 2;
187    private static final int MAILBOX_ID_ADD_TO_FIELD = MAILBOX_BASE + 2;
188
189    private static final int MESSAGE_BASE = 0x2000;
190    private static final int MESSAGE = MESSAGE_BASE;
191    private static final int MESSAGE_ID = MESSAGE_BASE + 1;
192    private static final int SYNCED_MESSAGE_ID = MESSAGE_BASE + 2;
193
194    private static final int ATTACHMENT_BASE = 0x3000;
195    private static final int ATTACHMENT = ATTACHMENT_BASE;
196    private static final int ATTACHMENT_ID = ATTACHMENT_BASE + 1;
197    private static final int ATTACHMENTS_MESSAGE_ID = ATTACHMENT_BASE + 2;
198
199    private static final int HOSTAUTH_BASE = 0x4000;
200    private static final int HOSTAUTH = HOSTAUTH_BASE;
201    private static final int HOSTAUTH_ID = HOSTAUTH_BASE + 1;
202
203    private static final int UPDATED_MESSAGE_BASE = 0x5000;
204    private static final int UPDATED_MESSAGE = UPDATED_MESSAGE_BASE;
205    private static final int UPDATED_MESSAGE_ID = UPDATED_MESSAGE_BASE + 1;
206
207    private static final int DELETED_MESSAGE_BASE = 0x6000;
208    private static final int DELETED_MESSAGE = DELETED_MESSAGE_BASE;
209    private static final int DELETED_MESSAGE_ID = DELETED_MESSAGE_BASE + 1;
210
211    private static final int POLICY_BASE = 0x7000;
212    private static final int POLICY = POLICY_BASE;
213    private static final int POLICY_ID = POLICY_BASE + 1;
214
215    private static final int QUICK_RESPONSE_BASE = 0x8000;
216    private static final int QUICK_RESPONSE = QUICK_RESPONSE_BASE;
217    private static final int QUICK_RESPONSE_ID = QUICK_RESPONSE_BASE + 1;
218    private static final int QUICK_RESPONSE_ACCOUNT_ID = QUICK_RESPONSE_BASE + 2;
219
220    // MUST ALWAYS EQUAL THE LAST OF THE PREVIOUS BASE CONSTANTS
221    private static final int LAST_EMAIL_PROVIDER_DB_BASE = QUICK_RESPONSE_BASE;
222
223    // DO NOT CHANGE BODY_BASE!!
224    private static final int BODY_BASE = LAST_EMAIL_PROVIDER_DB_BASE + 0x1000;
225    private static final int BODY = BODY_BASE;
226    private static final int BODY_ID = BODY_BASE + 1;
227
228    private static final int BASE_SHIFT = 12;  // 12 bits to the base type: 0, 0x1000, 0x2000, etc.
229
230    // TABLE_NAMES MUST remain in the order of the BASE constants above (e.g. ACCOUNT_BASE = 0x0000,
231    // MESSAGE_BASE = 0x1000, etc.)
232    private static final String[] TABLE_NAMES = {
233        Account.TABLE_NAME,
234        Mailbox.TABLE_NAME,
235        Message.TABLE_NAME,
236        Attachment.TABLE_NAME,
237        HostAuth.TABLE_NAME,
238        Message.UPDATED_TABLE_NAME,
239        Message.DELETED_TABLE_NAME,
240        Policy.TABLE_NAME,
241        QuickResponse.TABLE_NAME,
242        Body.TABLE_NAME
243    };
244
245    // CONTENT_CACHES MUST remain in the order of the BASE constants above
246    private final ContentCache[] mContentCaches = {
247        mCacheAccount,
248        mCacheMailbox,
249        mCacheMessage,
250        null, // Attachment
251        mCacheHostAuth,
252        null, // Updated message
253        null, // Deleted message
254        mCachePolicy,
255        null, // Quick response
256        null  // Body
257    };
258
259    // CACHE_PROJECTIONS MUST remain in the order of the BASE constants above
260    private static final String[][] CACHE_PROJECTIONS = {
261        Account.CONTENT_PROJECTION,
262        Mailbox.CONTENT_PROJECTION,
263        Message.CONTENT_PROJECTION,
264        null, // Attachment
265        HostAuth.CONTENT_PROJECTION,
266        null, // Updated message
267        null, // Deleted message
268        Policy.CONTENT_PROJECTION,
269        null,  // Quick response
270        null  // Body
271    };
272
273    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
274
275    private static final String MAILBOX_PRE_CACHE_SELECTION = MailboxColumns.TYPE + " IN (" +
276        Mailbox.TYPE_INBOX + "," + Mailbox.TYPE_DRAFTS + "," + Mailbox.TYPE_TRASH + "," +
277        Mailbox.TYPE_SENT + "," + Mailbox.TYPE_SEARCH + "," + Mailbox.TYPE_OUTBOX + ")";
278
279    /**
280     * Let's only generate these SQL strings once, as they are used frequently
281     * Note that this isn't relevant for table creation strings, since they are used only once
282     */
283    private static final String UPDATED_MESSAGE_INSERT = "insert or ignore into " +
284        Message.UPDATED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
285        EmailContent.RECORD_ID + '=';
286
287    private static final String UPDATED_MESSAGE_DELETE = "delete from " +
288        Message.UPDATED_TABLE_NAME + " where " + EmailContent.RECORD_ID + '=';
289
290    private static final String DELETED_MESSAGE_INSERT = "insert or replace into " +
291        Message.DELETED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
292        EmailContent.RECORD_ID + '=';
293
294    private static final String DELETE_ORPHAN_BODIES = "delete from " + Body.TABLE_NAME +
295        " where " + BodyColumns.MESSAGE_KEY + " in " + "(select " + BodyColumns.MESSAGE_KEY +
296        " from " + Body.TABLE_NAME + " except select " + EmailContent.RECORD_ID + " from " +
297        Message.TABLE_NAME + ')';
298
299    private static final String DELETE_BODY = "delete from " + Body.TABLE_NAME +
300        " where " + BodyColumns.MESSAGE_KEY + '=';
301
302    private static final String ID_EQUALS = EmailContent.RECORD_ID + "=?";
303
304    private static final String TRIGGER_MAILBOX_DELETE =
305        "create trigger mailbox_delete before delete on " + Mailbox.TABLE_NAME +
306        " begin" +
307        " delete from " + Message.TABLE_NAME +
308        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
309        "; delete from " + Message.UPDATED_TABLE_NAME +
310        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
311        "; delete from " + Message.DELETED_TABLE_NAME +
312        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
313        "; end";
314
315    private static final String TRIGGER_ACCOUNT_DELETE =
316        "create trigger account_delete before delete on " + Account.TABLE_NAME +
317        " begin delete from " + Mailbox.TABLE_NAME +
318        " where " + MailboxColumns.ACCOUNT_KEY + "=old." + EmailContent.RECORD_ID +
319        "; delete from " + HostAuth.TABLE_NAME +
320        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_RECV +
321        "; delete from " + HostAuth.TABLE_NAME +
322        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_SEND +
323        "; delete from " + Policy.TABLE_NAME +
324        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.POLICY_KEY +
325        "; end";
326
327    private static final ContentValues CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
328
329    public static final String MESSAGE_URI_PARAMETER_MAILBOX_ID = "mailboxId";
330
331    static {
332        // Email URI matching table
333        UriMatcher matcher = sURIMatcher;
334
335        // All accounts
336        matcher.addURI(EmailContent.AUTHORITY, "account", ACCOUNT);
337        // A specific account
338        // insert into this URI causes a mailbox to be added to the account
339        matcher.addURI(EmailContent.AUTHORITY, "account/#", ACCOUNT_ID);
340        matcher.addURI(EmailContent.AUTHORITY, "account/default", ACCOUNT_DEFAULT_ID);
341
342        // Special URI to reset the new message count.  Only update works, and content values
343        // will be ignored.
344        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount",
345                ACCOUNT_RESET_NEW_COUNT);
346        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount/#",
347                ACCOUNT_RESET_NEW_COUNT_ID);
348
349        // All mailboxes
350        matcher.addURI(EmailContent.AUTHORITY, "mailbox", MAILBOX);
351        // A specific mailbox
352        // insert into this URI causes a message to be added to the mailbox
353        // ** NOTE For now, the accountKey must be set manually in the values!
354        matcher.addURI(EmailContent.AUTHORITY, "mailbox/#", MAILBOX_ID);
355        matcher.addURI(EmailContent.AUTHORITY, "mailboxIdFromAccountAndType/#/#",
356                MAILBOX_ID_FROM_ACCOUNT_AND_TYPE);
357        // All messages
358        matcher.addURI(EmailContent.AUTHORITY, "message", MESSAGE);
359        // A specific message
360        // insert into this URI causes an attachment to be added to the message
361        matcher.addURI(EmailContent.AUTHORITY, "message/#", MESSAGE_ID);
362
363        // A specific attachment
364        matcher.addURI(EmailContent.AUTHORITY, "attachment", ATTACHMENT);
365        // A specific attachment (the header information)
366        matcher.addURI(EmailContent.AUTHORITY, "attachment/#", ATTACHMENT_ID);
367        // The attachments of a specific message (query only) (insert & delete TBD)
368        matcher.addURI(EmailContent.AUTHORITY, "attachment/message/#",
369                ATTACHMENTS_MESSAGE_ID);
370
371        // All mail bodies
372        matcher.addURI(EmailContent.AUTHORITY, "body", BODY);
373        // A specific mail body
374        matcher.addURI(EmailContent.AUTHORITY, "body/#", BODY_ID);
375
376        // All hostauth records
377        matcher.addURI(EmailContent.AUTHORITY, "hostauth", HOSTAUTH);
378        // A specific hostauth
379        matcher.addURI(EmailContent.AUTHORITY, "hostauth/#", HOSTAUTH_ID);
380
381        // Atomically a constant value to a particular field of a mailbox/account
382        matcher.addURI(EmailContent.AUTHORITY, "mailboxIdAddToField/#",
383                MAILBOX_ID_ADD_TO_FIELD);
384        matcher.addURI(EmailContent.AUTHORITY, "accountIdAddToField/#",
385                ACCOUNT_ID_ADD_TO_FIELD);
386
387        /**
388         * THIS URI HAS SPECIAL SEMANTICS
389         * ITS USE IS INTENDED FOR THE UI APPLICATION TO MARK CHANGES THAT NEED TO BE SYNCED BACK
390         * TO A SERVER VIA A SYNC ADAPTER
391         */
392        matcher.addURI(EmailContent.AUTHORITY, "syncedMessage/#", SYNCED_MESSAGE_ID);
393
394        /**
395         * THE URIs BELOW THIS POINT ARE INTENDED TO BE USED BY SYNC ADAPTERS ONLY
396         * THEY REFER TO DATA CREATED AND MAINTAINED BY CALLS TO THE SYNCED_MESSAGE_ID URI
397         * BY THE UI APPLICATION
398         */
399        // All deleted messages
400        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage", DELETED_MESSAGE);
401        // A specific deleted message
402        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage/#", DELETED_MESSAGE_ID);
403
404        // All updated messages
405        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage", UPDATED_MESSAGE);
406        // A specific updated message
407        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage/#", UPDATED_MESSAGE_ID);
408
409        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT = new ContentValues();
410        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT.put(Account.NEW_MESSAGE_COUNT, 0);
411
412        matcher.addURI(EmailContent.AUTHORITY, "policy", POLICY);
413        matcher.addURI(EmailContent.AUTHORITY, "policy/#", POLICY_ID);
414
415        // All quick responses
416        matcher.addURI(EmailContent.AUTHORITY, "quickresponse", QUICK_RESPONSE);
417        // A specific quick response
418        matcher.addURI(EmailContent.AUTHORITY, "quickresponse/#", QUICK_RESPONSE_ID);
419        // All quick responses associated with a particular account id
420        matcher.addURI(EmailContent.AUTHORITY, "quickresponse/account/#",
421                QUICK_RESPONSE_ACCOUNT_ID);
422    }
423
424    /**
425     * Wrap the UriMatcher call so we can throw a runtime exception if an unknown Uri is passed in
426     * @param uri the Uri to match
427     * @return the match value
428     */
429    private static int findMatch(Uri uri, String methodName) {
430        int match = sURIMatcher.match(uri);
431        if (match < 0) {
432            throw new IllegalArgumentException("Unknown uri: " + uri);
433        } else if (Logging.LOGD) {
434            Log.v(TAG, methodName + ": uri=" + uri + ", match is " + match);
435        }
436        return match;
437    }
438
439    /*
440     * Internal helper method for index creation.
441     * Example:
442     * "create index message_" + MessageColumns.FLAG_READ
443     * + " on " + Message.TABLE_NAME + " (" + MessageColumns.FLAG_READ + ");"
444     */
445    /* package */
446    static String createIndex(String tableName, String columnName) {
447        return "create index " + tableName.toLowerCase() + '_' + columnName
448            + " on " + tableName + " (" + columnName + ");";
449    }
450
451    static void createMessageTable(SQLiteDatabase db) {
452        String messageColumns = MessageColumns.DISPLAY_NAME + " text, "
453            + MessageColumns.TIMESTAMP + " integer, "
454            + MessageColumns.SUBJECT + " text, "
455            + MessageColumns.FLAG_READ + " integer, "
456            + MessageColumns.FLAG_LOADED + " integer, "
457            + MessageColumns.FLAG_FAVORITE + " integer, "
458            + MessageColumns.FLAG_ATTACHMENT + " integer, "
459            + MessageColumns.FLAGS + " integer, "
460            + MessageColumns.CLIENT_ID + " integer, "
461            + MessageColumns.MESSAGE_ID + " text, "
462            + MessageColumns.MAILBOX_KEY + " integer, "
463            + MessageColumns.ACCOUNT_KEY + " integer, "
464            + MessageColumns.FROM_LIST + " text, "
465            + MessageColumns.TO_LIST + " text, "
466            + MessageColumns.CC_LIST + " text, "
467            + MessageColumns.BCC_LIST + " text, "
468            + MessageColumns.REPLY_TO_LIST + " text, "
469            + MessageColumns.MEETING_INFO + " text, "
470            + MessageColumns.SNIPPET + " text, "
471            + MessageColumns.PROTOCOL_SEARCH_INFO + " text"
472            + ");";
473
474        // This String and the following String MUST have the same columns, except for the type
475        // of those columns!
476        String createString = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
477            + SyncColumns.SERVER_ID + " text, "
478            + SyncColumns.SERVER_TIMESTAMP + " integer, "
479            + messageColumns;
480
481        // For the updated and deleted tables, the id is assigned, but we do want to keep track
482        // of the ORDER of updates using an autoincrement primary key.  We use the DATA column
483        // at this point; it has no other function
484        String altCreateString = " (" + EmailContent.RECORD_ID + " integer unique, "
485            + SyncColumns.SERVER_ID + " text, "
486            + SyncColumns.SERVER_TIMESTAMP + " integer, "
487            + messageColumns;
488
489        // The three tables have the same schema
490        db.execSQL("create table " + Message.TABLE_NAME + createString);
491        db.execSQL("create table " + Message.UPDATED_TABLE_NAME + altCreateString);
492        db.execSQL("create table " + Message.DELETED_TABLE_NAME + altCreateString);
493
494        String indexColumns[] = {
495            MessageColumns.TIMESTAMP,
496            MessageColumns.FLAG_READ,
497            MessageColumns.FLAG_LOADED,
498            MessageColumns.MAILBOX_KEY,
499            SyncColumns.SERVER_ID
500        };
501
502        for (String columnName : indexColumns) {
503            db.execSQL(createIndex(Message.TABLE_NAME, columnName));
504        }
505
506        // Deleting a Message deletes all associated Attachments
507        // Deleting the associated Body cannot be done in a trigger, because the Body is stored
508        // in a separate database, and trigger cannot operate on attached databases.
509        db.execSQL("create trigger message_delete before delete on " + Message.TABLE_NAME +
510                " begin delete from " + Attachment.TABLE_NAME +
511                "  where " + AttachmentColumns.MESSAGE_KEY + "=old." + EmailContent.RECORD_ID +
512                "; end");
513
514        // Add triggers to keep unread count accurate per mailbox
515
516        // NOTE: SQLite's before triggers are not safe when recursive triggers are involved.
517        // Use caution when changing them.
518
519        // Insert a message; if flagRead is zero, add to the unread count of the message's mailbox
520        db.execSQL("create trigger unread_message_insert before insert on " + Message.TABLE_NAME +
521                " when NEW." + MessageColumns.FLAG_READ + "=0" +
522                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
523                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
524                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
525                "; end");
526
527        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
528        db.execSQL("create trigger unread_message_delete before delete on " + Message.TABLE_NAME +
529                " when OLD." + MessageColumns.FLAG_READ + "=0" +
530                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
531                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
532                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
533                "; end");
534
535        // Change a message's mailbox
536        db.execSQL("create trigger unread_message_move before update of " +
537                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
538                " when OLD." + MessageColumns.FLAG_READ + "=0" +
539                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
540                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
541                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
542                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
543                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
544                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
545                "; end");
546
547        // Change a message's read state
548        db.execSQL("create trigger unread_message_read before update of " +
549                MessageColumns.FLAG_READ + " on " + Message.TABLE_NAME +
550                " when OLD." + MessageColumns.FLAG_READ + "!=NEW." + MessageColumns.FLAG_READ +
551                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
552                '=' + MailboxColumns.UNREAD_COUNT + "+ case OLD." + MessageColumns.FLAG_READ +
553                " when 0 then -1 else 1 end" +
554                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
555                "; end");
556
557        // Add triggers to update message count per mailbox
558
559        // Insert a message.
560        db.execSQL("create trigger message_count_message_insert after insert on " +
561                Message.TABLE_NAME +
562                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
563                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
564                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
565                "; end");
566
567        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
568        db.execSQL("create trigger message_count_message_delete after delete on " +
569                Message.TABLE_NAME +
570                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
571                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
572                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
573                "; end");
574
575        // Change a message's mailbox
576        db.execSQL("create trigger message_count_message_move after update of " +
577                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
578                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
579                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
580                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
581                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
582                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
583                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
584                "; end");
585    }
586
587    static void resetMessageTable(SQLiteDatabase db, int oldVersion, int newVersion) {
588        try {
589            db.execSQL("drop table " + Message.TABLE_NAME);
590            db.execSQL("drop table " + Message.UPDATED_TABLE_NAME);
591            db.execSQL("drop table " + Message.DELETED_TABLE_NAME);
592        } catch (SQLException e) {
593        }
594        createMessageTable(db);
595    }
596
597    @SuppressWarnings("deprecation")
598    static void createAccountTable(SQLiteDatabase db) {
599        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
600            + AccountColumns.DISPLAY_NAME + " text, "
601            + AccountColumns.EMAIL_ADDRESS + " text, "
602            + AccountColumns.SYNC_KEY + " text, "
603            + AccountColumns.SYNC_LOOKBACK + " integer, "
604            + AccountColumns.SYNC_INTERVAL + " text, "
605            + AccountColumns.HOST_AUTH_KEY_RECV + " integer, "
606            + AccountColumns.HOST_AUTH_KEY_SEND + " integer, "
607            + AccountColumns.FLAGS + " integer, "
608            + AccountColumns.IS_DEFAULT + " integer, "
609            + AccountColumns.COMPATIBILITY_UUID + " text, "
610            + AccountColumns.SENDER_NAME + " text, "
611            + AccountColumns.RINGTONE_URI + " text, "
612            + AccountColumns.PROTOCOL_VERSION + " text, "
613            + AccountColumns.NEW_MESSAGE_COUNT + " integer, "
614            + AccountColumns.SECURITY_FLAGS + " integer, "
615            + AccountColumns.SECURITY_SYNC_KEY + " text, "
616            + AccountColumns.SIGNATURE + " text, "
617            + AccountColumns.POLICY_KEY + " integer, "
618            + AccountColumns.NOTIFIED_MESSAGE_ID + " integer, "
619            + AccountColumns.NOTIFIED_MESSAGE_COUNT + " integer"
620            + ");";
621        db.execSQL("create table " + Account.TABLE_NAME + s);
622        // Deleting an account deletes associated Mailboxes and HostAuth's
623        db.execSQL(TRIGGER_ACCOUNT_DELETE);
624    }
625
626    static void resetAccountTable(SQLiteDatabase db, int oldVersion, int newVersion) {
627        try {
628            db.execSQL("drop table " +  Account.TABLE_NAME);
629        } catch (SQLException e) {
630        }
631        createAccountTable(db);
632    }
633
634    static void createPolicyTable(SQLiteDatabase db) {
635        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
636            + PolicyColumns.PASSWORD_MODE + " integer, "
637            + PolicyColumns.PASSWORD_MIN_LENGTH + " integer, "
638            + PolicyColumns.PASSWORD_EXPIRATION_DAYS + " integer, "
639            + PolicyColumns.PASSWORD_HISTORY + " integer, "
640            + PolicyColumns.PASSWORD_COMPLEX_CHARS + " integer, "
641            + PolicyColumns.PASSWORD_MAX_FAILS + " integer, "
642            + PolicyColumns.MAX_SCREEN_LOCK_TIME + " integer, "
643            + PolicyColumns.REQUIRE_REMOTE_WIPE + " integer, "
644            + PolicyColumns.REQUIRE_ENCRYPTION + " integer, "
645            + PolicyColumns.REQUIRE_ENCRYPTION_EXTERNAL + " integer, "
646            + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING + " integer, "
647            + PolicyColumns.DONT_ALLOW_CAMERA + " integer, "
648            + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer, "
649            + PolicyColumns.DONT_ALLOW_HTML + " integer, "
650            + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer, "
651            + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE + " integer, "
652            + PolicyColumns.MAX_HTML_TRUNCATION_SIZE + " integer, "
653            + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer, "
654            + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer, "
655            + PolicyColumns.PASSWORD_RECOVERY_ENABLED + " integer, "
656            + PolicyColumns.PROTOCOL_POLICIES_ENFORCED + " text, "
657            + PolicyColumns.PROTOCOL_POLICIES_UNSUPPORTED + " text"
658            + ");";
659        db.execSQL("create table " + Policy.TABLE_NAME + s);
660    }
661
662    static void createHostAuthTable(SQLiteDatabase db) {
663        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
664            + HostAuthColumns.PROTOCOL + " text, "
665            + HostAuthColumns.ADDRESS + " text, "
666            + HostAuthColumns.PORT + " integer, "
667            + HostAuthColumns.FLAGS + " integer, "
668            + HostAuthColumns.LOGIN + " text, "
669            + HostAuthColumns.PASSWORD + " text, "
670            + HostAuthColumns.DOMAIN + " text, "
671            + HostAuthColumns.ACCOUNT_KEY + " integer,"
672            + HostAuthColumns.CLIENT_CERT_ALIAS + " text"
673            + ");";
674        db.execSQL("create table " + HostAuth.TABLE_NAME + s);
675    }
676
677    static void resetHostAuthTable(SQLiteDatabase db, int oldVersion, int newVersion) {
678        try {
679            db.execSQL("drop table " + HostAuth.TABLE_NAME);
680        } catch (SQLException e) {
681        }
682        createHostAuthTable(db);
683    }
684
685    static void createMailboxTable(SQLiteDatabase db) {
686        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
687            + MailboxColumns.DISPLAY_NAME + " text, "
688            + MailboxColumns.SERVER_ID + " text, "
689            + MailboxColumns.PARENT_SERVER_ID + " text, "
690            + MailboxColumns.PARENT_KEY + " integer, "
691            + MailboxColumns.ACCOUNT_KEY + " integer, "
692            + MailboxColumns.TYPE + " integer, "
693            + MailboxColumns.DELIMITER + " integer, "
694            + MailboxColumns.SYNC_KEY + " text, "
695            + MailboxColumns.SYNC_LOOKBACK + " integer, "
696            + MailboxColumns.SYNC_INTERVAL + " integer, "
697            + MailboxColumns.SYNC_TIME + " integer, "
698            + MailboxColumns.UNREAD_COUNT + " integer, "
699            + MailboxColumns.FLAG_VISIBLE + " integer, "
700            + MailboxColumns.FLAGS + " integer, "
701            + MailboxColumns.VISIBLE_LIMIT + " integer, "
702            + MailboxColumns.SYNC_STATUS + " text, "
703            + MailboxColumns.MESSAGE_COUNT + " integer not null default 0, "
704            + MailboxColumns.LAST_SEEN_MESSAGE_KEY + " integer, "
705            + MailboxColumns.LAST_TOUCHED_TIME + " integer default 0"
706            + ");";
707        db.execSQL("create table " + Mailbox.TABLE_NAME + s);
708        db.execSQL("create index mailbox_" + MailboxColumns.SERVER_ID
709                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.SERVER_ID + ")");
710        db.execSQL("create index mailbox_" + MailboxColumns.ACCOUNT_KEY
711                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.ACCOUNT_KEY + ")");
712        // Deleting a Mailbox deletes associated Messages in all three tables
713        db.execSQL(TRIGGER_MAILBOX_DELETE);
714    }
715
716    static void resetMailboxTable(SQLiteDatabase db, int oldVersion, int newVersion) {
717        try {
718            db.execSQL("drop table " + Mailbox.TABLE_NAME);
719        } catch (SQLException e) {
720        }
721        createMailboxTable(db);
722    }
723
724    static void createAttachmentTable(SQLiteDatabase db) {
725        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
726            + AttachmentColumns.FILENAME + " text, "
727            + AttachmentColumns.MIME_TYPE + " text, "
728            + AttachmentColumns.SIZE + " integer, "
729            + AttachmentColumns.CONTENT_ID + " text, "
730            + AttachmentColumns.CONTENT_URI + " text, "
731            + AttachmentColumns.MESSAGE_KEY + " integer, "
732            + AttachmentColumns.LOCATION + " text, "
733            + AttachmentColumns.ENCODING + " text, "
734            + AttachmentColumns.CONTENT + " text, "
735            + AttachmentColumns.FLAGS + " integer, "
736            + AttachmentColumns.CONTENT_BYTES + " blob, "
737            + AttachmentColumns.ACCOUNT_KEY + " integer"
738            + ");";
739        db.execSQL("create table " + Attachment.TABLE_NAME + s);
740        db.execSQL(createIndex(Attachment.TABLE_NAME, AttachmentColumns.MESSAGE_KEY));
741    }
742
743    static void resetAttachmentTable(SQLiteDatabase db, int oldVersion, int newVersion) {
744        try {
745            db.execSQL("drop table " + Attachment.TABLE_NAME);
746        } catch (SQLException e) {
747        }
748        createAttachmentTable(db);
749    }
750
751    static void createQuickResponseTable(SQLiteDatabase db) {
752        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
753                + QuickResponseColumns.TEXT + " text, "
754                + QuickResponseColumns.ACCOUNT_KEY + " integer"
755                + ");";
756        db.execSQL("create table " + QuickResponse.TABLE_NAME + s);
757    }
758
759    static void createBodyTable(SQLiteDatabase db) {
760        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
761            + BodyColumns.MESSAGE_KEY + " integer, "
762            + BodyColumns.HTML_CONTENT + " text, "
763            + BodyColumns.TEXT_CONTENT + " text, "
764            + BodyColumns.HTML_REPLY + " text, "
765            + BodyColumns.TEXT_REPLY + " text, "
766            + BodyColumns.SOURCE_MESSAGE_KEY + " text, "
767            + BodyColumns.INTRO_TEXT + " text"
768            + ");";
769        db.execSQL("create table " + Body.TABLE_NAME + s);
770        db.execSQL(createIndex(Body.TABLE_NAME, BodyColumns.MESSAGE_KEY));
771    }
772
773    static void upgradeBodyTable(SQLiteDatabase db, int oldVersion, int newVersion) {
774        if (oldVersion < 5) {
775            try {
776                db.execSQL("drop table " + Body.TABLE_NAME);
777                createBodyTable(db);
778            } catch (SQLException e) {
779            }
780        } else if (oldVersion == 5) {
781            try {
782                db.execSQL("alter table " + Body.TABLE_NAME
783                        + " add " + BodyColumns.INTRO_TEXT + " text");
784            } catch (SQLException e) {
785                // Shouldn't be needed unless we're debugging and interrupt the process
786                Log.w(TAG, "Exception upgrading EmailProviderBody.db from v5 to v6", e);
787            }
788            oldVersion = 6;
789        }
790    }
791
792    private SQLiteDatabase mDatabase;
793    private SQLiteDatabase mBodyDatabase;
794
795    /**
796     * Orphan record deletion utility.  Generates a sqlite statement like:
797     *  delete from <table> where <column> not in (select <foreignColumn> from <foreignTable>)
798     * @param db the EmailProvider database
799     * @param table the table whose orphans are to be removed
800     * @param column the column deletion will be based on
801     * @param foreignColumn the column in the foreign table whose absence will trigger the deletion
802     * @param foreignTable the foreign table
803     */
804    @VisibleForTesting
805    void deleteUnlinked(SQLiteDatabase db, String table, String column, String foreignColumn,
806            String foreignTable) {
807        int count = db.delete(table, column + " not in (select " + foreignColumn + " from " +
808                foreignTable + ")", null);
809        if (count > 0) {
810            Log.w(TAG, "Found " + count + " orphaned row(s) in " + table);
811        }
812    }
813
814    @VisibleForTesting
815    synchronized SQLiteDatabase getDatabase(Context context) {
816        // Always return the cached database, if we've got one
817        if (mDatabase != null) {
818            return mDatabase;
819        }
820
821        // Whenever we create or re-cache the databases, make sure that we haven't lost one
822        // to corruption
823        checkDatabases();
824
825        DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
826        mDatabase = helper.getWritableDatabase();
827        mDatabase.setLockingEnabled(true);
828        BodyDatabaseHelper bodyHelper = new BodyDatabaseHelper(context, BODY_DATABASE_NAME);
829        mBodyDatabase = bodyHelper.getWritableDatabase();
830        if (mBodyDatabase != null) {
831            mBodyDatabase.setLockingEnabled(true);
832            String bodyFileName = mBodyDatabase.getPath();
833            mDatabase.execSQL("attach \"" + bodyFileName + "\" as BodyDatabase");
834        }
835
836        // Restore accounts if the database is corrupted...
837        restoreIfNeeded(context, mDatabase);
838
839        if (Email.DEBUG) {
840            Log.d(TAG, "Deleting orphans...");
841        }
842        // Check for any orphaned Messages in the updated/deleted tables
843        deleteMessageOrphans(mDatabase, Message.UPDATED_TABLE_NAME);
844        deleteMessageOrphans(mDatabase, Message.DELETED_TABLE_NAME);
845        // Delete orphaned mailboxes/messages/policies (account no longer exists)
846        deleteUnlinked(mDatabase, Mailbox.TABLE_NAME, MailboxColumns.ACCOUNT_KEY, AccountColumns.ID,
847                Account.TABLE_NAME);
848        deleteUnlinked(mDatabase, Message.TABLE_NAME, MessageColumns.ACCOUNT_KEY, AccountColumns.ID,
849                Account.TABLE_NAME);
850        deleteUnlinked(mDatabase, Policy.TABLE_NAME, PolicyColumns.ID, AccountColumns.POLICY_KEY,
851                Account.TABLE_NAME);
852
853        if (Email.DEBUG) {
854            Log.d(TAG, "EmailProvider pre-caching...");
855        }
856        preCacheData();
857        if (Email.DEBUG) {
858            Log.d(TAG, "EmailProvider ready.");
859        }
860        return mDatabase;
861    }
862
863    /**
864     * Pre-cache all of the items in a given table meeting the selection criteria
865     * @param tableUri the table uri
866     * @param baseProjection the base projection of that table
867     * @param selection the selection criteria
868     */
869    private void preCacheTable(Uri tableUri, String[] baseProjection, String selection) {
870        Cursor c = query(tableUri, EmailContent.ID_PROJECTION, selection, null, null);
871        try {
872            while (c.moveToNext()) {
873                long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN);
874                Cursor cachedCursor = query(ContentUris.withAppendedId(
875                        tableUri, id), baseProjection, null, null, null);
876                if (cachedCursor != null) {
877                    // For accounts, create a mailbox type map entry (if necessary)
878                    if (tableUri == Account.CONTENT_URI) {
879                        getOrCreateAccountMailboxTypeMap(id);
880                    }
881                    cachedCursor.close();
882                }
883            }
884        } finally {
885            c.close();
886        }
887    }
888
889    private final HashMap<Long, HashMap<Integer, Long>> mMailboxTypeMap =
890        new HashMap<Long, HashMap<Integer, Long>>();
891
892    private HashMap<Integer, Long> getOrCreateAccountMailboxTypeMap(long accountId) {
893        synchronized(mMailboxTypeMap) {
894            HashMap<Integer, Long> accountMailboxTypeMap = mMailboxTypeMap.get(accountId);
895            if (accountMailboxTypeMap == null) {
896                accountMailboxTypeMap = new HashMap<Integer, Long>();
897                mMailboxTypeMap.put(accountId, accountMailboxTypeMap);
898            }
899            return accountMailboxTypeMap;
900        }
901    }
902
903    private void addToMailboxTypeMap(Cursor c) {
904        long accountId = c.getLong(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN);
905        int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
906        synchronized(mMailboxTypeMap) {
907            HashMap<Integer, Long> accountMailboxTypeMap =
908                getOrCreateAccountMailboxTypeMap(accountId);
909            accountMailboxTypeMap.put(type, c.getLong(Mailbox.CONTENT_ID_COLUMN));
910        }
911    }
912
913    private long getMailboxIdFromMailboxTypeMap(long accountId, int type) {
914        synchronized(mMailboxTypeMap) {
915            HashMap<Integer, Long> accountMap = mMailboxTypeMap.get(accountId);
916            Long mailboxId = null;
917            if (accountMap != null) {
918                mailboxId = accountMap.get(type);
919            }
920            if (mailboxId == null) return Mailbox.NO_MAILBOX;
921            return mailboxId;
922        }
923    }
924
925    private void preCacheData() {
926        synchronized(mMailboxTypeMap) {
927            mMailboxTypeMap.clear();
928
929            // Pre-cache accounts, host auth's, policies, and special mailboxes
930            preCacheTable(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null);
931            preCacheTable(HostAuth.CONTENT_URI, HostAuth.CONTENT_PROJECTION, null);
932            preCacheTable(Policy.CONTENT_URI, Policy.CONTENT_PROJECTION, null);
933            preCacheTable(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
934                    MAILBOX_PRE_CACHE_SELECTION);
935
936            // Create a map from account,type to a mailbox
937            Map<String, Cursor> snapshot = mCacheMailbox.getSnapshot();
938            Collection<Cursor> values = snapshot.values();
939            if (values != null) {
940                for (Cursor c: values) {
941                    if (c.moveToFirst()) {
942                        addToMailboxTypeMap(c);
943                    }
944                }
945            }
946        }
947    }
948
949    /*package*/ static SQLiteDatabase getReadableDatabase(Context context) {
950        DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
951        return helper.getReadableDatabase();
952    }
953
954    /**
955     * Restore user Account and HostAuth data from our backup database
956     */
957    public static void restoreIfNeeded(Context context, SQLiteDatabase mainDatabase) {
958        if (Email.DEBUG) {
959            Log.w(TAG, "restoreIfNeeded...");
960        }
961        // Check for legacy backup
962        String legacyBackup = Preferences.getLegacyBackupPreference(context);
963        // If there's a legacy backup, create a new-style backup and delete the legacy backup
964        // In the 1:1000000000 chance that the user gets an app update just as his database becomes
965        // corrupt, oh well...
966        if (!TextUtils.isEmpty(legacyBackup)) {
967            backupAccounts(context, mainDatabase);
968            Preferences.clearLegacyBackupPreference(context);
969            Log.w(TAG, "Created new EmailProvider backup database");
970            return;
971        }
972
973        // If we have accounts, we're done
974        Cursor c = mainDatabase.query(Account.TABLE_NAME, EmailContent.ID_PROJECTION, null, null,
975                null, null, null);
976        if (c.moveToFirst()) {
977            if (Email.DEBUG) {
978                Log.w(TAG, "restoreIfNeeded: Account exists.");
979            }
980            return; // At least one account exists.
981        }
982        restoreAccounts(context, mainDatabase);
983    }
984
985    /** {@inheritDoc} */
986    @Override
987    public void shutdown() {
988        if (mDatabase != null) {
989            mDatabase.close();
990            mDatabase = null;
991        }
992        if (mBodyDatabase != null) {
993            mBodyDatabase.close();
994            mBodyDatabase = null;
995        }
996    }
997
998    /*package*/ static void deleteMessageOrphans(SQLiteDatabase database, String tableName) {
999        if (database != null) {
1000            // We'll look at all of the items in the table; there won't be many typically
1001            Cursor c = database.query(tableName, ORPHANS_PROJECTION, null, null, null, null, null);
1002            // Usually, there will be nothing in these tables, so make a quick check
1003            try {
1004                if (c.getCount() == 0) return;
1005                ArrayList<Long> foundMailboxes = new ArrayList<Long>();
1006                ArrayList<Long> notFoundMailboxes = new ArrayList<Long>();
1007                ArrayList<Long> deleteList = new ArrayList<Long>();
1008                String[] bindArray = new String[1];
1009                while (c.moveToNext()) {
1010                    // Get the mailbox key and see if we've already found this mailbox
1011                    // If so, we're fine
1012                    long mailboxId = c.getLong(ORPHANS_MAILBOX_KEY);
1013                    // If we already know this mailbox doesn't exist, mark the message for deletion
1014                    if (notFoundMailboxes.contains(mailboxId)) {
1015                        deleteList.add(c.getLong(ORPHANS_ID));
1016                    // If we don't know about this mailbox, we'll try to find it
1017                    } else if (!foundMailboxes.contains(mailboxId)) {
1018                        bindArray[0] = Long.toString(mailboxId);
1019                        Cursor boxCursor = database.query(Mailbox.TABLE_NAME,
1020                                Mailbox.ID_PROJECTION, WHERE_ID, bindArray, null, null, null);
1021                        try {
1022                            // If it exists, we'll add it to the "found" mailboxes
1023                            if (boxCursor.moveToFirst()) {
1024                                foundMailboxes.add(mailboxId);
1025                            // Otherwise, we'll add to "not found" and mark the message for deletion
1026                            } else {
1027                                notFoundMailboxes.add(mailboxId);
1028                                deleteList.add(c.getLong(ORPHANS_ID));
1029                            }
1030                        } finally {
1031                            boxCursor.close();
1032                        }
1033                    }
1034                }
1035                // Now, delete the orphan messages
1036                for (long messageId: deleteList) {
1037                    bindArray[0] = Long.toString(messageId);
1038                    database.delete(tableName, WHERE_ID, bindArray);
1039                }
1040            } finally {
1041                c.close();
1042            }
1043        }
1044    }
1045
1046    private class BodyDatabaseHelper extends SQLiteOpenHelper {
1047        BodyDatabaseHelper(Context context, String name) {
1048            super(context, name, null, BODY_DATABASE_VERSION);
1049        }
1050
1051        @Override
1052        public void onCreate(SQLiteDatabase db) {
1053            Log.d(TAG, "Creating EmailProviderBody database");
1054            createBodyTable(db);
1055        }
1056
1057        @Override
1058        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1059            upgradeBodyTable(db, oldVersion, newVersion);
1060        }
1061
1062        @Override
1063        public void onOpen(SQLiteDatabase db) {
1064        }
1065    }
1066
1067    private static class DatabaseHelper extends SQLiteOpenHelper {
1068        Context mContext;
1069
1070        DatabaseHelper(Context context, String name) {
1071            super(context, name, null, DATABASE_VERSION);
1072            mContext = context;
1073        }
1074
1075        @Override
1076        public void onCreate(SQLiteDatabase db) {
1077            Log.d(TAG, "Creating EmailProvider database");
1078            // Create all tables here; each class has its own method
1079            createMessageTable(db);
1080            createAttachmentTable(db);
1081            createMailboxTable(db);
1082            createHostAuthTable(db);
1083            createAccountTable(db);
1084            createPolicyTable(db);
1085            createQuickResponseTable(db);
1086        }
1087
1088        @Override
1089        @SuppressWarnings("deprecation")
1090        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1091            // For versions prior to 5, delete all data
1092            // Versions >= 5 require that data be preserved!
1093            if (oldVersion < 5) {
1094                android.accounts.Account[] accounts = AccountManager.get(mContext)
1095                        .getAccountsByType(AccountManagerTypes.TYPE_EXCHANGE);
1096                for (android.accounts.Account account: accounts) {
1097                    AccountManager.get(mContext).removeAccount(account, null, null);
1098                }
1099                resetMessageTable(db, oldVersion, newVersion);
1100                resetAttachmentTable(db, oldVersion, newVersion);
1101                resetMailboxTable(db, oldVersion, newVersion);
1102                resetHostAuthTable(db, oldVersion, newVersion);
1103                resetAccountTable(db, oldVersion, newVersion);
1104                return;
1105            }
1106            if (oldVersion == 5) {
1107                // Message Tables: Add SyncColumns.SERVER_TIMESTAMP
1108                try {
1109                    db.execSQL("alter table " + Message.TABLE_NAME
1110                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1111                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1112                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1113                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1114                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1115                } catch (SQLException e) {
1116                    // Shouldn't be needed unless we're debugging and interrupt the process
1117                    Log.w(TAG, "Exception upgrading EmailProvider.db from v5 to v6", e);
1118                }
1119                oldVersion = 6;
1120            }
1121            if (oldVersion == 6) {
1122                // Use the newer mailbox_delete trigger
1123                db.execSQL("drop trigger mailbox_delete;");
1124                db.execSQL(TRIGGER_MAILBOX_DELETE);
1125                oldVersion = 7;
1126            }
1127            if (oldVersion == 7) {
1128                // add the security (provisioning) column
1129                try {
1130                    db.execSQL("alter table " + Account.TABLE_NAME
1131                            + " add column " + AccountColumns.SECURITY_FLAGS + " integer" + ";");
1132                } catch (SQLException e) {
1133                    // Shouldn't be needed unless we're debugging and interrupt the process
1134                    Log.w(TAG, "Exception upgrading EmailProvider.db from 7 to 8 " + e);
1135                }
1136                oldVersion = 8;
1137            }
1138            if (oldVersion == 8) {
1139                // accounts: add security sync key & user signature columns
1140                try {
1141                    db.execSQL("alter table " + Account.TABLE_NAME
1142                            + " add column " + AccountColumns.SECURITY_SYNC_KEY + " text" + ";");
1143                    db.execSQL("alter table " + Account.TABLE_NAME
1144                            + " add column " + AccountColumns.SIGNATURE + " text" + ";");
1145                } catch (SQLException e) {
1146                    // Shouldn't be needed unless we're debugging and interrupt the process
1147                    Log.w(TAG, "Exception upgrading EmailProvider.db from 8 to 9 " + e);
1148                }
1149                oldVersion = 9;
1150            }
1151            if (oldVersion == 9) {
1152                // Message: add meeting info column into Message tables
1153                try {
1154                    db.execSQL("alter table " + Message.TABLE_NAME
1155                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1156                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1157                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1158                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1159                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1160                } catch (SQLException e) {
1161                    // Shouldn't be needed unless we're debugging and interrupt the process
1162                    Log.w(TAG, "Exception upgrading EmailProvider.db from 9 to 10 " + e);
1163                }
1164                oldVersion = 10;
1165            }
1166            if (oldVersion == 10) {
1167                // Attachment: add content and flags columns
1168                try {
1169                    db.execSQL("alter table " + Attachment.TABLE_NAME
1170                            + " add column " + AttachmentColumns.CONTENT + " text" + ";");
1171                    db.execSQL("alter table " + Attachment.TABLE_NAME
1172                            + " add column " + AttachmentColumns.FLAGS + " integer" + ";");
1173                } catch (SQLException e) {
1174                    // Shouldn't be needed unless we're debugging and interrupt the process
1175                    Log.w(TAG, "Exception upgrading EmailProvider.db from 10 to 11 " + e);
1176                }
1177                oldVersion = 11;
1178            }
1179            if (oldVersion == 11) {
1180                // Attachment: add content_bytes
1181                try {
1182                    db.execSQL("alter table " + Attachment.TABLE_NAME
1183                            + " add column " + AttachmentColumns.CONTENT_BYTES + " blob" + ";");
1184                } catch (SQLException e) {
1185                    // Shouldn't be needed unless we're debugging and interrupt the process
1186                    Log.w(TAG, "Exception upgrading EmailProvider.db from 11 to 12 " + e);
1187                }
1188                oldVersion = 12;
1189            }
1190            if (oldVersion == 12) {
1191                try {
1192                    db.execSQL("alter table " + Mailbox.TABLE_NAME
1193                            + " add column " + Mailbox.MESSAGE_COUNT
1194                                    +" integer not null default 0" + ";");
1195                    recalculateMessageCount(db);
1196                } catch (SQLException e) {
1197                    // Shouldn't be needed unless we're debugging and interrupt the process
1198                    Log.w(TAG, "Exception upgrading EmailProvider.db from 12 to 13 " + e);
1199                }
1200                oldVersion = 13;
1201            }
1202            if (oldVersion == 13) {
1203                try {
1204                    db.execSQL("alter table " + Message.TABLE_NAME
1205                            + " add column " + Message.SNIPPET
1206                                    +" text" + ";");
1207                } catch (SQLException e) {
1208                    // Shouldn't be needed unless we're debugging and interrupt the process
1209                    Log.w(TAG, "Exception upgrading EmailProvider.db from 13 to 14 " + e);
1210                }
1211                oldVersion = 14;
1212            }
1213            if (oldVersion == 14) {
1214                try {
1215                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1216                            + " add column " + Message.SNIPPET +" text" + ";");
1217                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1218                            + " add column " + Message.SNIPPET +" text" + ";");
1219                } catch (SQLException e) {
1220                    // Shouldn't be needed unless we're debugging and interrupt the process
1221                    Log.w(TAG, "Exception upgrading EmailProvider.db from 14 to 15 " + e);
1222                }
1223                oldVersion = 15;
1224            }
1225            if (oldVersion == 15) {
1226                try {
1227                    db.execSQL("alter table " + Attachment.TABLE_NAME
1228                            + " add column " + Attachment.ACCOUNT_KEY +" integer" + ";");
1229                    // Update all existing attachments to add the accountKey data
1230                    db.execSQL("update " + Attachment.TABLE_NAME + " set " +
1231                            Attachment.ACCOUNT_KEY + "= (SELECT " + Message.TABLE_NAME + "." +
1232                            Message.ACCOUNT_KEY + " from " + Message.TABLE_NAME + " where " +
1233                            Message.TABLE_NAME + "." + Message.RECORD_ID + " = " +
1234                            Attachment.TABLE_NAME + "." + Attachment.MESSAGE_KEY + ")");
1235                } catch (SQLException e) {
1236                    // Shouldn't be needed unless we're debugging and interrupt the process
1237                    Log.w(TAG, "Exception upgrading EmailProvider.db from 15 to 16 " + e);
1238                }
1239                oldVersion = 16;
1240            }
1241            if (oldVersion == 16) {
1242                try {
1243                    db.execSQL("alter table " + Mailbox.TABLE_NAME
1244                            + " add column " + Mailbox.PARENT_KEY + " integer;");
1245                } catch (SQLException e) {
1246                    // Shouldn't be needed unless we're debugging and interrupt the process
1247                    Log.w(TAG, "Exception upgrading EmailProvider.db from 16 to 17 " + e);
1248                }
1249                oldVersion = 17;
1250            }
1251            if (oldVersion == 17) {
1252                upgradeFromVersion17ToVersion18(db);
1253                oldVersion = 18;
1254            }
1255            if (oldVersion == 18) {
1256                try {
1257                    db.execSQL("alter table " + Account.TABLE_NAME
1258                            + " add column " + Account.POLICY_KEY + " integer;");
1259                    db.execSQL("drop trigger account_delete;");
1260                    db.execSQL(TRIGGER_ACCOUNT_DELETE);
1261                    createPolicyTable(db);
1262                    convertPolicyFlagsToPolicyTable(db);
1263                } catch (SQLException e) {
1264                    // Shouldn't be needed unless we're debugging and interrupt the process
1265                    Log.w(TAG, "Exception upgrading EmailProvider.db from 18 to 19 " + e);
1266                }
1267                oldVersion = 19;
1268            }
1269            if (oldVersion == 19) {
1270                try {
1271                    db.execSQL("alter table " + Policy.TABLE_NAME
1272                            + " add column " + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING +
1273                            " integer;");
1274                    db.execSQL("alter table " + Policy.TABLE_NAME
1275                            + " add column " + PolicyColumns.DONT_ALLOW_CAMERA + " integer;");
1276                    db.execSQL("alter table " + Policy.TABLE_NAME
1277                            + " add column " + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer;");
1278                    db.execSQL("alter table " + Policy.TABLE_NAME
1279                            + " add column " + PolicyColumns.DONT_ALLOW_HTML + " integer;");
1280                    db.execSQL("alter table " + Policy.TABLE_NAME
1281                            + " add column " + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer;");
1282                    db.execSQL("alter table " + Policy.TABLE_NAME
1283                            + " add column " + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE +
1284                            " integer;");
1285                    db.execSQL("alter table " + Policy.TABLE_NAME
1286                            + " add column " + PolicyColumns.MAX_HTML_TRUNCATION_SIZE +
1287                            " integer;");
1288                    db.execSQL("alter table " + Policy.TABLE_NAME
1289                            + " add column " + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer;");
1290                    db.execSQL("alter table " + Policy.TABLE_NAME
1291                            + " add column " + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer;");
1292                    db.execSQL("alter table " + Policy.TABLE_NAME
1293                            + " add column " + PolicyColumns.PASSWORD_RECOVERY_ENABLED +
1294                            " integer;");
1295                } catch (SQLException e) {
1296                    // Shouldn't be needed unless we're debugging and interrupt the process
1297                    Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " + e);
1298                }
1299                oldVersion = 20;
1300            }
1301            if (oldVersion == 20) {
1302                upgradeFromVersion20ToVersion21(db);
1303                oldVersion = 21;
1304            }
1305            if (oldVersion == 21) {
1306                upgradeFromVersion21ToVersion22(db, mContext);
1307                oldVersion = 22;
1308            }
1309            if (oldVersion == 22) {
1310                upgradeFromVersion22ToVersion23(db);
1311                oldVersion = 23;
1312            }
1313            if (oldVersion == 23) {
1314                upgradeFromVersion23ToVersion24(db);
1315                oldVersion = 24;
1316            }
1317            if (oldVersion == 24) {
1318                upgradeFromVersion24ToVersion25(db);
1319                oldVersion = 25;
1320            }
1321            if (oldVersion == 25) {
1322                upgradeFromVersion25ToVersion26(db);
1323                oldVersion = 26;
1324            }
1325            if (oldVersion == 26) {
1326                try {
1327                    db.execSQL("alter table " + Message.TABLE_NAME
1328                            + " add column " + Message.PROTOCOL_SEARCH_INFO + " text;");
1329                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1330                            + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
1331                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1332                            + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
1333                } catch (SQLException e) {
1334                    // Shouldn't be needed unless we're debugging and interrupt the process
1335                    Log.w(TAG, "Exception upgrading EmailProvider.db from 26 to 27 " + e);
1336                }
1337                oldVersion = 27;
1338            }
1339            if (oldVersion == 27) {
1340                try {
1341                    db.execSQL("alter table " + Account.TABLE_NAME
1342                            + " add column " + Account.NOTIFIED_MESSAGE_ID + " integer;");
1343                    db.execSQL("alter table " + Account.TABLE_NAME
1344                            + " add column " + Account.NOTIFIED_MESSAGE_COUNT + " integer;");
1345                } catch (SQLException e) {
1346                    // Shouldn't be needed unless we're debugging and interrupt the process
1347                    Log.w(TAG, "Exception upgrading EmailProvider.db from 27 to 28 " + e);
1348                }
1349                oldVersion = 28;
1350            }
1351            if (oldVersion == 28) {
1352                try {
1353                    db.execSQL("alter table " + Policy.TABLE_NAME
1354                            + " add column " + Policy.PROTOCOL_POLICIES_ENFORCED + " text;");
1355                    db.execSQL("alter table " + Policy.TABLE_NAME
1356                            + " add column " + Policy.PROTOCOL_POLICIES_UNSUPPORTED + " text;");
1357                } catch (SQLException e) {
1358                    // Shouldn't be needed unless we're debugging and interrupt the process
1359                    Log.w(TAG, "Exception upgrading EmailProvider.db from 28 to 29 " + e);
1360                }
1361                oldVersion = 29;
1362            }
1363        }
1364
1365        @Override
1366        public void onOpen(SQLiteDatabase db) {
1367        }
1368    }
1369
1370    @Override
1371    public int delete(Uri uri, String selection, String[] selectionArgs) {
1372        final int match = findMatch(uri, "delete");
1373        Context context = getContext();
1374        // Pick the correct database for this operation
1375        // If we're in a transaction already (which would happen during applyBatch), then the
1376        // body database is already attached to the email database and any attempt to use the
1377        // body database directly will result in a SQLiteException (the database is locked)
1378        SQLiteDatabase db = getDatabase(context);
1379        int table = match >> BASE_SHIFT;
1380        String id = "0";
1381        boolean messageDeletion = false;
1382        ContentResolver resolver = context.getContentResolver();
1383
1384        ContentCache cache = mContentCaches[table];
1385        String tableName = TABLE_NAMES[table];
1386        int result = -1;
1387
1388        try {
1389            switch (match) {
1390                // These are cases in which one or more Messages might get deleted, either by
1391                // cascade or explicitly
1392                case MAILBOX_ID:
1393                case MAILBOX:
1394                case ACCOUNT_ID:
1395                case ACCOUNT:
1396                case MESSAGE:
1397                case SYNCED_MESSAGE_ID:
1398                case MESSAGE_ID:
1399                    // Handle lost Body records here, since this cannot be done in a trigger
1400                    // The process is:
1401                    //  1) Begin a transaction, ensuring that both databases are affected atomically
1402                    //  2) Do the requested deletion, with cascading deletions handled in triggers
1403                    //  3) End the transaction, committing all changes atomically
1404                    //
1405                    // Bodies are auto-deleted here;  Attachments are auto-deleted via trigger
1406                    messageDeletion = true;
1407                    db.beginTransaction();
1408                    break;
1409            }
1410            switch (match) {
1411                case BODY_ID:
1412                case DELETED_MESSAGE_ID:
1413                case SYNCED_MESSAGE_ID:
1414                case MESSAGE_ID:
1415                case UPDATED_MESSAGE_ID:
1416                case ATTACHMENT_ID:
1417                case MAILBOX_ID:
1418                case ACCOUNT_ID:
1419                case HOSTAUTH_ID:
1420                case POLICY_ID:
1421                case QUICK_RESPONSE_ID:
1422                    id = uri.getPathSegments().get(1);
1423                    if (match == SYNCED_MESSAGE_ID) {
1424                        // For synced messages, first copy the old message to the deleted table and
1425                        // delete it from the updated table (in case it was updated first)
1426                        // Note that this is all within a transaction, for atomicity
1427                        db.execSQL(DELETED_MESSAGE_INSERT + id);
1428                        db.execSQL(UPDATED_MESSAGE_DELETE + id);
1429                    }
1430                    if (cache != null) {
1431                        cache.lock(id);
1432                    }
1433                    try {
1434                        result = db.delete(tableName, whereWithId(id, selection), selectionArgs);
1435                        if (cache != null) {
1436                            switch(match) {
1437                                case ACCOUNT_ID:
1438                                    // Account deletion will clear all of the caches, as HostAuth's,
1439                                    // Mailboxes, and Messages will be deleted in the process
1440                                    mCacheMailbox.invalidate("Delete", uri, selection);
1441                                    mCacheHostAuth.invalidate("Delete", uri, selection);
1442                                    mCachePolicy.invalidate("Delete", uri, selection);
1443                                    //$FALL-THROUGH$
1444                                case MAILBOX_ID:
1445                                    // Mailbox deletion will clear the Message cache
1446                                    mCacheMessage.invalidate("Delete", uri, selection);
1447                                    //$FALL-THROUGH$
1448                                case SYNCED_MESSAGE_ID:
1449                                case MESSAGE_ID:
1450                                case HOSTAUTH_ID:
1451                                case POLICY_ID:
1452                                    cache.invalidate("Delete", uri, selection);
1453                                    // Make sure all data is properly cached
1454                                    if (match != MESSAGE_ID) {
1455                                        preCacheData();
1456                                    }
1457                                    break;
1458                            }
1459                        }
1460                    } finally {
1461                        if (cache != null) {
1462                            cache.unlock(id);
1463                        }
1464                    }
1465                    break;
1466                case ATTACHMENTS_MESSAGE_ID:
1467                    // All attachments for the given message
1468                    id = uri.getPathSegments().get(2);
1469                    result = db.delete(tableName,
1470                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection), selectionArgs);
1471                    break;
1472
1473                case BODY:
1474                case MESSAGE:
1475                case DELETED_MESSAGE:
1476                case UPDATED_MESSAGE:
1477                case ATTACHMENT:
1478                case MAILBOX:
1479                case ACCOUNT:
1480                case HOSTAUTH:
1481                case POLICY:
1482                    switch(match) {
1483                        // See the comments above for deletion of ACCOUNT_ID, etc
1484                        case ACCOUNT:
1485                            mCacheMailbox.invalidate("Delete", uri, selection);
1486                            mCacheHostAuth.invalidate("Delete", uri, selection);
1487                            mCachePolicy.invalidate("Delete", uri, selection);
1488                            //$FALL-THROUGH$
1489                        case MAILBOX:
1490                            mCacheMessage.invalidate("Delete", uri, selection);
1491                            //$FALL-THROUGH$
1492                        case MESSAGE:
1493                        case HOSTAUTH:
1494                        case POLICY:
1495                            cache.invalidate("Delete", uri, selection);
1496                            break;
1497                    }
1498                    result = db.delete(tableName, selection, selectionArgs);
1499                    switch(match) {
1500                        case ACCOUNT:
1501                        case MAILBOX:
1502                        case HOSTAUTH:
1503                        case POLICY:
1504                            // Make sure all data is properly cached
1505                            preCacheData();
1506                            break;
1507                    }
1508                    break;
1509
1510                default:
1511                    throw new IllegalArgumentException("Unknown URI " + uri);
1512            }
1513            if (messageDeletion) {
1514                if (match == MESSAGE_ID) {
1515                    // Delete the Body record associated with the deleted message
1516                    db.execSQL(DELETE_BODY + id);
1517                } else {
1518                    // Delete any orphaned Body records
1519                    db.execSQL(DELETE_ORPHAN_BODIES);
1520                }
1521                db.setTransactionSuccessful();
1522            }
1523        } catch (SQLiteException e) {
1524            checkDatabases();
1525            throw e;
1526        } finally {
1527            if (messageDeletion) {
1528                db.endTransaction();
1529            }
1530        }
1531
1532        // Notify all notifier cursors
1533        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_DELETE, id);
1534
1535        // Notify all email content cursors
1536        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1537        return result;
1538    }
1539
1540    @Override
1541    // Use the email- prefix because message, mailbox, and account are so generic (e.g. SMS, IM)
1542    public String getType(Uri uri) {
1543        int match = findMatch(uri, "getType");
1544        switch (match) {
1545            case BODY_ID:
1546                return "vnd.android.cursor.item/email-body";
1547            case BODY:
1548                return "vnd.android.cursor.dir/email-body";
1549            case UPDATED_MESSAGE_ID:
1550            case MESSAGE_ID:
1551                // NOTE: According to the framework folks, we're supposed to invent mime types as
1552                // a way of passing information to drag & drop recipients.
1553                // If there's a mailboxId parameter in the url, we respond with a mime type that
1554                // has -n appended, where n is the mailboxId of the message.  The drag & drop code
1555                // uses this information to know not to allow dragging the item to its own mailbox
1556                String mimeType = EMAIL_MESSAGE_MIME_TYPE;
1557                String mailboxId = uri.getQueryParameter(MESSAGE_URI_PARAMETER_MAILBOX_ID);
1558                if (mailboxId != null) {
1559                    mimeType += "-" + mailboxId;
1560                }
1561                return mimeType;
1562            case UPDATED_MESSAGE:
1563            case MESSAGE:
1564                return "vnd.android.cursor.dir/email-message";
1565            case MAILBOX:
1566                return "vnd.android.cursor.dir/email-mailbox";
1567            case MAILBOX_ID:
1568                return "vnd.android.cursor.item/email-mailbox";
1569            case ACCOUNT:
1570                return "vnd.android.cursor.dir/email-account";
1571            case ACCOUNT_ID:
1572                return "vnd.android.cursor.item/email-account";
1573            case ATTACHMENTS_MESSAGE_ID:
1574            case ATTACHMENT:
1575                return "vnd.android.cursor.dir/email-attachment";
1576            case ATTACHMENT_ID:
1577                return EMAIL_ATTACHMENT_MIME_TYPE;
1578            case HOSTAUTH:
1579                return "vnd.android.cursor.dir/email-hostauth";
1580            case HOSTAUTH_ID:
1581                return "vnd.android.cursor.item/email-hostauth";
1582            default:
1583                throw new IllegalArgumentException("Unknown URI " + uri);
1584        }
1585    }
1586
1587    @Override
1588    public Uri insert(Uri uri, ContentValues values) {
1589        int match = findMatch(uri, "insert");
1590        Context context = getContext();
1591        ContentResolver resolver = context.getContentResolver();
1592
1593        // See the comment at delete(), above
1594        SQLiteDatabase db = getDatabase(context);
1595        int table = match >> BASE_SHIFT;
1596        String id = "0";
1597        long longId;
1598
1599        // We do NOT allow setting of unreadCount/messageCount via the provider
1600        // These columns are maintained via triggers
1601        if (match == MAILBOX_ID || match == MAILBOX) {
1602            values.put(MailboxColumns.UNREAD_COUNT, 0);
1603            values.put(MailboxColumns.MESSAGE_COUNT, 0);
1604        }
1605
1606        Uri resultUri = null;
1607
1608        try {
1609            switch (match) {
1610                // NOTE: It is NOT legal for production code to insert directly into UPDATED_MESSAGE
1611                // or DELETED_MESSAGE; see the comment below for details
1612                case UPDATED_MESSAGE:
1613                case DELETED_MESSAGE:
1614                case MESSAGE:
1615                case BODY:
1616                case ATTACHMENT:
1617                case MAILBOX:
1618                case ACCOUNT:
1619                case HOSTAUTH:
1620                case POLICY:
1621                case QUICK_RESPONSE:
1622                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1623                    resultUri = ContentUris.withAppendedId(uri, longId);
1624                    switch(match) {
1625                        case MAILBOX:
1626                            if (values.containsKey(MailboxColumns.TYPE)) {
1627                                // Only cache special mailbox types
1628                                int type = values.getAsInteger(MailboxColumns.TYPE);
1629                                if (type != Mailbox.TYPE_INBOX && type != Mailbox.TYPE_OUTBOX &&
1630                                        type != Mailbox.TYPE_DRAFTS && type != Mailbox.TYPE_SENT &&
1631                                        type != Mailbox.TYPE_TRASH && type != Mailbox.TYPE_SEARCH) {
1632                                    break;
1633                                }
1634                            }
1635                            //$FALL-THROUGH$
1636                        case ACCOUNT:
1637                        case HOSTAUTH:
1638                        case POLICY:
1639                            // Cache new account, host auth, policy, and some mailbox rows
1640                            Cursor c = query(resultUri, CACHE_PROJECTIONS[table], null, null, null);
1641                            if (c != null) {
1642                                if (match == MAILBOX) {
1643                                    addToMailboxTypeMap(c);
1644                                } else if (match == ACCOUNT) {
1645                                    getOrCreateAccountMailboxTypeMap(longId);
1646                                }
1647                                c.close();
1648                            }
1649                            break;
1650                    }
1651                    // Clients shouldn't normally be adding rows to these tables, as they are
1652                    // maintained by triggers.  However, we need to be able to do this for unit
1653                    // testing, so we allow the insert and then throw the same exception that we
1654                    // would if this weren't allowed.
1655                    if (match == UPDATED_MESSAGE || match == DELETED_MESSAGE) {
1656                        throw new IllegalArgumentException("Unknown URL " + uri);
1657                    }
1658                    if (match == ATTACHMENT) {
1659                        int flags = 0;
1660                        if (values.containsKey(Attachment.FLAGS)) {
1661                            flags = values.getAsInteger(Attachment.FLAGS);
1662                        }
1663                        // Report all new attachments to the download service
1664                        mAttachmentService.attachmentChanged(getContext(), longId, flags);
1665                    }
1666                    break;
1667                case MAILBOX_ID:
1668                    // This implies adding a message to a mailbox
1669                    // Hmm, a problem here is that we can't link the account as well, so it must be
1670                    // already in the values...
1671                    longId = Long.parseLong(uri.getPathSegments().get(1));
1672                    values.put(MessageColumns.MAILBOX_KEY, longId);
1673                    return insert(Message.CONTENT_URI, values); // Recurse
1674                case MESSAGE_ID:
1675                    // This implies adding an attachment to a message.
1676                    id = uri.getPathSegments().get(1);
1677                    longId = Long.parseLong(id);
1678                    values.put(AttachmentColumns.MESSAGE_KEY, longId);
1679                    return insert(Attachment.CONTENT_URI, values); // Recurse
1680                case ACCOUNT_ID:
1681                    // This implies adding a mailbox to an account.
1682                    longId = Long.parseLong(uri.getPathSegments().get(1));
1683                    values.put(MailboxColumns.ACCOUNT_KEY, longId);
1684                    return insert(Mailbox.CONTENT_URI, values); // Recurse
1685                case ATTACHMENTS_MESSAGE_ID:
1686                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1687                    resultUri = ContentUris.withAppendedId(Attachment.CONTENT_URI, longId);
1688                    break;
1689                default:
1690                    throw new IllegalArgumentException("Unknown URL " + uri);
1691            }
1692        } catch (SQLiteException e) {
1693            checkDatabases();
1694            throw e;
1695        }
1696
1697        // Notify all notifier cursors
1698        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_INSERT, id);
1699
1700        // Notify all existing cursors.
1701        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1702        return resultUri;
1703    }
1704
1705    @Override
1706    public boolean onCreate() {
1707        checkDatabases();
1708        return false;
1709    }
1710
1711    /**
1712     * The idea here is that the two databases (EmailProvider.db and EmailProviderBody.db must
1713     * always be in sync (i.e. there are two database or NO databases).  This code will delete
1714     * any "orphan" database, so that both will be created together.  Note that an "orphan" database
1715     * will exist after either of the individual databases is deleted due to data corruption.
1716     */
1717    public void checkDatabases() {
1718        // Uncache the databases
1719        if (mDatabase != null) {
1720            mDatabase = null;
1721        }
1722        if (mBodyDatabase != null) {
1723            mBodyDatabase = null;
1724        }
1725        // Look for orphans, and delete as necessary; these must always be in sync
1726        File databaseFile = getContext().getDatabasePath(DATABASE_NAME);
1727        File bodyFile = getContext().getDatabasePath(BODY_DATABASE_NAME);
1728
1729        // TODO Make sure attachments are deleted
1730        if (databaseFile.exists() && !bodyFile.exists()) {
1731            Log.w(TAG, "Deleting orphaned EmailProvider database...");
1732            databaseFile.delete();
1733        } else if (bodyFile.exists() && !databaseFile.exists()) {
1734            Log.w(TAG, "Deleting orphaned EmailProviderBody database...");
1735            bodyFile.delete();
1736        }
1737    }
1738
1739    @Override
1740    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
1741            String sortOrder) {
1742        long time = 0L;
1743        if (Email.DEBUG) {
1744            time = System.nanoTime();
1745        }
1746        Cursor c = null;
1747        int match;
1748        try {
1749            match = findMatch(uri, "query");
1750        } catch (IllegalArgumentException e) {
1751            String uriString = uri.toString();
1752            // If we were passed an illegal uri, see if it ends in /-1
1753            // if so, and if substituting 0 for -1 results in a valid uri, return an empty cursor
1754            if (uriString != null && uriString.endsWith("/-1")) {
1755                uri = Uri.parse(uriString.substring(0, uriString.length() - 2) + "0");
1756                match = findMatch(uri, "query");
1757                switch (match) {
1758                    case BODY_ID:
1759                    case MESSAGE_ID:
1760                    case DELETED_MESSAGE_ID:
1761                    case UPDATED_MESSAGE_ID:
1762                    case ATTACHMENT_ID:
1763                    case MAILBOX_ID:
1764                    case ACCOUNT_ID:
1765                    case HOSTAUTH_ID:
1766                    case POLICY_ID:
1767                        return new MatrixCursor(projection, 0);
1768                }
1769            }
1770            throw e;
1771        }
1772        Context context = getContext();
1773        // See the comment at delete(), above
1774        SQLiteDatabase db = getDatabase(context);
1775        int table = match >> BASE_SHIFT;
1776        String limit = uri.getQueryParameter(EmailContent.PARAMETER_LIMIT);
1777        String id;
1778
1779        // Find the cache for this query's table (if any)
1780        ContentCache cache = null;
1781        String tableName = TABLE_NAMES[table];
1782        // We can only use the cache if there's no selection
1783        if (selection == null) {
1784            cache = mContentCaches[table];
1785        }
1786        if (cache == null) {
1787            ContentCache.notCacheable(uri, selection);
1788        }
1789
1790        try {
1791            switch (match) {
1792                case ACCOUNT_DEFAULT_ID:
1793                    // Start with a snapshot of the cache
1794                    Map<String, Cursor> accountCache = mCacheAccount.getSnapshot();
1795                    long accountId = Account.NO_ACCOUNT;
1796                    // Find the account with "isDefault" set, or the lowest account ID otherwise.
1797                    // Note that the snapshot from the cached isn't guaranteed to be sorted in any
1798                    // way.
1799                    Collection<Cursor> accounts = accountCache.values();
1800                    for (Cursor accountCursor: accounts) {
1801                        // For now, at least, we can have zero count cursors (e.g. if someone looks
1802                        // up a non-existent id); we need to skip these
1803                        if (accountCursor.moveToFirst()) {
1804                            boolean isDefault =
1805                                accountCursor.getInt(Account.CONTENT_IS_DEFAULT_COLUMN) == 1;
1806                            long iterId = accountCursor.getLong(Account.CONTENT_ID_COLUMN);
1807                            // We'll remember this one if it's the default or the first one we see
1808                            if (isDefault) {
1809                                accountId = iterId;
1810                                break;
1811                            } else if ((accountId == Account.NO_ACCOUNT) || (iterId < accountId)) {
1812                                accountId = iterId;
1813                            }
1814                        }
1815                    }
1816                    // Return a cursor with an id projection
1817                    MatrixCursor mc = new MatrixCursor(EmailContent.ID_PROJECTION);
1818                    mc.addRow(new Object[] {accountId});
1819                    c = mc;
1820                    break;
1821                case MAILBOX_ID_FROM_ACCOUNT_AND_TYPE:
1822                    // Get accountId and type and find the mailbox in our map
1823                    List<String> pathSegments = uri.getPathSegments();
1824                    accountId = Long.parseLong(pathSegments.get(1));
1825                    int type = Integer.parseInt(pathSegments.get(2));
1826                    long mailboxId = getMailboxIdFromMailboxTypeMap(accountId, type);
1827                    // Return a cursor with an id projection
1828                    mc = new MatrixCursor(EmailContent.ID_PROJECTION);
1829                    mc.addRow(new Object[] {mailboxId});
1830                    c = mc;
1831                    break;
1832                case BODY:
1833                case MESSAGE:
1834                case UPDATED_MESSAGE:
1835                case DELETED_MESSAGE:
1836                case ATTACHMENT:
1837                case MAILBOX:
1838                case ACCOUNT:
1839                case HOSTAUTH:
1840                case POLICY:
1841                case QUICK_RESPONSE:
1842                    // Special-case "count of accounts"; it's common and we always know it
1843                    if (match == ACCOUNT && Arrays.equals(projection, EmailContent.COUNT_COLUMNS) &&
1844                            selection == null && limit.equals("1")) {
1845                        int accountCount = mMailboxTypeMap.size();
1846                        // In the rare case there are MAX_CACHED_ACCOUNTS or more, we can't do this
1847                        if (accountCount < MAX_CACHED_ACCOUNTS) {
1848                            mc = new MatrixCursor(projection, 1);
1849                            mc.addRow(new Object[] {accountCount});
1850                            c = mc;
1851                            break;
1852                        }
1853                    }
1854                    c = db.query(tableName, projection,
1855                            selection, selectionArgs, null, null, sortOrder, limit);
1856                    break;
1857                case BODY_ID:
1858                case MESSAGE_ID:
1859                case DELETED_MESSAGE_ID:
1860                case UPDATED_MESSAGE_ID:
1861                case ATTACHMENT_ID:
1862                case MAILBOX_ID:
1863                case ACCOUNT_ID:
1864                case HOSTAUTH_ID:
1865                case POLICY_ID:
1866                case QUICK_RESPONSE_ID:
1867                    id = uri.getPathSegments().get(1);
1868                    if (cache != null) {
1869                        c = cache.getCachedCursor(id, projection);
1870                    }
1871                    if (c == null) {
1872                        CacheToken token = null;
1873                        if (cache != null) {
1874                            token = cache.getCacheToken(id);
1875                        }
1876                        c = db.query(tableName, projection, whereWithId(id, selection),
1877                                selectionArgs, null, null, sortOrder, limit);
1878                        if (cache != null) {
1879                            c = cache.putCursor(c, id, projection, token);
1880                        }
1881                    }
1882                    break;
1883                case ATTACHMENTS_MESSAGE_ID:
1884                    // All attachments for the given message
1885                    id = uri.getPathSegments().get(2);
1886                    c = db.query(Attachment.TABLE_NAME, projection,
1887                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection),
1888                            selectionArgs, null, null, sortOrder, limit);
1889                    break;
1890                case QUICK_RESPONSE_ACCOUNT_ID:
1891                    // All quick responses for the given account
1892                    id = uri.getPathSegments().get(2);
1893                    c = db.query(QuickResponse.TABLE_NAME, projection,
1894                            whereWith(QuickResponse.ACCOUNT_KEY + "=" + id, selection),
1895                            selectionArgs, null, null, sortOrder);
1896                    break;
1897                default:
1898                    throw new IllegalArgumentException("Unknown URI " + uri);
1899            }
1900        } catch (SQLiteException e) {
1901            checkDatabases();
1902            throw e;
1903        } catch (RuntimeException e) {
1904            checkDatabases();
1905            e.printStackTrace();
1906            throw e;
1907        } finally {
1908            if (cache != null && c != null && Email.DEBUG) {
1909                cache.recordQueryTime(c, System.nanoTime() - time);
1910            }
1911            if (c == null) {
1912                // This should never happen, but let's be sure to log it...
1913                Log.e(TAG, "Query returning null for uri: " + uri + ", selection: " + selection);
1914            }
1915        }
1916
1917        if ((c != null) && !isTemporary()) {
1918            c.setNotificationUri(getContext().getContentResolver(), uri);
1919        }
1920        return c;
1921    }
1922
1923    private String whereWithId(String id, String selection) {
1924        StringBuilder sb = new StringBuilder(256);
1925        sb.append("_id=");
1926        sb.append(id);
1927        if (selection != null) {
1928            sb.append(" AND (");
1929            sb.append(selection);
1930            sb.append(')');
1931        }
1932        return sb.toString();
1933    }
1934
1935    /**
1936     * Combine a locally-generated selection with a user-provided selection
1937     *
1938     * This introduces risk that the local selection might insert incorrect chars
1939     * into the SQL, so use caution.
1940     *
1941     * @param where locally-generated selection, must not be null
1942     * @param selection user-provided selection, may be null
1943     * @return a single selection string
1944     */
1945    private String whereWith(String where, String selection) {
1946        if (selection == null) {
1947            return where;
1948        }
1949        StringBuilder sb = new StringBuilder(where);
1950        sb.append(" AND (");
1951        sb.append(selection);
1952        sb.append(')');
1953
1954        return sb.toString();
1955    }
1956
1957    /**
1958     * Restore a HostAuth from a database, given its unique id
1959     * @param db the database
1960     * @param id the unique id (_id) of the row
1961     * @return a fully populated HostAuth or null if the row does not exist
1962     */
1963    private static HostAuth restoreHostAuth(SQLiteDatabase db, long id) {
1964        Cursor c = db.query(HostAuth.TABLE_NAME, HostAuth.CONTENT_PROJECTION,
1965                HostAuth.RECORD_ID + "=?", new String[] {Long.toString(id)}, null, null, null);
1966        try {
1967            if (c.moveToFirst()) {
1968                HostAuth hostAuth = new HostAuth();
1969                hostAuth.restore(c);
1970                return hostAuth;
1971            }
1972            return null;
1973        } finally {
1974            c.close();
1975        }
1976    }
1977
1978    /**
1979     * Copy the Account and HostAuth tables from one database to another
1980     * @param fromDatabase the source database
1981     * @param toDatabase the destination database
1982     * @return the number of accounts copied, or -1 if an error occurred
1983     */
1984    private static int copyAccountTables(SQLiteDatabase fromDatabase, SQLiteDatabase toDatabase) {
1985        if (fromDatabase == null || toDatabase == null) return -1;
1986        int copyCount = 0;
1987        try {
1988            // Lock both databases; for the "from" database, we don't want anyone changing it from
1989            // under us; for the "to" database, we want to make the operation atomic
1990            fromDatabase.beginTransaction();
1991            toDatabase.beginTransaction();
1992            // Delete anything hanging around here
1993            toDatabase.delete(Account.TABLE_NAME, null, null);
1994            toDatabase.delete(HostAuth.TABLE_NAME, null, null);
1995            // Get our account cursor
1996            Cursor c = fromDatabase.query(Account.TABLE_NAME, Account.CONTENT_PROJECTION,
1997                    null, null, null, null, null);
1998            boolean noErrors = true;
1999            try {
2000                // Loop through accounts, copying them and associated host auth's
2001                while (c.moveToNext()) {
2002                    Account account = new Account();
2003                    account.restore(c);
2004
2005                    // Clear security sync key and sync key, as these were specific to the state of
2006                    // the account, and we've reset that...
2007                    // Clear policy key so that we can re-establish policies from the server
2008                    // TODO This is pretty EAS specific, but there's a lot of that around
2009                    account.mSecuritySyncKey = null;
2010                    account.mSyncKey = null;
2011                    account.mPolicyKey = 0;
2012
2013                    // Copy host auth's and update foreign keys
2014                    HostAuth hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeyRecv);
2015                    // The account might have gone away, though very unlikely
2016                    if (hostAuth == null) continue;
2017                    account.mHostAuthKeyRecv = toDatabase.insert(HostAuth.TABLE_NAME, null,
2018                            hostAuth.toContentValues());
2019                    // EAS accounts have no send HostAuth
2020                    if (account.mHostAuthKeySend > 0) {
2021                        hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeySend);
2022                        // Belt and suspenders; I can't imagine that this is possible, since we
2023                        // checked the validity of the account above, and the database is now locked
2024                        if (hostAuth == null) continue;
2025                        account.mHostAuthKeySend = toDatabase.insert(HostAuth.TABLE_NAME, null,
2026                                hostAuth.toContentValues());
2027                    }
2028                    // Now, create the account in the "to" database
2029                    toDatabase.insert(Account.TABLE_NAME, null, account.toContentValues());
2030                    copyCount++;
2031                }
2032            } catch (SQLiteException e) {
2033                noErrors = false;
2034                copyCount = -1;
2035            } finally {
2036                fromDatabase.endTransaction();
2037                if (noErrors) {
2038                    // Say it's ok to commit
2039                    toDatabase.setTransactionSuccessful();
2040                }
2041                toDatabase.endTransaction();
2042                c.close();
2043            }
2044        } catch (SQLiteException e) {
2045            copyCount = -1;
2046        }
2047        return copyCount;
2048    }
2049
2050    private static SQLiteDatabase getBackupDatabase(Context context) {
2051        DatabaseHelper helper = new DatabaseHelper(context, BACKUP_DATABASE_NAME);
2052        return helper.getWritableDatabase();
2053    }
2054
2055    /**
2056     * Backup account data, returning the number of accounts backed up
2057     */
2058    private static int backupAccounts(Context context, SQLiteDatabase mainDatabase) {
2059        if (Email.DEBUG) {
2060            Log.d(TAG, "backupAccounts...");
2061        }
2062        SQLiteDatabase backupDatabase = getBackupDatabase(context);
2063        try {
2064            int numBackedUp = copyAccountTables(mainDatabase, backupDatabase);
2065            if (numBackedUp < 0) {
2066                Log.e(TAG, "Account backup failed!");
2067            } else if (Email.DEBUG) {
2068                Log.d(TAG, "Backed up " + numBackedUp + " accounts...");
2069            }
2070            return numBackedUp;
2071        } finally {
2072            if (backupDatabase != null) {
2073                backupDatabase.close();
2074            }
2075        }
2076    }
2077
2078    /**
2079     * Restore account data, returning the number of accounts restored
2080     */
2081    private static int restoreAccounts(Context context, SQLiteDatabase mainDatabase) {
2082        if (Email.DEBUG) {
2083            Log.d(TAG, "restoreAccounts...");
2084        }
2085        SQLiteDatabase backupDatabase = getBackupDatabase(context);
2086        try {
2087            int numRecovered = copyAccountTables(backupDatabase, mainDatabase);
2088            if (numRecovered > 0) {
2089                Log.e(TAG, "Recovered " + numRecovered + " accounts!");
2090            } else if (numRecovered < 0) {
2091                Log.e(TAG, "Account recovery failed?");
2092            } else if (Email.DEBUG) {
2093                Log.d(TAG, "No accounts to restore...");
2094            }
2095            return numRecovered;
2096        } finally {
2097            if (backupDatabase != null) {
2098                backupDatabase.close();
2099            }
2100        }
2101    }
2102
2103    @Override
2104    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
2105        // Handle this special case the fastest possible way
2106        if (uri == INTEGRITY_CHECK_URI) {
2107            checkDatabases();
2108            return 0;
2109        } else if (uri == ACCOUNT_BACKUP_URI) {
2110            return backupAccounts(getContext(), getDatabase(getContext()));
2111        }
2112
2113        // Notify all existing cursors, except for ACCOUNT_RESET_NEW_COUNT(_ID)
2114        Uri notificationUri = EmailContent.CONTENT_URI;
2115
2116        int match = findMatch(uri, "update");
2117        Context context = getContext();
2118        ContentResolver resolver = context.getContentResolver();
2119        // See the comment at delete(), above
2120        SQLiteDatabase db = getDatabase(context);
2121        int table = match >> BASE_SHIFT;
2122        int result;
2123
2124        // We do NOT allow setting of unreadCount/messageCount via the provider
2125        // These columns are maintained via triggers
2126        if (match == MAILBOX_ID || match == MAILBOX) {
2127            values.remove(MailboxColumns.UNREAD_COUNT);
2128            values.remove(MailboxColumns.MESSAGE_COUNT);
2129        }
2130
2131        ContentCache cache = mContentCaches[table];
2132        String tableName = TABLE_NAMES[table];
2133        String id = "0";
2134
2135        try {
2136outer:
2137            switch (match) {
2138                case MAILBOX_ID_ADD_TO_FIELD:
2139                case ACCOUNT_ID_ADD_TO_FIELD:
2140                    id = uri.getPathSegments().get(1);
2141                    String field = values.getAsString(EmailContent.FIELD_COLUMN_NAME);
2142                    Long add = values.getAsLong(EmailContent.ADD_COLUMN_NAME);
2143                    if (field == null || add == null) {
2144                        throw new IllegalArgumentException("No field/add specified " + uri);
2145                    }
2146                    ContentValues actualValues = new ContentValues();
2147                    if (cache != null) {
2148                        cache.lock(id);
2149                    }
2150                    try {
2151                        db.beginTransaction();
2152                        try {
2153                            Cursor c = db.query(tableName,
2154                                    new String[] {EmailContent.RECORD_ID, field},
2155                                    whereWithId(id, selection),
2156                                    selectionArgs, null, null, null);
2157                            try {
2158                                result = 0;
2159                                String[] bind = new String[1];
2160                                if (c.moveToNext()) {
2161                                    bind[0] = c.getString(0); // _id
2162                                    long value = c.getLong(1) + add;
2163                                    actualValues.put(field, value);
2164                                    result = db.update(tableName, actualValues, ID_EQUALS, bind);
2165                                }
2166                                db.setTransactionSuccessful();
2167                            } finally {
2168                                c.close();
2169                            }
2170                        } finally {
2171                            db.endTransaction();
2172                        }
2173                    } finally {
2174                        if (cache != null) {
2175                            cache.unlock(id, actualValues);
2176                        }
2177                    }
2178                    break;
2179                case SYNCED_MESSAGE_ID:
2180                case UPDATED_MESSAGE_ID:
2181                case MESSAGE_ID:
2182                case BODY_ID:
2183                case ATTACHMENT_ID:
2184                case MAILBOX_ID:
2185                case ACCOUNT_ID:
2186                case HOSTAUTH_ID:
2187                case QUICK_RESPONSE_ID:
2188                case POLICY_ID:
2189                    id = uri.getPathSegments().get(1);
2190                    if (cache != null) {
2191                        cache.lock(id);
2192                    }
2193                    try {
2194                        if (match == SYNCED_MESSAGE_ID) {
2195                            // For synced messages, first copy the old message to the updated table
2196                            // Note the insert or ignore semantics, guaranteeing that only the first
2197                            // update will be reflected in the updated message table; therefore this
2198                            // row will always have the "original" data
2199                            db.execSQL(UPDATED_MESSAGE_INSERT + id);
2200                        } else if (match == MESSAGE_ID) {
2201                            db.execSQL(UPDATED_MESSAGE_DELETE + id);
2202                        }
2203                        result = db.update(tableName, values, whereWithId(id, selection),
2204                                selectionArgs);
2205                    } catch (SQLiteException e) {
2206                        // Null out values (so they aren't cached) and re-throw
2207                        values = null;
2208                        throw e;
2209                    } finally {
2210                        if (cache != null) {
2211                            cache.unlock(id, values);
2212                        }
2213                    }
2214                    if (match == ATTACHMENT_ID) {
2215                        if (values.containsKey(Attachment.FLAGS)) {
2216                            int flags = values.getAsInteger(Attachment.FLAGS);
2217                            mAttachmentService.attachmentChanged(getContext(),
2218                                    Integer.parseInt(id), flags);
2219                        }
2220                    }
2221                    break;
2222                case BODY:
2223                case MESSAGE:
2224                case UPDATED_MESSAGE:
2225                case ATTACHMENT:
2226                case MAILBOX:
2227                case ACCOUNT:
2228                case HOSTAUTH:
2229                case POLICY:
2230                    switch(match) {
2231                        // To avoid invalidating the cache on updates, we execute them one at a
2232                        // time using the XXX_ID uri; these are all executed atomically
2233                        case ACCOUNT:
2234                        case MAILBOX:
2235                        case HOSTAUTH:
2236                        case POLICY:
2237                            Cursor c = db.query(tableName, EmailContent.ID_PROJECTION,
2238                                    selection, selectionArgs, null, null, null);
2239                            db.beginTransaction();
2240                            result = 0;
2241                            try {
2242                                while (c.moveToNext()) {
2243                                    update(ContentUris.withAppendedId(
2244                                                uri, c.getLong(EmailContent.ID_PROJECTION_COLUMN)),
2245                                            values, null, null);
2246                                    result++;
2247                                }
2248                                db.setTransactionSuccessful();
2249                            } finally {
2250                                db.endTransaction();
2251                                c.close();
2252                            }
2253                            break outer;
2254                        // Any cached table other than those above should be invalidated here
2255                        case MESSAGE:
2256                            // If we're doing some generic update, the whole cache needs to be
2257                            // invalidated.  This case should be quite rare
2258                            cache.invalidate("Update", uri, selection);
2259                            //$FALL-THROUGH$
2260                        default:
2261                            result = db.update(tableName, values, selection, selectionArgs);
2262                            break outer;
2263                    }
2264                case ACCOUNT_RESET_NEW_COUNT_ID:
2265                    id = uri.getPathSegments().get(1);
2266                    if (cache != null) {
2267                        cache.lock(id);
2268                    }
2269                    ContentValues newMessageCount = CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
2270                    if (values != null) {
2271                        Long set = values.getAsLong(EmailContent.SET_COLUMN_NAME);
2272                        if (set != null) {
2273                            newMessageCount = new ContentValues();
2274                            newMessageCount.put(Account.NEW_MESSAGE_COUNT, set);
2275                        }
2276                    }
2277                    try {
2278                        result = db.update(tableName, newMessageCount,
2279                                whereWithId(id, selection), selectionArgs);
2280                    } finally {
2281                        if (cache != null) {
2282                            cache.unlock(id, values);
2283                        }
2284                    }
2285                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
2286                    break;
2287                case ACCOUNT_RESET_NEW_COUNT:
2288                    result = db.update(tableName, CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT,
2289                            selection, selectionArgs);
2290                    // Affects all accounts.  Just invalidate all account cache.
2291                    cache.invalidate("Reset all new counts", null, null);
2292                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
2293                    break;
2294                default:
2295                    throw new IllegalArgumentException("Unknown URI " + uri);
2296            }
2297        } catch (SQLiteException e) {
2298            checkDatabases();
2299            throw e;
2300        }
2301
2302        // Notify all notifier cursors
2303        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_UPDATE, id);
2304
2305        resolver.notifyChange(notificationUri, null);
2306        return result;
2307    }
2308
2309    /**
2310     * Returns the base notification URI for the given content type.
2311     *
2312     * @param match The type of content that was modified.
2313     */
2314    private Uri getBaseNotificationUri(int match) {
2315        Uri baseUri = null;
2316        switch (match) {
2317            case MESSAGE:
2318            case MESSAGE_ID:
2319            case SYNCED_MESSAGE_ID:
2320                baseUri = Message.NOTIFIER_URI;
2321                break;
2322            case ACCOUNT:
2323            case ACCOUNT_ID:
2324                baseUri = Account.NOTIFIER_URI;
2325                break;
2326        }
2327        return baseUri;
2328    }
2329
2330    /**
2331     * Sends a change notification to any cursors observers of the given base URI. The final
2332     * notification URI is dynamically built to contain the specified information. It will be
2333     * of the format <<baseURI>>/<<op>>/<<id>>; where <<op>> and <<id>> are optional depending
2334     * upon the given values.
2335     * NOTE: If <<op>> is specified, notifications for <<baseURI>>/<<id>> will NOT be invoked.
2336     * If this is necessary, it can be added. However, due to the implementation of
2337     * {@link ContentObserver}, observers of <<baseURI>> will receive multiple notifications.
2338     *
2339     * @param baseUri The base URI to send notifications to. Must be able to take appended IDs.
2340     * @param op Optional operation to be appended to the URI.
2341     * @param id If a positive value, the ID to append to the base URI. Otherwise, no ID will be
2342     *           appended to the base URI.
2343     */
2344    private void sendNotifierChange(Uri baseUri, String op, String id) {
2345        if (baseUri == null) return;
2346
2347        final ContentResolver resolver = getContext().getContentResolver();
2348
2349        // Append the operation, if specified
2350        if (op != null) {
2351            baseUri = baseUri.buildUpon().appendEncodedPath(op).build();
2352        }
2353
2354        long longId = 0L;
2355        try {
2356            longId = Long.valueOf(id);
2357        } catch (NumberFormatException ignore) {}
2358        if (longId > 0) {
2359            resolver.notifyChange(ContentUris.withAppendedId(baseUri, longId), null);
2360        } else {
2361            resolver.notifyChange(baseUri, null);
2362        }
2363    }
2364
2365    @Override
2366    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
2367            throws OperationApplicationException {
2368        Context context = getContext();
2369        SQLiteDatabase db = getDatabase(context);
2370        db.beginTransaction();
2371        try {
2372            ContentProviderResult[] results = super.applyBatch(operations);
2373            db.setTransactionSuccessful();
2374            return results;
2375        } finally {
2376            db.endTransaction();
2377        }
2378    }
2379
2380    /** Counts the number of messages in each mailbox, and updates the message count column. */
2381    @VisibleForTesting
2382    static void recalculateMessageCount(SQLiteDatabase db) {
2383        db.execSQL("update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
2384                "= (select count(*) from " + Message.TABLE_NAME +
2385                " where " + Message.MAILBOX_KEY + " = " +
2386                    Mailbox.TABLE_NAME + "." + EmailContent.RECORD_ID + ")");
2387    }
2388
2389    @VisibleForTesting
2390    @SuppressWarnings("deprecation")
2391    static void convertPolicyFlagsToPolicyTable(SQLiteDatabase db) {
2392        Cursor c = db.query(Account.TABLE_NAME,
2393                new String[] {EmailContent.RECORD_ID /*0*/, AccountColumns.SECURITY_FLAGS /*1*/},
2394                AccountColumns.SECURITY_FLAGS + ">0", null, null, null, null);
2395        ContentValues cv = new ContentValues();
2396        String[] args = new String[1];
2397        while (c.moveToNext()) {
2398            long securityFlags = c.getLong(1 /*SECURITY_FLAGS*/);
2399            Policy policy = LegacyPolicySet.flagsToPolicy(securityFlags);
2400            long policyId = db.insert(Policy.TABLE_NAME, null, policy.toContentValues());
2401            cv.put(AccountColumns.POLICY_KEY, policyId);
2402            cv.putNull(AccountColumns.SECURITY_FLAGS);
2403            args[0] = Long.toString(c.getLong(0 /*RECORD_ID*/));
2404            db.update(Account.TABLE_NAME, cv, EmailContent.RECORD_ID + "=?", args);
2405        }
2406    }
2407
2408    /** Upgrades the database from v17 to v18 */
2409    @VisibleForTesting
2410    static void upgradeFromVersion17ToVersion18(SQLiteDatabase db) {
2411        // Copy the displayName column to the serverId column. In v18 of the database,
2412        // we use the serverId for IMAP/POP3 mailboxes instead of overloading the
2413        // display name.
2414        //
2415        // For posterity; this is the command we're executing:
2416        //sqlite> UPDATE mailbox SET serverid=displayname WHERE mailbox._id in (
2417        //        ...> SELECT mailbox._id FROM mailbox,account,hostauth WHERE
2418        //        ...> (mailbox.parentkey isnull OR mailbox.parentkey=0) AND
2419        //        ...> mailbox.accountkey=account._id AND
2420        //        ...> account.hostauthkeyrecv=hostauth._id AND
2421        //        ...> (hostauth.protocol='imap' OR hostauth.protocol='pop3'));
2422        try {
2423            db.execSQL(
2424                    "UPDATE " + Mailbox.TABLE_NAME + " SET "
2425                    + MailboxColumns.SERVER_ID + "=" + MailboxColumns.DISPLAY_NAME
2426                    + " WHERE "
2427                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " IN ( SELECT "
2428                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " FROM "
2429                    + Mailbox.TABLE_NAME + "," + Account.TABLE_NAME + ","
2430                    + HostAuth.TABLE_NAME + " WHERE "
2431                    + "("
2432                    + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + " isnull OR "
2433                    + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + "=0 "
2434                    + ") AND "
2435                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ACCOUNT_KEY + "="
2436                    + Account.TABLE_NAME + "." + AccountColumns.ID + " AND "
2437                    + Account.TABLE_NAME + "." + AccountColumns.HOST_AUTH_KEY_RECV + "="
2438                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.ID + " AND ( "
2439                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='imap' OR "
2440                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='pop3' ) )");
2441        } catch (SQLException e) {
2442            // Shouldn't be needed unless we're debugging and interrupt the process
2443            Log.w(TAG, "Exception upgrading EmailProvider.db from 17 to 18 " + e);
2444        }
2445        ContentCache.invalidateAllCaches();
2446    }
2447
2448    /** Upgrades the database from v20 to v21 */
2449    private static void upgradeFromVersion20ToVersion21(SQLiteDatabase db) {
2450        try {
2451            db.execSQL("alter table " + Mailbox.TABLE_NAME
2452                    + " add column " + Mailbox.LAST_SEEN_MESSAGE_KEY + " integer;");
2453        } catch (SQLException e) {
2454            // Shouldn't be needed unless we're debugging and interrupt the process
2455            Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
2456        }
2457    }
2458
2459    /**
2460     * Upgrade the database from v21 to v22
2461     * This entails creating AccountManager accounts for all pop3 and imap accounts
2462     */
2463
2464    private static final String[] V21_ACCOUNT_PROJECTION =
2465        new String[] {AccountColumns.HOST_AUTH_KEY_RECV, AccountColumns.EMAIL_ADDRESS};
2466    private static final int V21_ACCOUNT_RECV = 0;
2467    private static final int V21_ACCOUNT_EMAIL = 1;
2468
2469    private static final String[] V21_HOSTAUTH_PROJECTION =
2470        new String[] {HostAuthColumns.PROTOCOL, HostAuthColumns.PASSWORD};
2471    private static final int V21_HOSTAUTH_PROTOCOL = 0;
2472    private static final int V21_HOSTAUTH_PASSWORD = 1;
2473
2474    static private void createAccountManagerAccount(Context context, String login,
2475            String password) {
2476        AccountManager accountManager = AccountManager.get(context);
2477        android.accounts.Account amAccount =
2478            new android.accounts.Account(login, AccountManagerTypes.TYPE_POP_IMAP);
2479        accountManager.addAccountExplicitly(amAccount, password, null);
2480        ContentResolver.setIsSyncable(amAccount, EmailContent.AUTHORITY, 1);
2481        ContentResolver.setSyncAutomatically(amAccount, EmailContent.AUTHORITY, true);
2482        ContentResolver.setIsSyncable(amAccount, ContactsContract.AUTHORITY, 0);
2483        ContentResolver.setIsSyncable(amAccount, CalendarProviderStub.AUTHORITY, 0);
2484    }
2485
2486    @VisibleForTesting
2487    static void upgradeFromVersion21ToVersion22(SQLiteDatabase db, Context accountManagerContext) {
2488        try {
2489            // Loop through accounts, looking for pop/imap accounts
2490            Cursor accountCursor = db.query(Account.TABLE_NAME, V21_ACCOUNT_PROJECTION, null,
2491                    null, null, null, null);
2492            try {
2493                String[] hostAuthArgs = new String[1];
2494                while (accountCursor.moveToNext()) {
2495                    hostAuthArgs[0] = accountCursor.getString(V21_ACCOUNT_RECV);
2496                    // Get the "receive" HostAuth for this account
2497                    Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
2498                            V21_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
2499                            null, null, null);
2500                    try {
2501                        if (hostAuthCursor.moveToFirst()) {
2502                            String protocol = hostAuthCursor.getString(V21_HOSTAUTH_PROTOCOL);
2503                            // If this is a pop3 or imap account, create the account manager account
2504                            if (HostAuth.SCHEME_IMAP.equals(protocol) ||
2505                                    HostAuth.SCHEME_POP3.equals(protocol)) {
2506                                if (Email.DEBUG) {
2507                                    Log.d(TAG, "Create AccountManager account for " + protocol +
2508                                            "account: " +
2509                                            accountCursor.getString(V21_ACCOUNT_EMAIL));
2510                                }
2511                                createAccountManagerAccount(accountManagerContext,
2512                                        accountCursor.getString(V21_ACCOUNT_EMAIL),
2513                                        hostAuthCursor.getString(V21_HOSTAUTH_PASSWORD));
2514                            }
2515                        }
2516                    } finally {
2517                        hostAuthCursor.close();
2518                    }
2519                }
2520            } finally {
2521                accountCursor.close();
2522            }
2523        } catch (SQLException e) {
2524            // Shouldn't be needed unless we're debugging and interrupt the process
2525            Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
2526        }
2527    }
2528
2529    /** Upgrades the database from v22 to v23 */
2530    private static void upgradeFromVersion22ToVersion23(SQLiteDatabase db) {
2531        try {
2532            db.execSQL("alter table " + Mailbox.TABLE_NAME
2533                    + " add column " + Mailbox.LAST_TOUCHED_TIME + " integer default 0;");
2534        } catch (SQLException e) {
2535            // Shouldn't be needed unless we're debugging and interrupt the process
2536            Log.w(TAG, "Exception upgrading EmailProvider.db from 22 to 23 " + e);
2537        }
2538    }
2539
2540    /** Adds in a column for information about a client certificate to use. */
2541    private static void upgradeFromVersion23ToVersion24(SQLiteDatabase db) {
2542        try {
2543            db.execSQL("alter table " + HostAuth.TABLE_NAME
2544                    + " add column " + HostAuth.CLIENT_CERT_ALIAS + " text;");
2545        } catch (SQLException e) {
2546            // Shouldn't be needed unless we're debugging and interrupt the process
2547            Log.w(TAG, "Exception upgrading EmailProvider.db from 23 to 24 " + e);
2548        }
2549    }
2550
2551    /** Upgrades the database from v24 to v25 by creating table for quick responses */
2552    private static void upgradeFromVersion24ToVersion25(SQLiteDatabase db) {
2553        try {
2554            createQuickResponseTable(db);
2555        } catch (SQLException e) {
2556            // Shouldn't be needed unless we're debugging and interrupt the process
2557            Log.w(TAG, "Exception upgrading EmailProvider.db from 24 to 25 " + e);
2558        }
2559    }
2560
2561    private static final String[] V25_ACCOUNT_PROJECTION =
2562        new String[] {AccountColumns.ID, AccountColumns.FLAGS, AccountColumns.HOST_AUTH_KEY_RECV};
2563    private static final int V25_ACCOUNT_ID = 0;
2564    private static final int V25_ACCOUNT_FLAGS = 1;
2565    private static final int V25_ACCOUNT_RECV = 2;
2566
2567    private static final String[] V25_HOSTAUTH_PROJECTION = new String[] {HostAuthColumns.PROTOCOL};
2568    private static final int V25_HOSTAUTH_PROTOCOL = 0;
2569
2570    /** Upgrades the database from v25 to v26 by adding FLAG_SUPPORTS_SEARCH to IMAP accounts */
2571    private static void upgradeFromVersion25ToVersion26(SQLiteDatabase db) {
2572        try {
2573            // Loop through accounts, looking for imap accounts
2574            Cursor accountCursor = db.query(Account.TABLE_NAME, V25_ACCOUNT_PROJECTION, null,
2575                    null, null, null, null);
2576            ContentValues cv = new ContentValues();
2577            try {
2578                String[] hostAuthArgs = new String[1];
2579                while (accountCursor.moveToNext()) {
2580                    hostAuthArgs[0] = accountCursor.getString(V25_ACCOUNT_RECV);
2581                    // Get the "receive" HostAuth for this account
2582                    Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
2583                            V25_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
2584                            null, null, null);
2585                    try {
2586                        if (hostAuthCursor.moveToFirst()) {
2587                            String protocol = hostAuthCursor.getString(V25_HOSTAUTH_PROTOCOL);
2588                            // If this is an imap account, add the search flag
2589                            if (HostAuth.SCHEME_IMAP.equals(protocol)) {
2590                                String id = accountCursor.getString(V25_ACCOUNT_ID);
2591                                int flags = accountCursor.getInt(V25_ACCOUNT_FLAGS);
2592                                cv.put(AccountColumns.FLAGS, flags | Account.FLAGS_SUPPORTS_SEARCH);
2593                                db.update(Account.TABLE_NAME, cv, Account.RECORD_ID + "=?",
2594                                        new String[] {id});
2595                            }
2596                        }
2597                    } finally {
2598                        hostAuthCursor.close();
2599                    }
2600                }
2601            } finally {
2602                accountCursor.close();
2603            }
2604        } catch (SQLException e) {
2605            // Shouldn't be needed unless we're debugging and interrupt the process
2606            Log.w(TAG, "Exception upgrading EmailProvider.db from 25 to 26 " + e);
2607        }
2608    }
2609
2610        /**
2611     * For testing purposes, check whether a given row is cached
2612     * @param baseUri the base uri of the EmailContent
2613     * @param id the row id of the EmailContent
2614     * @return whether or not the row is currently cached
2615     */
2616    @VisibleForTesting
2617    protected boolean isCached(Uri baseUri, long id) {
2618        int match = findMatch(baseUri, "isCached");
2619        int table = match >> BASE_SHIFT;
2620        ContentCache cache = mContentCaches[table];
2621        if (cache == null) return false;
2622        Cursor cc = cache.get(Long.toString(id));
2623        return (cc != null);
2624    }
2625
2626    public static interface AttachmentService {
2627        /**
2628         * Notify the service that an attachment has changed.
2629         */
2630        void attachmentChanged(Context context, long id, int flags);
2631    }
2632
2633    private final AttachmentService DEFAULT_ATTACHMENT_SERVICE = new AttachmentService() {
2634        @Override
2635        public void attachmentChanged(Context context, long id, int flags) {
2636            // The default implementation delegates to the real service.
2637            AttachmentDownloadService.attachmentChanged(context, id, flags);
2638        }
2639    };
2640    private AttachmentService mAttachmentService = DEFAULT_ATTACHMENT_SERVICE;
2641
2642    /**
2643     * Injects a custom attachment service handler. If null is specified, will reset to the
2644     * default service.
2645     */
2646    public void injectAttachmentService(AttachmentService as) {
2647        mAttachmentService = (as == null) ? DEFAULT_ATTACHMENT_SERVICE : as;
2648    }
2649}
2650