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