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