DBHelper.java revision db48fcbe056f5d621e0a64cf1f05aa92db40b97d
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.email.provider;
18
19import android.accounts.AccountManager;
20import android.content.ContentResolver;
21import android.content.ContentValues;
22import android.content.Context;
23import android.database.Cursor;
24import android.database.SQLException;
25import android.database.sqlite.SQLiteDatabase;
26import android.database.sqlite.SQLiteOpenHelper;
27import android.provider.ContactsContract;
28import android.util.Log;
29
30import com.android.email.Email;
31import com.android.emailcommon.AccountManagerTypes;
32import com.android.emailcommon.CalendarProviderStub;
33import com.android.emailcommon.mail.Address;
34import com.android.emailcommon.provider.Account;
35import com.android.emailcommon.provider.EmailContent;
36import com.android.emailcommon.provider.EmailContent.AccountColumns;
37import com.android.emailcommon.provider.EmailContent.Attachment;
38import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
39import com.android.emailcommon.provider.EmailContent.Body;
40import com.android.emailcommon.provider.EmailContent.BodyColumns;
41import com.android.emailcommon.provider.EmailContent.HostAuthColumns;
42import com.android.emailcommon.provider.EmailContent.MailboxColumns;
43import com.android.emailcommon.provider.EmailContent.Message;
44import com.android.emailcommon.provider.EmailContent.MessageColumns;
45import com.android.emailcommon.provider.EmailContent.PolicyColumns;
46import com.android.emailcommon.provider.EmailContent.QuickResponseColumns;
47import com.android.emailcommon.provider.EmailContent.SyncColumns;
48import com.android.emailcommon.provider.HostAuth;
49import com.android.emailcommon.provider.Mailbox;
50import com.android.emailcommon.provider.Policy;
51import com.android.emailcommon.provider.QuickResponse;
52import com.android.emailcommon.service.LegacyPolicySet;
53import com.google.common.annotations.VisibleForTesting;
54
55public final class DBHelper {
56    private static final String TAG = "EmailProvider";
57
58    private static final String WHERE_ID = EmailContent.RECORD_ID + "=?";
59
60    private static final String TRIGGER_MAILBOX_DELETE =
61        "create trigger mailbox_delete before delete on " + Mailbox.TABLE_NAME +
62        " begin" +
63        " delete from " + Message.TABLE_NAME +
64        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
65        "; delete from " + Message.UPDATED_TABLE_NAME +
66        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
67        "; delete from " + Message.DELETED_TABLE_NAME +
68        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
69        "; end";
70
71    private static final String TRIGGER_ACCOUNT_DELETE =
72        "create trigger account_delete before delete on " + Account.TABLE_NAME +
73        " begin delete from " + Mailbox.TABLE_NAME +
74        " where " + MailboxColumns.ACCOUNT_KEY + "=old." + EmailContent.RECORD_ID +
75        "; delete from " + HostAuth.TABLE_NAME +
76        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_RECV +
77        "; delete from " + HostAuth.TABLE_NAME +
78        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_SEND +
79        "; delete from " + Policy.TABLE_NAME +
80        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.POLICY_KEY +
81        "; end";
82
83    // Any changes to the database format *must* include update-in-place code.
84    // Original version: 3
85    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
86    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
87    // Version 6: Adding Message.mServerTimeStamp column
88    // Version 7: Replace the mailbox_delete trigger with a version that removes orphaned messages
89    //            from the Message_Deletes and Message_Updates tables
90    // Version 8: Add security flags column to accounts table
91    // Version 9: Add security sync key and signature to accounts table
92    // Version 10: Add meeting info to message table
93    // Version 11: Add content and flags to attachment table
94    // Version 12: Add content_bytes to attachment table. content is deprecated.
95    // Version 13: Add messageCount to Mailbox table.
96    // Version 14: Add snippet to Message table
97    // Version 15: Fix upgrade problem in version 14.
98    // Version 16: Add accountKey to Attachment table
99    // Version 17: Add parentKey to Mailbox table
100    // Version 18: Copy Mailbox.displayName to Mailbox.serverId for all IMAP & POP3 mailboxes.
101    //             Column Mailbox.serverId is used for the server-side pathname of a mailbox.
102    // Version 19: Add Policy table; add policyKey to Account table and trigger to delete an
103    //             Account's policy when the Account is deleted
104    // Version 20: Add new policies to Policy table
105    // Version 21: Add lastSeenMessageKey column to Mailbox table
106    // Version 22: Upgrade path for IMAP/POP accounts to integrate with AccountManager
107    // Version 23: Add column to mailbox table for time of last access
108    // Version 24: Add column to hostauth table for client cert alias
109    // Version 25: Added QuickResponse table
110    // Version 26: Update IMAP accounts to add FLAG_SUPPORTS_SEARCH flag
111    // Version 27: Add protocolSearchInfo to Message table
112    // Version 28: Add notifiedMessageId and notifiedMessageCount to Account
113    // Version 29: Add protocolPoliciesEnforced and protocolPoliciesUnsupported to Policy
114    // Version 30: Use CSV of RFC822 addresses instead of "packed" values
115    // Version 31: Add columns to mailbox for ui status/last result
116    // Version 32: Add columns to mailbox for last notified message key/count; insure not null
117    //             for "notified" columns
118    // Version 33: Add columns to attachment for ui provider columns
119    // Version 34: Add total count to mailbox
120    // Version 35: Set up defaults for lastTouchedCount for drafts and sent
121    // Version 36: mblank intentionally left this space
122    // Version 37: Add flag for settings support in folders
123    // Version 38&39: Add threadTopic to message (for future support)
124
125    // Versions 100+ are in Email2
126
127    public static final int DATABASE_VERSION = 39;
128
129    // Any changes to the database format *must* include update-in-place code.
130    // Original version: 2
131    // Version 3: Add "sourceKey" column
132    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
133    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
134    // Version 6: Adding Body.mIntroText column
135    // Version 7/8: Adding quoted text start pos
136
137    // Versions 100+ are in Email2
138
139    public static final int BODY_DATABASE_VERSION = 8;
140
141    /*
142     * Internal helper method for index creation.
143     * Example:
144     * "create index message_" + MessageColumns.FLAG_READ
145     * + " on " + Message.TABLE_NAME + " (" + MessageColumns.FLAG_READ + ");"
146     */
147    /* package */
148    static String createIndex(String tableName, String columnName) {
149        return "create index " + tableName.toLowerCase() + '_' + columnName
150            + " on " + tableName + " (" + columnName + ");";
151    }
152
153    static void createMessageTable(SQLiteDatabase db) {
154        String messageColumns = MessageColumns.DISPLAY_NAME + " text, "
155            + MessageColumns.TIMESTAMP + " integer, "
156            + MessageColumns.SUBJECT + " text, "
157            + MessageColumns.FLAG_READ + " integer, "
158            + MessageColumns.FLAG_LOADED + " integer, "
159            + MessageColumns.FLAG_FAVORITE + " integer, "
160            + MessageColumns.FLAG_ATTACHMENT + " integer, "
161            + MessageColumns.FLAGS + " integer, "
162            + MessageColumns.CLIENT_ID + " integer, "
163            + MessageColumns.MESSAGE_ID + " text, "
164            + MessageColumns.MAILBOX_KEY + " integer, "
165            + MessageColumns.ACCOUNT_KEY + " integer, "
166            + MessageColumns.FROM_LIST + " text, "
167            + MessageColumns.TO_LIST + " text, "
168            + MessageColumns.CC_LIST + " text, "
169            + MessageColumns.BCC_LIST + " text, "
170            + MessageColumns.REPLY_TO_LIST + " text, "
171            + MessageColumns.MEETING_INFO + " text, "
172            + MessageColumns.SNIPPET + " text, "
173            + MessageColumns.PROTOCOL_SEARCH_INFO + " text, "
174            + MessageColumns.THREAD_TOPIC + " text"
175            + ");";
176
177        // This String and the following String MUST have the same columns, except for the type
178        // of those columns!
179        String createString = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
180            + SyncColumns.SERVER_ID + " text, "
181            + SyncColumns.SERVER_TIMESTAMP + " integer, "
182            + messageColumns;
183
184        // For the updated and deleted tables, the id is assigned, but we do want to keep track
185        // of the ORDER of updates using an autoincrement primary key.  We use the DATA column
186        // at this point; it has no other function
187        String altCreateString = " (" + EmailContent.RECORD_ID + " integer unique, "
188            + SyncColumns.SERVER_ID + " text, "
189            + SyncColumns.SERVER_TIMESTAMP + " integer, "
190            + messageColumns;
191
192        // The three tables have the same schema
193        db.execSQL("create table " + Message.TABLE_NAME + createString);
194        db.execSQL("create table " + Message.UPDATED_TABLE_NAME + altCreateString);
195        db.execSQL("create table " + Message.DELETED_TABLE_NAME + altCreateString);
196
197        String indexColumns[] = {
198            MessageColumns.TIMESTAMP,
199            MessageColumns.FLAG_READ,
200            MessageColumns.FLAG_LOADED,
201            MessageColumns.MAILBOX_KEY,
202            SyncColumns.SERVER_ID
203        };
204
205        for (String columnName : indexColumns) {
206            db.execSQL(createIndex(Message.TABLE_NAME, columnName));
207        }
208
209        // Deleting a Message deletes all associated Attachments
210        // Deleting the associated Body cannot be done in a trigger, because the Body is stored
211        // in a separate database, and trigger cannot operate on attached databases.
212        db.execSQL("create trigger message_delete before delete on " + Message.TABLE_NAME +
213                " begin delete from " + Attachment.TABLE_NAME +
214                "  where " + AttachmentColumns.MESSAGE_KEY + "=old." + EmailContent.RECORD_ID +
215                "; end");
216
217        // Add triggers to keep unread count accurate per mailbox
218
219        // NOTE: SQLite's before triggers are not safe when recursive triggers are involved.
220        // Use caution when changing them.
221
222        // Insert a message; if flagRead is zero, add to the unread count of the message's mailbox
223        db.execSQL("create trigger unread_message_insert before insert on " + Message.TABLE_NAME +
224                " when NEW." + MessageColumns.FLAG_READ + "=0" +
225                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
226                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
227                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
228                "; end");
229
230        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
231        db.execSQL("create trigger unread_message_delete before delete on " + Message.TABLE_NAME +
232                " when OLD." + MessageColumns.FLAG_READ + "=0" +
233                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
234                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
235                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
236                "; end");
237
238        // Change a message's mailbox
239        db.execSQL("create trigger unread_message_move before update of " +
240                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
241                " when OLD." + MessageColumns.FLAG_READ + "=0" +
242                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
243                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
244                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
245                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
246                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
247                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
248                "; end");
249
250        // Change a message's read state
251        db.execSQL("create trigger unread_message_read before update of " +
252                MessageColumns.FLAG_READ + " on " + Message.TABLE_NAME +
253                " when OLD." + MessageColumns.FLAG_READ + "!=NEW." + MessageColumns.FLAG_READ +
254                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
255                '=' + MailboxColumns.UNREAD_COUNT + "+ case OLD." + MessageColumns.FLAG_READ +
256                " when 0 then -1 else 1 end" +
257                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
258                "; end");
259
260        // Add triggers to update message count per mailbox
261
262        // Insert a message.
263        db.execSQL("create trigger message_count_message_insert after insert on " +
264                Message.TABLE_NAME +
265                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
266                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
267                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
268                "; end");
269
270        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
271        db.execSQL("create trigger message_count_message_delete after delete on " +
272                Message.TABLE_NAME +
273                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
274                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
275                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
276                "; end");
277
278        // Change a message's mailbox
279        db.execSQL("create trigger message_count_message_move after update of " +
280                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
281                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
282                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
283                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
284                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
285                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
286                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
287                "; end");
288    }
289
290    static void resetMessageTable(SQLiteDatabase db, int oldVersion, int newVersion) {
291        try {
292            db.execSQL("drop table " + Message.TABLE_NAME);
293            db.execSQL("drop table " + Message.UPDATED_TABLE_NAME);
294            db.execSQL("drop table " + Message.DELETED_TABLE_NAME);
295        } catch (SQLException e) {
296        }
297        createMessageTable(db);
298    }
299
300    @SuppressWarnings("deprecation")
301    static void createAccountTable(SQLiteDatabase db) {
302        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
303            + AccountColumns.DISPLAY_NAME + " text, "
304            + AccountColumns.EMAIL_ADDRESS + " text, "
305            + AccountColumns.SYNC_KEY + " text, "
306            + AccountColumns.SYNC_LOOKBACK + " integer, "
307            + AccountColumns.SYNC_INTERVAL + " text, "
308            + AccountColumns.HOST_AUTH_KEY_RECV + " integer, "
309            + AccountColumns.HOST_AUTH_KEY_SEND + " integer, "
310            + AccountColumns.FLAGS + " integer, "
311            + AccountColumns.IS_DEFAULT + " integer, "
312            + AccountColumns.COMPATIBILITY_UUID + " text, "
313            + AccountColumns.SENDER_NAME + " text, "
314            + AccountColumns.RINGTONE_URI + " text, "
315            + AccountColumns.PROTOCOL_VERSION + " text, "
316            + AccountColumns.NEW_MESSAGE_COUNT + " integer, "
317            + AccountColumns.SECURITY_FLAGS + " integer, "
318            + AccountColumns.SECURITY_SYNC_KEY + " text, "
319            + AccountColumns.SIGNATURE + " text, "
320            + AccountColumns.POLICY_KEY + " integer"
321            + ");";
322        db.execSQL("create table " + Account.TABLE_NAME + s);
323        // Deleting an account deletes associated Mailboxes and HostAuth's
324        db.execSQL(TRIGGER_ACCOUNT_DELETE);
325    }
326
327    static void resetAccountTable(SQLiteDatabase db, int oldVersion, int newVersion) {
328        try {
329            db.execSQL("drop table " +  Account.TABLE_NAME);
330        } catch (SQLException e) {
331        }
332        createAccountTable(db);
333    }
334
335    static void createPolicyTable(SQLiteDatabase db) {
336        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
337            + PolicyColumns.PASSWORD_MODE + " integer, "
338            + PolicyColumns.PASSWORD_MIN_LENGTH + " integer, "
339            + PolicyColumns.PASSWORD_EXPIRATION_DAYS + " integer, "
340            + PolicyColumns.PASSWORD_HISTORY + " integer, "
341            + PolicyColumns.PASSWORD_COMPLEX_CHARS + " integer, "
342            + PolicyColumns.PASSWORD_MAX_FAILS + " integer, "
343            + PolicyColumns.MAX_SCREEN_LOCK_TIME + " integer, "
344            + PolicyColumns.REQUIRE_REMOTE_WIPE + " integer, "
345            + PolicyColumns.REQUIRE_ENCRYPTION + " integer, "
346            + PolicyColumns.REQUIRE_ENCRYPTION_EXTERNAL + " integer, "
347            + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING + " integer, "
348            + PolicyColumns.DONT_ALLOW_CAMERA + " integer, "
349            + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer, "
350            + PolicyColumns.DONT_ALLOW_HTML + " integer, "
351            + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer, "
352            + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE + " integer, "
353            + PolicyColumns.MAX_HTML_TRUNCATION_SIZE + " integer, "
354            + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer, "
355            + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer, "
356            + PolicyColumns.PASSWORD_RECOVERY_ENABLED + " integer, "
357            + PolicyColumns.PROTOCOL_POLICIES_ENFORCED + " text, "
358            + PolicyColumns.PROTOCOL_POLICIES_UNSUPPORTED + " text"
359            + ");";
360        db.execSQL("create table " + Policy.TABLE_NAME + s);
361    }
362
363    static void createHostAuthTable(SQLiteDatabase db) {
364        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
365            + HostAuthColumns.PROTOCOL + " text, "
366            + HostAuthColumns.ADDRESS + " text, "
367            + HostAuthColumns.PORT + " integer, "
368            + HostAuthColumns.FLAGS + " integer, "
369            + HostAuthColumns.LOGIN + " text, "
370            + HostAuthColumns.PASSWORD + " text, "
371            + HostAuthColumns.DOMAIN + " text, "
372            + HostAuthColumns.ACCOUNT_KEY + " integer,"
373            + HostAuthColumns.CLIENT_CERT_ALIAS + " text"
374            + ");";
375        db.execSQL("create table " + HostAuth.TABLE_NAME + s);
376    }
377
378    static void resetHostAuthTable(SQLiteDatabase db, int oldVersion, int newVersion) {
379        try {
380            db.execSQL("drop table " + HostAuth.TABLE_NAME);
381        } catch (SQLException e) {
382        }
383        createHostAuthTable(db);
384    }
385
386    static void createMailboxTable(SQLiteDatabase db) {
387        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
388            + MailboxColumns.DISPLAY_NAME + " text, "
389            + MailboxColumns.SERVER_ID + " text, "
390            + MailboxColumns.PARENT_SERVER_ID + " text, "
391            + MailboxColumns.PARENT_KEY + " integer, "
392            + MailboxColumns.ACCOUNT_KEY + " integer, "
393            + MailboxColumns.TYPE + " integer, "
394            + MailboxColumns.DELIMITER + " integer, "
395            + MailboxColumns.SYNC_KEY + " text, "
396            + MailboxColumns.SYNC_LOOKBACK + " integer, "
397            + MailboxColumns.SYNC_INTERVAL + " integer, "
398            + MailboxColumns.SYNC_TIME + " integer, "
399            + MailboxColumns.UNREAD_COUNT + " integer, "
400            + MailboxColumns.FLAG_VISIBLE + " integer, "
401            + MailboxColumns.FLAGS + " integer, "
402            + MailboxColumns.VISIBLE_LIMIT + " integer, "
403            + MailboxColumns.SYNC_STATUS + " text, "
404            + MailboxColumns.MESSAGE_COUNT + " integer not null default 0, "
405            + MailboxColumns.LAST_TOUCHED_TIME + " integer default 0, "
406            + MailboxColumns.UI_SYNC_STATUS + " integer default 0, "
407            + MailboxColumns.UI_LAST_SYNC_RESULT + " integer default 0, "
408            + MailboxColumns.LAST_NOTIFIED_MESSAGE_KEY + " integer not null default 0, "
409            + MailboxColumns.LAST_NOTIFIED_MESSAGE_COUNT + " integer not null default 0, "
410            + MailboxColumns.TOTAL_COUNT + " integer"
411            + ");";
412        db.execSQL("create table " + Mailbox.TABLE_NAME + s);
413        db.execSQL("create index mailbox_" + MailboxColumns.SERVER_ID
414                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.SERVER_ID + ")");
415        db.execSQL("create index mailbox_" + MailboxColumns.ACCOUNT_KEY
416                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.ACCOUNT_KEY + ")");
417        // Deleting a Mailbox deletes associated Messages in all three tables
418        db.execSQL(TRIGGER_MAILBOX_DELETE);
419    }
420
421    static void resetMailboxTable(SQLiteDatabase db, int oldVersion, int newVersion) {
422        try {
423            db.execSQL("drop table " + Mailbox.TABLE_NAME);
424        } catch (SQLException e) {
425        }
426        createMailboxTable(db);
427    }
428
429    static void createAttachmentTable(SQLiteDatabase db) {
430        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
431            + AttachmentColumns.FILENAME + " text, "
432            + AttachmentColumns.MIME_TYPE + " text, "
433            + AttachmentColumns.SIZE + " integer, "
434            + AttachmentColumns.CONTENT_ID + " text, "
435            + AttachmentColumns.CONTENT_URI + " text, "
436            + AttachmentColumns.MESSAGE_KEY + " integer, "
437            + AttachmentColumns.LOCATION + " text, "
438            + AttachmentColumns.ENCODING + " text, "
439            + AttachmentColumns.CONTENT + " text, "
440            + AttachmentColumns.FLAGS + " integer, "
441            + AttachmentColumns.CONTENT_BYTES + " blob, "
442            + AttachmentColumns.ACCOUNT_KEY + " integer, "
443            + AttachmentColumns.UI_STATE + " integer, "
444            + AttachmentColumns.UI_DESTINATION + " integer, "
445            + AttachmentColumns.UI_DOWNLOADED_SIZE + " integer"
446            + ");";
447        db.execSQL("create table " + Attachment.TABLE_NAME + s);
448        db.execSQL(createIndex(Attachment.TABLE_NAME, AttachmentColumns.MESSAGE_KEY));
449    }
450
451    static void resetAttachmentTable(SQLiteDatabase db, int oldVersion, int newVersion) {
452        try {
453            db.execSQL("drop table " + Attachment.TABLE_NAME);
454        } catch (SQLException e) {
455        }
456        createAttachmentTable(db);
457    }
458
459    static void createQuickResponseTable(SQLiteDatabase db) {
460        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
461                + QuickResponseColumns.TEXT + " text, "
462                + QuickResponseColumns.ACCOUNT_KEY + " integer"
463                + ");";
464        db.execSQL("create table " + QuickResponse.TABLE_NAME + s);
465    }
466
467    static void createBodyTable(SQLiteDatabase db) {
468        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
469            + BodyColumns.MESSAGE_KEY + " integer, "
470            + BodyColumns.HTML_CONTENT + " text, "
471            + BodyColumns.TEXT_CONTENT + " text, "
472            + BodyColumns.HTML_REPLY + " text, "
473            + BodyColumns.TEXT_REPLY + " text, "
474            + BodyColumns.SOURCE_MESSAGE_KEY + " text, "
475            + BodyColumns.INTRO_TEXT + " text, "
476            + BodyColumns.QUOTED_TEXT_START_POS + " integer"
477            + ");";
478        db.execSQL("create table " + Body.TABLE_NAME + s);
479        db.execSQL(createIndex(Body.TABLE_NAME, BodyColumns.MESSAGE_KEY));
480    }
481
482    static void upgradeBodyTable(SQLiteDatabase db, int oldVersion, int newVersion) {
483        if (oldVersion < 5) {
484            try {
485                db.execSQL("drop table " + Body.TABLE_NAME);
486                createBodyTable(db);
487                oldVersion = 5;
488            } catch (SQLException e) {
489            }
490        }
491        if (oldVersion == 5) {
492            try {
493                db.execSQL("alter table " + Body.TABLE_NAME
494                        + " add " + BodyColumns.INTRO_TEXT + " text");
495            } catch (SQLException e) {
496                // Shouldn't be needed unless we're debugging and interrupt the process
497                Log.w(TAG, "Exception upgrading EmailProviderBody.db from v5 to v6", e);
498            }
499            oldVersion = 6;
500        }
501        if (oldVersion == 6 || oldVersion ==7) {
502            try {
503                db.execSQL("alter table " + Body.TABLE_NAME
504                        + " add " + BodyColumns.QUOTED_TEXT_START_POS + " integer");
505            } catch (SQLException e) {
506                // Shouldn't be needed unless we're debugging and interrupt the process
507                Log.w(TAG, "Exception upgrading EmailProviderBody.db from v6 to v8", e);
508            }
509            oldVersion = 8;
510        }
511    }
512
513    protected static class BodyDatabaseHelper extends SQLiteOpenHelper {
514        BodyDatabaseHelper(Context context, String name) {
515            super(context, name, null, BODY_DATABASE_VERSION);
516        }
517
518        @Override
519        public void onCreate(SQLiteDatabase db) {
520            Log.d(TAG, "Creating EmailProviderBody database");
521            createBodyTable(db);
522        }
523
524        @Override
525        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
526            upgradeBodyTable(db, oldVersion, newVersion);
527        }
528
529        @Override
530        public void onOpen(SQLiteDatabase db) {
531        }
532    }
533
534    /** Counts the number of messages in each mailbox, and updates the message count column. */
535    @VisibleForTesting
536    static void recalculateMessageCount(SQLiteDatabase db) {
537        db.execSQL("update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
538                "= (select count(*) from " + Message.TABLE_NAME +
539                " where " + Message.MAILBOX_KEY + " = " +
540                    Mailbox.TABLE_NAME + "." + EmailContent.RECORD_ID + ")");
541    }
542
543    protected static class DatabaseHelper extends SQLiteOpenHelper {
544        Context mContext;
545
546        DatabaseHelper(Context context, String name) {
547            super(context, name, null, DATABASE_VERSION);
548            mContext = context;
549        }
550
551        @Override
552        public void onCreate(SQLiteDatabase db) {
553            Log.d(TAG, "Creating EmailProvider database");
554            // Create all tables here; each class has its own method
555            createMessageTable(db);
556            createAttachmentTable(db);
557            createMailboxTable(db);
558            createHostAuthTable(db);
559            createAccountTable(db);
560            createPolicyTable(db);
561            createQuickResponseTable(db);
562        }
563
564        @Override
565        @SuppressWarnings("deprecation")
566        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
567            // For versions prior to 5, delete all data
568            // Versions >= 5 require that data be preserved!
569            if (oldVersion < 5) {
570                android.accounts.Account[] accounts = AccountManager.get(mContext)
571                        .getAccountsByType(AccountManagerTypes.TYPE_EXCHANGE);
572                for (android.accounts.Account account: accounts) {
573                    AccountManager.get(mContext).removeAccount(account, null, null);
574                }
575                resetMessageTable(db, oldVersion, newVersion);
576                resetAttachmentTable(db, oldVersion, newVersion);
577                resetMailboxTable(db, oldVersion, newVersion);
578                resetHostAuthTable(db, oldVersion, newVersion);
579                resetAccountTable(db, oldVersion, newVersion);
580                return;
581            }
582            if (oldVersion == 5) {
583                // Message Tables: Add SyncColumns.SERVER_TIMESTAMP
584                try {
585                    db.execSQL("alter table " + Message.TABLE_NAME
586                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
587                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
588                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
589                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
590                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
591                } catch (SQLException e) {
592                    // Shouldn't be needed unless we're debugging and interrupt the process
593                    Log.w(TAG, "Exception upgrading EmailProvider.db from v5 to v6", e);
594                }
595                oldVersion = 6;
596            }
597            if (oldVersion == 6) {
598                // Use the newer mailbox_delete trigger
599                db.execSQL("drop trigger mailbox_delete;");
600                db.execSQL(TRIGGER_MAILBOX_DELETE);
601                oldVersion = 7;
602            }
603            if (oldVersion == 7) {
604                // add the security (provisioning) column
605                try {
606                    db.execSQL("alter table " + Account.TABLE_NAME
607                            + " add column " + AccountColumns.SECURITY_FLAGS + " integer" + ";");
608                } catch (SQLException e) {
609                    // Shouldn't be needed unless we're debugging and interrupt the process
610                    Log.w(TAG, "Exception upgrading EmailProvider.db from 7 to 8 " + e);
611                }
612                oldVersion = 8;
613            }
614            if (oldVersion == 8) {
615                // accounts: add security sync key & user signature columns
616                try {
617                    db.execSQL("alter table " + Account.TABLE_NAME
618                            + " add column " + AccountColumns.SECURITY_SYNC_KEY + " text" + ";");
619                    db.execSQL("alter table " + Account.TABLE_NAME
620                            + " add column " + AccountColumns.SIGNATURE + " text" + ";");
621                } catch (SQLException e) {
622                    // Shouldn't be needed unless we're debugging and interrupt the process
623                    Log.w(TAG, "Exception upgrading EmailProvider.db from 8 to 9 " + e);
624                }
625                oldVersion = 9;
626            }
627            if (oldVersion == 9) {
628                // Message: add meeting info column into Message tables
629                try {
630                    db.execSQL("alter table " + Message.TABLE_NAME
631                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
632                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
633                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
634                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
635                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
636                } catch (SQLException e) {
637                    // Shouldn't be needed unless we're debugging and interrupt the process
638                    Log.w(TAG, "Exception upgrading EmailProvider.db from 9 to 10 " + e);
639                }
640                oldVersion = 10;
641            }
642            if (oldVersion == 10) {
643                // Attachment: add content and flags columns
644                try {
645                    db.execSQL("alter table " + Attachment.TABLE_NAME
646                            + " add column " + AttachmentColumns.CONTENT + " text" + ";");
647                    db.execSQL("alter table " + Attachment.TABLE_NAME
648                            + " add column " + AttachmentColumns.FLAGS + " integer" + ";");
649                } catch (SQLException e) {
650                    // Shouldn't be needed unless we're debugging and interrupt the process
651                    Log.w(TAG, "Exception upgrading EmailProvider.db from 10 to 11 " + e);
652                }
653                oldVersion = 11;
654            }
655            if (oldVersion == 11) {
656                // Attachment: add content_bytes
657                try {
658                    db.execSQL("alter table " + Attachment.TABLE_NAME
659                            + " add column " + AttachmentColumns.CONTENT_BYTES + " blob" + ";");
660                } catch (SQLException e) {
661                    // Shouldn't be needed unless we're debugging and interrupt the process
662                    Log.w(TAG, "Exception upgrading EmailProvider.db from 11 to 12 " + e);
663                }
664                oldVersion = 12;
665            }
666            if (oldVersion == 12) {
667                try {
668                    db.execSQL("alter table " + Mailbox.TABLE_NAME
669                            + " add column " + Mailbox.MESSAGE_COUNT
670                                    +" integer not null default 0" + ";");
671                    recalculateMessageCount(db);
672                } catch (SQLException e) {
673                    // Shouldn't be needed unless we're debugging and interrupt the process
674                    Log.w(TAG, "Exception upgrading EmailProvider.db from 12 to 13 " + e);
675                }
676                oldVersion = 13;
677            }
678            if (oldVersion == 13) {
679                try {
680                    db.execSQL("alter table " + Message.TABLE_NAME
681                            + " add column " + Message.SNIPPET
682                                    +" text" + ";");
683                } catch (SQLException e) {
684                    // Shouldn't be needed unless we're debugging and interrupt the process
685                    Log.w(TAG, "Exception upgrading EmailProvider.db from 13 to 14 " + e);
686                }
687                oldVersion = 14;
688            }
689            if (oldVersion == 14) {
690                try {
691                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
692                            + " add column " + Message.SNIPPET +" text" + ";");
693                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
694                            + " add column " + Message.SNIPPET +" text" + ";");
695                } catch (SQLException e) {
696                    // Shouldn't be needed unless we're debugging and interrupt the process
697                    Log.w(TAG, "Exception upgrading EmailProvider.db from 14 to 15 " + e);
698                }
699                oldVersion = 15;
700            }
701            if (oldVersion == 15) {
702                try {
703                    db.execSQL("alter table " + Attachment.TABLE_NAME
704                            + " add column " + Attachment.ACCOUNT_KEY +" integer" + ";");
705                    // Update all existing attachments to add the accountKey data
706                    db.execSQL("update " + Attachment.TABLE_NAME + " set " +
707                            Attachment.ACCOUNT_KEY + "= (SELECT " + Message.TABLE_NAME + "." +
708                            Message.ACCOUNT_KEY + " from " + Message.TABLE_NAME + " where " +
709                            Message.TABLE_NAME + "." + Message.RECORD_ID + " = " +
710                            Attachment.TABLE_NAME + "." + Attachment.MESSAGE_KEY + ")");
711                } catch (SQLException e) {
712                    // Shouldn't be needed unless we're debugging and interrupt the process
713                    Log.w(TAG, "Exception upgrading EmailProvider.db from 15 to 16 " + e);
714                }
715                oldVersion = 16;
716            }
717            if (oldVersion == 16) {
718                try {
719                    db.execSQL("alter table " + Mailbox.TABLE_NAME
720                            + " add column " + Mailbox.PARENT_KEY + " integer;");
721                } catch (SQLException e) {
722                    // Shouldn't be needed unless we're debugging and interrupt the process
723                    Log.w(TAG, "Exception upgrading EmailProvider.db from 16 to 17 " + e);
724                }
725                oldVersion = 17;
726            }
727            if (oldVersion == 17) {
728                upgradeFromVersion17ToVersion18(db);
729                oldVersion = 18;
730            }
731            if (oldVersion == 18) {
732                try {
733                    db.execSQL("alter table " + Account.TABLE_NAME
734                            + " add column " + Account.POLICY_KEY + " integer;");
735                    db.execSQL("drop trigger account_delete;");
736                    db.execSQL(TRIGGER_ACCOUNT_DELETE);
737                    createPolicyTable(db);
738                    convertPolicyFlagsToPolicyTable(db);
739                } catch (SQLException e) {
740                    // Shouldn't be needed unless we're debugging and interrupt the process
741                    Log.w(TAG, "Exception upgrading EmailProvider.db from 18 to 19 " + e);
742                }
743                oldVersion = 19;
744            }
745            if (oldVersion == 19) {
746                try {
747                    db.execSQL("alter table " + Policy.TABLE_NAME
748                            + " add column " + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING +
749                            " integer;");
750                    db.execSQL("alter table " + Policy.TABLE_NAME
751                            + " add column " + PolicyColumns.DONT_ALLOW_CAMERA + " integer;");
752                    db.execSQL("alter table " + Policy.TABLE_NAME
753                            + " add column " + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer;");
754                    db.execSQL("alter table " + Policy.TABLE_NAME
755                            + " add column " + PolicyColumns.DONT_ALLOW_HTML + " integer;");
756                    db.execSQL("alter table " + Policy.TABLE_NAME
757                            + " add column " + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer;");
758                    db.execSQL("alter table " + Policy.TABLE_NAME
759                            + " add column " + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE +
760                            " integer;");
761                    db.execSQL("alter table " + Policy.TABLE_NAME
762                            + " add column " + PolicyColumns.MAX_HTML_TRUNCATION_SIZE +
763                            " integer;");
764                    db.execSQL("alter table " + Policy.TABLE_NAME
765                            + " add column " + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer;");
766                    db.execSQL("alter table " + Policy.TABLE_NAME
767                            + " add column " + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer;");
768                    db.execSQL("alter table " + Policy.TABLE_NAME
769                            + " add column " + PolicyColumns.PASSWORD_RECOVERY_ENABLED +
770                            " integer;");
771                } catch (SQLException e) {
772                    // Shouldn't be needed unless we're debugging and interrupt the process
773                    Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " + e);
774                }
775                oldVersion = 20;
776            }
777            if (oldVersion == 20) {
778                oldVersion = 21;
779            }
780            if (oldVersion == 21) {
781                upgradeFromVersion21ToVersion22(db, mContext);
782                oldVersion = 22;
783            }
784            if (oldVersion == 22) {
785                upgradeFromVersion22ToVersion23(db);
786                oldVersion = 23;
787            }
788            if (oldVersion == 23) {
789                upgradeFromVersion23ToVersion24(db);
790                oldVersion = 24;
791            }
792            if (oldVersion == 24) {
793                upgradeFromVersion24ToVersion25(db);
794                oldVersion = 25;
795            }
796            if (oldVersion == 25) {
797                upgradeFromVersion25ToVersion26(db);
798                oldVersion = 26;
799            }
800            if (oldVersion == 26) {
801                try {
802                    db.execSQL("alter table " + Message.TABLE_NAME
803                            + " add column " + Message.PROTOCOL_SEARCH_INFO + " text;");
804                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
805                            + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
806                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
807                            + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
808                } catch (SQLException e) {
809                    // Shouldn't be needed unless we're debugging and interrupt the process
810                    Log.w(TAG, "Exception upgrading EmailProvider.db from 26 to 27 " + e);
811                }
812                oldVersion = 27;
813            }
814            if (oldVersion == 27) {
815                oldVersion = 28;
816            }
817            if (oldVersion == 28) {
818                try {
819                    db.execSQL("alter table " + Policy.TABLE_NAME
820                            + " add column " + Policy.PROTOCOL_POLICIES_ENFORCED + " text;");
821                    db.execSQL("alter table " + Policy.TABLE_NAME
822                            + " add column " + Policy.PROTOCOL_POLICIES_UNSUPPORTED + " text;");
823                } catch (SQLException e) {
824                    // Shouldn't be needed unless we're debugging and interrupt the process
825                    Log.w(TAG, "Exception upgrading EmailProvider.db from 28 to 29 " + e);
826                }
827                oldVersion = 29;
828            }
829            if (oldVersion == 29) {
830                upgradeFromVersion29ToVersion30(db);
831                oldVersion = 30;
832            }
833            if (oldVersion == 30) {
834                try {
835                    db.execSQL("alter table " + Mailbox.TABLE_NAME
836                            + " add column " + Mailbox.UI_SYNC_STATUS + " integer;");
837                    db.execSQL("alter table " + Mailbox.TABLE_NAME
838                            + " add column " + Mailbox.UI_LAST_SYNC_RESULT + " integer;");
839                } catch (SQLException e) {
840                    // Shouldn't be needed unless we're debugging and interrupt the process
841                    Log.w(TAG, "Exception upgrading EmailProvider.db from 30 to 31 " + e);
842                }
843                oldVersion = 31;
844            }
845            if (oldVersion == 31) {
846                try {
847                    db.execSQL("alter table " + Mailbox.TABLE_NAME
848                            + " add column " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY + " integer;");
849                    db.execSQL("alter table " + Mailbox.TABLE_NAME
850                            + " add column " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT + " integer;");
851                    db.execSQL("update Mailbox set " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY +
852                            "=0 where " + Mailbox.LAST_NOTIFIED_MESSAGE_KEY + " IS NULL");
853                    db.execSQL("update Mailbox set " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT +
854                            "=0 where " + Mailbox.LAST_NOTIFIED_MESSAGE_COUNT + " IS NULL");
855                } catch (SQLException e) {
856                    // Shouldn't be needed unless we're debugging and interrupt the process
857                    Log.w(TAG, "Exception upgrading EmailProvider.db from 31 to 32 " + e);
858                }
859                oldVersion = 32;
860            }
861            if (oldVersion == 32) {
862                try {
863                    db.execSQL("alter table " + Attachment.TABLE_NAME
864                            + " add column " + Attachment.UI_STATE + " integer;");
865                    db.execSQL("alter table " + Attachment.TABLE_NAME
866                            + " add column " + Attachment.UI_DESTINATION + " integer;");
867                    db.execSQL("alter table " + Attachment.TABLE_NAME
868                            + " add column " + Attachment.UI_DOWNLOADED_SIZE + " integer;");
869                } catch (SQLException e) {
870                    // Shouldn't be needed unless we're debugging and interrupt the process
871                    Log.w(TAG, "Exception upgrading EmailProvider.db from 32 to 33 " + e);
872                }
873                oldVersion = 33;
874            }
875            if (oldVersion == 33) {
876                try {
877                    db.execSQL("alter table " + Mailbox.TABLE_NAME
878                            + " add column " + MailboxColumns.TOTAL_COUNT + " integer;");
879                } catch (SQLException e) {
880                    // Shouldn't be needed unless we're debugging and interrupt the process
881                    Log.w(TAG, "Exception upgrading EmailProvider.db from 33 to 34 " + e);
882                }
883                oldVersion = 34;
884            }
885            if (oldVersion == 34) {
886                oldVersion = 35;
887            }
888            if (oldVersion == 35 || oldVersion == 36) {
889                oldVersion = 37;
890            }
891            if (oldVersion == 37) {
892                try {
893                    db.execSQL("alter table " + Message.TABLE_NAME
894                            + " add column " + MessageColumns.THREAD_TOPIC + " text;");
895                } catch (SQLException e) {
896                    // Shouldn't be needed unless we're debugging and interrupt the process
897                    Log.w(TAG, "Exception upgrading EmailProvider.db from 37 to 38 " + e);
898                }
899                oldVersion = 38;
900            }
901            if (oldVersion == 38) {
902                try {
903                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
904                            + " add column " + MessageColumns.THREAD_TOPIC + " text;");
905                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
906                            + " add column " + MessageColumns.THREAD_TOPIC + " text;");
907                } catch (SQLException e) {
908                    // Shouldn't be needed unless we're debugging and interrupt the process
909                    Log.w(TAG, "Exception upgrading EmailProvider.db from 38 to 39 " + e);
910                }
911                oldVersion = 39;
912            }
913        }
914
915        @Override
916        public void onOpen(SQLiteDatabase db) {
917        }
918    }
919
920    @VisibleForTesting
921    @SuppressWarnings("deprecation")
922    static void convertPolicyFlagsToPolicyTable(SQLiteDatabase db) {
923        Cursor c = db.query(Account.TABLE_NAME,
924                new String[] {EmailContent.RECORD_ID /*0*/, AccountColumns.SECURITY_FLAGS /*1*/},
925                AccountColumns.SECURITY_FLAGS + ">0", null, null, null, null);
926        ContentValues cv = new ContentValues();
927        String[] args = new String[1];
928        while (c.moveToNext()) {
929            long securityFlags = c.getLong(1 /*SECURITY_FLAGS*/);
930            Policy policy = LegacyPolicySet.flagsToPolicy(securityFlags);
931            long policyId = db.insert(Policy.TABLE_NAME, null, policy.toContentValues());
932            cv.put(AccountColumns.POLICY_KEY, policyId);
933            cv.putNull(AccountColumns.SECURITY_FLAGS);
934            args[0] = Long.toString(c.getLong(0 /*RECORD_ID*/));
935            db.update(Account.TABLE_NAME, cv, EmailContent.RECORD_ID + "=?", args);
936        }
937    }
938
939    /** Upgrades the database from v17 to v18 */
940    @VisibleForTesting
941    static void upgradeFromVersion17ToVersion18(SQLiteDatabase db) {
942        // Copy the displayName column to the serverId column. In v18 of the database,
943        // we use the serverId for IMAP/POP3 mailboxes instead of overloading the
944        // display name.
945        //
946        // For posterity; this is the command we're executing:
947        //sqlite> UPDATE mailbox SET serverid=displayname WHERE mailbox._id in (
948        //        ...> SELECT mailbox._id FROM mailbox,account,hostauth WHERE
949        //        ...> (mailbox.parentkey isnull OR mailbox.parentkey=0) AND
950        //        ...> mailbox.accountkey=account._id AND
951        //        ...> account.hostauthkeyrecv=hostauth._id AND
952        //        ...> (hostauth.protocol='imap' OR hostauth.protocol='pop3'));
953        try {
954            db.execSQL(
955                    "UPDATE " + Mailbox.TABLE_NAME + " SET "
956                    + MailboxColumns.SERVER_ID + "=" + MailboxColumns.DISPLAY_NAME
957                    + " WHERE "
958                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " IN ( SELECT "
959                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " FROM "
960                    + Mailbox.TABLE_NAME + "," + Account.TABLE_NAME + ","
961                    + HostAuth.TABLE_NAME + " WHERE "
962                    + "("
963                    + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + " isnull OR "
964                    + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + "=0 "
965                    + ") AND "
966                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ACCOUNT_KEY + "="
967                    + Account.TABLE_NAME + "." + AccountColumns.ID + " AND "
968                    + Account.TABLE_NAME + "." + AccountColumns.HOST_AUTH_KEY_RECV + "="
969                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.ID + " AND ( "
970                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='imap' OR "
971                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='pop3' ) )");
972        } catch (SQLException e) {
973            // Shouldn't be needed unless we're debugging and interrupt the process
974            Log.w(TAG, "Exception upgrading EmailProvider.db from 17 to 18 " + e);
975        }
976        ContentCache.invalidateAllCaches();
977    }
978
979    /**
980     * Upgrade the database from v21 to v22
981     * This entails creating AccountManager accounts for all pop3 and imap accounts
982     */
983
984    private static final String[] V21_ACCOUNT_PROJECTION =
985        new String[] {AccountColumns.HOST_AUTH_KEY_RECV, AccountColumns.EMAIL_ADDRESS};
986    private static final int V21_ACCOUNT_RECV = 0;
987    private static final int V21_ACCOUNT_EMAIL = 1;
988
989    private static final String[] V21_HOSTAUTH_PROJECTION =
990        new String[] {HostAuthColumns.PROTOCOL, HostAuthColumns.PASSWORD};
991    private static final int V21_HOSTAUTH_PROTOCOL = 0;
992    private static final int V21_HOSTAUTH_PASSWORD = 1;
993
994    static private void createAccountManagerAccount(Context context, String login,
995            String password) {
996        AccountManager accountManager = AccountManager.get(context);
997        android.accounts.Account amAccount =
998            new android.accounts.Account(login, AccountManagerTypes.TYPE_POP_IMAP);
999        accountManager.addAccountExplicitly(amAccount, password, null);
1000        ContentResolver.setIsSyncable(amAccount, EmailContent.AUTHORITY, 1);
1001        ContentResolver.setSyncAutomatically(amAccount, EmailContent.AUTHORITY, true);
1002        ContentResolver.setIsSyncable(amAccount, ContactsContract.AUTHORITY, 0);
1003        ContentResolver.setIsSyncable(amAccount, CalendarProviderStub.AUTHORITY, 0);
1004    }
1005
1006    @VisibleForTesting
1007    static void upgradeFromVersion21ToVersion22(SQLiteDatabase db, Context accountManagerContext) {
1008        try {
1009            // Loop through accounts, looking for pop/imap accounts
1010            Cursor accountCursor = db.query(Account.TABLE_NAME, V21_ACCOUNT_PROJECTION, null,
1011                    null, null, null, null);
1012            try {
1013                String[] hostAuthArgs = new String[1];
1014                while (accountCursor.moveToNext()) {
1015                    hostAuthArgs[0] = accountCursor.getString(V21_ACCOUNT_RECV);
1016                    // Get the "receive" HostAuth for this account
1017                    Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
1018                            V21_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
1019                            null, null, null);
1020                    try {
1021                        if (hostAuthCursor.moveToFirst()) {
1022                            String protocol = hostAuthCursor.getString(V21_HOSTAUTH_PROTOCOL);
1023                            // If this is a pop3 or imap account, create the account manager account
1024                            if (HostAuth.SCHEME_IMAP.equals(protocol) ||
1025                                    HostAuth.SCHEME_POP3.equals(protocol)) {
1026                                if (Email.DEBUG) {
1027                                    Log.d(TAG, "Create AccountManager account for " + protocol +
1028                                            "account: " +
1029                                            accountCursor.getString(V21_ACCOUNT_EMAIL));
1030                                }
1031                                createAccountManagerAccount(accountManagerContext,
1032                                        accountCursor.getString(V21_ACCOUNT_EMAIL),
1033                                        hostAuthCursor.getString(V21_HOSTAUTH_PASSWORD));
1034                            // If an EAS account, make Email sync automatically (equivalent of
1035                            // checking the "Sync Email" box in settings
1036                            } else if (HostAuth.SCHEME_EAS.equals(protocol)) {
1037                                android.accounts.Account amAccount =
1038                                        new android.accounts.Account(
1039                                                accountCursor.getString(V21_ACCOUNT_EMAIL),
1040                                                AccountManagerTypes.TYPE_EXCHANGE);
1041                                ContentResolver.setIsSyncable(amAccount, EmailContent.AUTHORITY, 1);
1042                                ContentResolver.setSyncAutomatically(amAccount,
1043                                        EmailContent.AUTHORITY, true);
1044
1045                            }
1046                        }
1047                    } finally {
1048                        hostAuthCursor.close();
1049                    }
1050                }
1051            } finally {
1052                accountCursor.close();
1053            }
1054        } catch (SQLException e) {
1055            // Shouldn't be needed unless we're debugging and interrupt the process
1056            Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
1057        }
1058    }
1059
1060    /** Upgrades the database from v22 to v23 */
1061    private static void upgradeFromVersion22ToVersion23(SQLiteDatabase db) {
1062        try {
1063            db.execSQL("alter table " + Mailbox.TABLE_NAME
1064                    + " add column " + Mailbox.LAST_TOUCHED_TIME + " integer default 0;");
1065        } catch (SQLException e) {
1066            // Shouldn't be needed unless we're debugging and interrupt the process
1067            Log.w(TAG, "Exception upgrading EmailProvider.db from 22 to 23 " + e);
1068        }
1069    }
1070
1071    /** Adds in a column for information about a client certificate to use. */
1072    private static void upgradeFromVersion23ToVersion24(SQLiteDatabase db) {
1073        try {
1074            db.execSQL("alter table " + HostAuth.TABLE_NAME
1075                    + " add column " + HostAuth.CLIENT_CERT_ALIAS + " text;");
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 23 to 24 " + e);
1079        }
1080    }
1081
1082    /** Upgrades the database from v24 to v25 by creating table for quick responses */
1083    private static void upgradeFromVersion24ToVersion25(SQLiteDatabase db) {
1084        try {
1085            createQuickResponseTable(db);
1086        } catch (SQLException e) {
1087            // Shouldn't be needed unless we're debugging and interrupt the process
1088            Log.w(TAG, "Exception upgrading EmailProvider.db from 24 to 25 " + e);
1089        }
1090    }
1091
1092    private static final String[] V25_ACCOUNT_PROJECTION =
1093        new String[] {AccountColumns.ID, AccountColumns.FLAGS, AccountColumns.HOST_AUTH_KEY_RECV};
1094    private static final int V25_ACCOUNT_ID = 0;
1095    private static final int V25_ACCOUNT_FLAGS = 1;
1096    private static final int V25_ACCOUNT_RECV = 2;
1097
1098    private static final String[] V25_HOSTAUTH_PROJECTION = new String[] {HostAuthColumns.PROTOCOL};
1099    private static final int V25_HOSTAUTH_PROTOCOL = 0;
1100
1101    /** Upgrades the database from v25 to v26 by adding FLAG_SUPPORTS_SEARCH to IMAP accounts */
1102    private static void upgradeFromVersion25ToVersion26(SQLiteDatabase db) {
1103        try {
1104            // Loop through accounts, looking for imap accounts
1105            Cursor accountCursor = db.query(Account.TABLE_NAME, V25_ACCOUNT_PROJECTION, null,
1106                    null, null, null, null);
1107            ContentValues cv = new ContentValues();
1108            try {
1109                String[] hostAuthArgs = new String[1];
1110                while (accountCursor.moveToNext()) {
1111                    hostAuthArgs[0] = accountCursor.getString(V25_ACCOUNT_RECV);
1112                    // Get the "receive" HostAuth for this account
1113                    Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
1114                            V25_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
1115                            null, null, null);
1116                    try {
1117                        if (hostAuthCursor.moveToFirst()) {
1118                            String protocol = hostAuthCursor.getString(V25_HOSTAUTH_PROTOCOL);
1119                            // If this is an imap account, add the search flag
1120                            if (HostAuth.SCHEME_IMAP.equals(protocol)) {
1121                                String id = accountCursor.getString(V25_ACCOUNT_ID);
1122                                int flags = accountCursor.getInt(V25_ACCOUNT_FLAGS);
1123                                cv.put(AccountColumns.FLAGS, flags | Account.FLAGS_SUPPORTS_SEARCH);
1124                                db.update(Account.TABLE_NAME, cv, Account.RECORD_ID + "=?",
1125                                        new String[] {id});
1126                            }
1127                        }
1128                    } finally {
1129                        hostAuthCursor.close();
1130                    }
1131                }
1132            } finally {
1133                accountCursor.close();
1134            }
1135        } catch (SQLException e) {
1136            // Shouldn't be needed unless we're debugging and interrupt the process
1137            Log.w(TAG, "Exception upgrading EmailProvider.db from 25 to 26 " + e);
1138        }
1139    }
1140
1141    /** Upgrades the database from v29 to v30 by updating all address fields in Message */
1142    private static final int[] ADDRESS_COLUMN_INDICES = new int[] {
1143        Message.CONTENT_BCC_LIST_COLUMN, Message.CONTENT_CC_LIST_COLUMN,
1144        Message.CONTENT_FROM_LIST_COLUMN, Message.CONTENT_REPLY_TO_COLUMN,
1145        Message.CONTENT_TO_LIST_COLUMN
1146    };
1147    private static final String[] ADDRESS_COLUMN_NAMES = new String[] {
1148        Message.BCC_LIST, Message.CC_LIST, Message.FROM_LIST, Message.REPLY_TO_LIST, Message.TO_LIST
1149    };
1150
1151    private static void upgradeFromVersion29ToVersion30(SQLiteDatabase db) {
1152        try {
1153            // Loop through all messages, updating address columns to new format (CSV, RFC822)
1154            Cursor messageCursor = db.query(Message.TABLE_NAME, Message.CONTENT_PROJECTION, null,
1155                    null, null, null, null);
1156            ContentValues cv = new ContentValues();
1157            String[] whereArgs = new String[1];
1158            try {
1159                while (messageCursor.moveToNext()) {
1160                    for (int i = 0; i < ADDRESS_COLUMN_INDICES.length; i++) {
1161                        Address[] addrs =
1162                                Address.unpack(messageCursor.getString(ADDRESS_COLUMN_INDICES[i]));
1163                        cv.put(ADDRESS_COLUMN_NAMES[i], Address.pack(addrs));
1164                    }
1165                    whereArgs[0] = messageCursor.getString(Message.CONTENT_ID_COLUMN);
1166                    db.update(Message.TABLE_NAME, cv, WHERE_ID, whereArgs);
1167                }
1168            } finally {
1169                messageCursor.close();
1170            }
1171        } catch (SQLException e) {
1172            // Shouldn't be needed unless we're debugging and interrupt the process
1173            Log.w(TAG, "Exception upgrading EmailProvider.db from 29 to 30 " + e);
1174        }
1175    }
1176
1177}
1178