blob: f15b76f0ea62e781ebf148568477c80583cfb760 [file] [log] [blame]
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001/*
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
Marc Blanke7e1ca42009-09-15 19:27:05 -070019import android.accounts.AccountManager;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070020import android.content.ContentProvider;
Marc Blankfae47272009-05-29 14:24:34 -070021import android.content.ContentProviderOperation;
22import android.content.ContentProviderResult;
Marc Blank1b9337e2010-09-23 09:19:44 -070023import android.content.ContentResolver;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070024import android.content.ContentUris;
25import android.content.ContentValues;
26import android.content.Context;
Marc Blankfae47272009-05-29 14:24:34 -070027import android.content.OperationApplicationException;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070028import android.content.UriMatcher;
Todd Kennedybf30f942011-05-06 11:31:10 -070029import android.database.ContentObserver;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070030import android.database.Cursor;
Marc Blankd306ba32010-12-30 14:55:27 -080031import android.database.MatrixCursor;
Marc Blanka290f502009-06-15 14:40:06 -070032import android.database.SQLException;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070033import android.database.sqlite.SQLiteDatabase;
Marc Blank0e1595c2009-11-18 17:11:33 -080034import android.database.sqlite.SQLiteException;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070035import android.database.sqlite.SQLiteOpenHelper;
36import android.net.Uri;
Marc Blankf3ff0ba2011-05-19 14:14:14 -070037import android.provider.ContactsContract;
Makoto Onuki9dad9ad2011-06-20 18:10:10 -070038import android.text.TextUtils;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070039import android.util.Log;
40
Marc Blank6e418aa2011-06-18 18:03:11 -070041import com.android.email.Email;
42import com.android.email.Preferences;
43import com.android.email.provider.ContentCache.CacheToken;
44import com.android.email.service.AttachmentDownloadService;
45import com.android.emailcommon.AccountManagerTypes;
46import com.android.emailcommon.CalendarProviderStub;
47import com.android.emailcommon.Logging;
48import com.android.emailcommon.provider.Account;
49import com.android.emailcommon.provider.EmailContent;
50import com.android.emailcommon.provider.EmailContent.AccountColumns;
51import com.android.emailcommon.provider.EmailContent.Attachment;
52import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
53import com.android.emailcommon.provider.EmailContent.Body;
54import com.android.emailcommon.provider.EmailContent.BodyColumns;
55import com.android.emailcommon.provider.EmailContent.HostAuthColumns;
56import com.android.emailcommon.provider.EmailContent.MailboxColumns;
57import com.android.emailcommon.provider.EmailContent.Message;
58import com.android.emailcommon.provider.EmailContent.MessageColumns;
59import com.android.emailcommon.provider.EmailContent.PolicyColumns;
60import com.android.emailcommon.provider.EmailContent.QuickResponseColumns;
61import com.android.emailcommon.provider.EmailContent.SyncColumns;
62import com.android.emailcommon.provider.HostAuth;
63import com.android.emailcommon.provider.Mailbox;
64import com.android.emailcommon.provider.Policy;
65import com.android.emailcommon.provider.QuickResponse;
66import com.android.emailcommon.service.LegacyPolicySet;
67import com.google.common.annotations.VisibleForTesting;
68
Marc Blank0e1595c2009-11-18 17:11:33 -080069import java.io.File;
Fred Quintana84969fb2009-06-01 12:55:50 -070070import java.util.ArrayList;
Marc Blank6e418aa2011-06-18 18:03:11 -070071import java.util.Arrays;
72import java.util.Collection;
73import java.util.HashMap;
Marc Blank5d7ff852011-06-27 20:11:24 -070074import java.util.List;
Marc Blank6e418aa2011-06-18 18:03:11 -070075import java.util.Map;
Fred Quintana84969fb2009-06-01 12:55:50 -070076
Andrew Stadlerf3d5b202009-05-26 16:40:34 -070077public class EmailProvider extends ContentProvider {
78
79 private static final String TAG = "EmailProvider";
80
Marc Blank0e1595c2009-11-18 17:11:33 -080081 protected static final String DATABASE_NAME = "EmailProvider.db";
82 protected static final String BODY_DATABASE_NAME = "EmailProviderBody.db";
Marc Blank09931902011-05-06 12:07:39 -070083 protected static final String BACKUP_DATABASE_NAME = "EmailProviderBackup.db";
Marc Blank0e1595c2009-11-18 17:11:33 -080084
Marc Blank09fd4d02010-08-09 17:48:53 -070085 public static final String ACTION_ATTACHMENT_UPDATED = "com.android.email.ATTACHMENT_UPDATED";
86 public static final String ATTACHMENT_UPDATED_EXTRA_FLAGS =
87 "com.android.email.ATTACHMENT_UPDATED_FLAGS";
88
Marc Blankc81bef62010-10-13 19:04:46 -070089 public static final String EMAIL_MESSAGE_MIME_TYPE =
90 "vnd.android.cursor.item/email-message";
Marc Blank09fd4d02010-08-09 17:48:53 -070091 public static final String EMAIL_ATTACHMENT_MIME_TYPE =
92 "vnd.android.cursor.item/email-attachment";
93
Marc Blank0e1595c2009-11-18 17:11:33 -080094 public static final Uri INTEGRITY_CHECK_URI =
95 Uri.parse("content://" + EmailContent.AUTHORITY + "/integrityCheck");
Marc Blank09931902011-05-06 12:07:39 -070096 public static final Uri ACCOUNT_BACKUP_URI =
97 Uri.parse("content://" + EmailContent.AUTHORITY + "/accountBackup");
Marc Blankef832992009-10-13 16:25:00 -070098
Todd Kennedybf30f942011-05-06 11:31:10 -070099 /** Appended to the notification URI for delete operations */
100 public static final String NOTIFICATION_OP_DELETE = "delete";
101 /** Appended to the notification URI for insert operations */
102 public static final String NOTIFICATION_OP_INSERT = "insert";
103 /** Appended to the notification URI for update operations */
104 public static final String NOTIFICATION_OP_UPDATE = "update";
105
Marc Blankef832992009-10-13 16:25:00 -0700106 // Definitions for our queries looking for orphaned messages
107 private static final String[] ORPHANS_PROJECTION
108 = new String[] {MessageColumns.ID, MessageColumns.MAILBOX_KEY};
109 private static final int ORPHANS_ID = 0;
110 private static final int ORPHANS_MAILBOX_KEY = 1;
111
112 private static final String WHERE_ID = EmailContent.RECORD_ID + "=?";
Marc Blankf3743042009-06-27 12:14:14 -0700113
Marc Blank6e418aa2011-06-18 18:03:11 -0700114 // This is not a hard limit on accounts, per se, but beyond this, we can't guarantee that all
115 // critical mailboxes, host auth's, accounts, and policies are cached
116 private static final int MAX_CACHED_ACCOUNTS = 16;
117 // Inbox, Drafts, Sent, Outbox, Trash, and Search (these boxes are cached when possible)
118 private static final int NUM_ALWAYS_CACHED_MAILBOXES = 6;
119
Marc Blankfab77f12010-10-27 16:50:54 -0700120 // We'll cache the following four tables; sizes are best estimates of effective values
Marc Blank6e418aa2011-06-18 18:03:11 -0700121 private final ContentCache mCacheAccount =
122 new ContentCache("Account", Account.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
123 private final ContentCache mCacheHostAuth =
124 new ContentCache("HostAuth", HostAuth.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS * 2);
125 /*package*/ final ContentCache mCacheMailbox =
126 new ContentCache("Mailbox", Mailbox.CONTENT_PROJECTION,
127 MAX_CACHED_ACCOUNTS * (NUM_ALWAYS_CACHED_MAILBOXES + 2));
128 private final ContentCache mCacheMessage =
Marc Blankaeee10e2011-04-27 17:12:06 -0700129 new ContentCache("Message", Message.CONTENT_PROJECTION, 8);
Marc Blank6e418aa2011-06-18 18:03:11 -0700130 private final ContentCache mCachePolicy =
131 new ContentCache("Policy", Policy.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
Marc Blankfab77f12010-10-27 16:50:54 -0700132
Andrew Stadler4a8c70c2009-08-18 12:14:15 -0700133 // Any changes to the database format *must* include update-in-place code.
Marc Blanke2569832009-09-07 16:03:02 -0700134 // Original version: 3
Marc Blanke7e1ca42009-09-15 19:27:05 -0700135 // Version 4: Database wipe required; changing AccountManager interface w/Exchange
Andrew Stadler0d008892009-09-22 18:31:10 -0700136 // Version 5: Database wipe required; changing AccountManager interface w/Exchange
137 // Version 6: Adding Message.mServerTimeStamp column
Marc Blankef832992009-10-13 16:25:00 -0700138 // Version 7: Replace the mailbox_delete trigger with a version that removes orphaned messages
139 // from the Message_Deletes and Message_Updates tables
Andrew Stadlerfc8d9432010-01-21 11:48:02 -0800140 // Version 8: Add security flags column to accounts table
Andrew Stadler345fb8b2010-01-26 17:24:15 -0800141 // Version 9: Add security sync key and signature to accounts table
Marc Blank4006e5f2010-02-15 16:01:38 -0800142 // Version 10: Add meeting info to message table
Andrew Stadler3aaba9e2010-02-22 12:57:33 -0800143 // Version 11: Add content and flags to attachment table
Makoto Onuki20225d52010-03-12 13:30:26 -0800144 // Version 12: Add content_bytes to attachment table. content is deprecated.
Makoto Onuki574854b2010-07-30 13:53:59 -0700145 // Version 13: Add messageCount to Mailbox table.
Marc Blanke7b9e4a2010-09-01 19:06:15 -0700146 // Version 14: Add snippet to Message table
Makoto Onukiddc8dea2010-09-07 12:36:48 -0700147 // Version 15: Fix upgrade problem in version 14.
Marc Blank75a873b2010-12-08 17:11:04 -0800148 // Version 16: Add accountKey to Attachment table
Andy Stadler3a585092011-03-01 10:45:50 -0800149 // Version 17: Add parentKey to Mailbox table
Todd Kennedy22208772011-04-22 15:45:11 -0700150 // Version 18: Copy Mailbox.displayName to Mailbox.serverId for all IMAP & POP3 mailboxes.
151 // Column Mailbox.serverId is used for the server-side pathname of a mailbox.
Marc Blankaeee10e2011-04-27 17:12:06 -0700152 // Version 19: Add Policy table; add policyKey to Account table and trigger to delete an
153 // Account's policy when the Account is deleted
Marc Blankf91a03f2011-05-05 10:34:29 -0700154 // Version 20: Add new policies to Policy table
Todd Kennedya9ac20b2011-05-06 13:37:02 -0700155 // Version 21: Add lastSeenMessageKey column to Mailbox table
Marc Blankf3ff0ba2011-05-19 14:14:14 -0700156 // Version 22: Upgrade path for IMAP/POP accounts to integrate with AccountManager
Todd Kennedy9dcb72e2011-06-03 08:51:25 -0700157 // Version 23: Add column to mailbox table for time of last access
Ben Komalo313586c2011-06-07 11:39:16 -0700158 // Version 24: Add column to hostauth table for client cert alias
Jorge Lugo5a3888f2011-06-01 10:09:26 -0700159 // Version 25: Added QuickResponse table
Marc Blankdeb345a2011-06-23 10:22:25 -0700160 // Version 26: Update IMAP accounts to add FLAG_SUPPORTS_SEARCH flag
Marc Blank9a013532011-06-23 10:52:21 -0700161 // Version 27: Add protocolSearchInfo to Message table
Marc Blankaca94262011-07-19 18:19:59 -0700162 // Version 28: Add notifiedMessageId and notifiedMessageCount to Account
Marc Blank2736c1a2011-10-20 10:13:02 -0700163 // Version 29: Add protocolPoliciesEnforced and protocolPoliciesUnsupported to Policy
Marc Blankf3ff0ba2011-05-19 14:14:14 -0700164
Marc Blank2736c1a2011-10-20 10:13:02 -0700165 public static final int DATABASE_VERSION = 29;
Marc Blanke2569832009-09-07 16:03:02 -0700166
167 // Any changes to the database format *must* include update-in-place code.
168 // Original version: 2
169 // Version 3: Add "sourceKey" column
Marc Blanke7e1ca42009-09-15 19:27:05 -0700170 // Version 4: Database wipe required; changing AccountManager interface w/Exchange
Andrew Stadler0d008892009-09-22 18:31:10 -0700171 // Version 5: Database wipe required; changing AccountManager interface w/Exchange
Marc Blank5fc57ec2009-09-22 18:38:28 -0700172 // Version 6: Adding Body.mIntroText column
173 public static final int BODY_DATABASE_VERSION = 6;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700174
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700175 private static final int ACCOUNT_BASE = 0;
176 private static final int ACCOUNT = ACCOUNT_BASE;
Makoto Onuki7bcf1882010-09-10 15:19:57 -0700177 private static final int ACCOUNT_ID = ACCOUNT_BASE + 1;
178 private static final int ACCOUNT_ID_ADD_TO_FIELD = ACCOUNT_BASE + 2;
Makoto Onuki261d6c32010-09-14 16:28:50 -0700179 private static final int ACCOUNT_RESET_NEW_COUNT = ACCOUNT_BASE + 3;
180 private static final int ACCOUNT_RESET_NEW_COUNT_ID = ACCOUNT_BASE + 4;
Marc Blank6e418aa2011-06-18 18:03:11 -0700181 private static final int ACCOUNT_DEFAULT_ID = ACCOUNT_BASE + 5;
Marc Blankf3743042009-06-27 12:14:14 -0700182
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700183 private static final int MAILBOX_BASE = 0x1000;
184 private static final int MAILBOX = MAILBOX_BASE;
Makoto Onuki7bcf1882010-09-10 15:19:57 -0700185 private static final int MAILBOX_ID = MAILBOX_BASE + 1;
Marc Blank6e418aa2011-06-18 18:03:11 -0700186 private static final int MAILBOX_ID_FROM_ACCOUNT_AND_TYPE = MAILBOX_BASE + 2;
Makoto Onuki7bcf1882010-09-10 15:19:57 -0700187 private static final int MAILBOX_ID_ADD_TO_FIELD = MAILBOX_BASE + 2;
Marc Blankf3743042009-06-27 12:14:14 -0700188
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700189 private static final int MESSAGE_BASE = 0x2000;
190 private static final int MESSAGE = MESSAGE_BASE;
Andrew Stadler41192182009-07-16 16:03:40 -0700191 private static final int MESSAGE_ID = MESSAGE_BASE + 1;
192 private static final int SYNCED_MESSAGE_ID = MESSAGE_BASE + 2;
Marc Blankf3743042009-06-27 12:14:14 -0700193
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700194 private static final int ATTACHMENT_BASE = 0x3000;
195 private static final int ATTACHMENT = ATTACHMENT_BASE;
Makoto Onuki7bcf1882010-09-10 15:19:57 -0700196 private static final int ATTACHMENT_ID = ATTACHMENT_BASE + 1;
197 private static final int ATTACHMENTS_MESSAGE_ID = ATTACHMENT_BASE + 2;
Marc Blankf3743042009-06-27 12:14:14 -0700198
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700199 private static final int HOSTAUTH_BASE = 0x4000;
200 private static final int HOSTAUTH = HOSTAUTH_BASE;
201 private static final int HOSTAUTH_ID = HOSTAUTH_BASE + 1;
Marc Blankf3743042009-06-27 12:14:14 -0700202
Marc Blanke34525d2009-06-17 10:22:37 -0700203 private static final int UPDATED_MESSAGE_BASE = 0x5000;
204 private static final int UPDATED_MESSAGE = UPDATED_MESSAGE_BASE;
Marc Blankf3743042009-06-27 12:14:14 -0700205 private static final int UPDATED_MESSAGE_ID = UPDATED_MESSAGE_BASE + 1;
206
207 private static final int DELETED_MESSAGE_BASE = 0x6000;
208 private static final int DELETED_MESSAGE = DELETED_MESSAGE_BASE;
209 private static final int DELETED_MESSAGE_ID = DELETED_MESSAGE_BASE + 1;
Marc Blankf3743042009-06-27 12:14:14 -0700210
Marc Blankaeee10e2011-04-27 17:12:06 -0700211 private static final int POLICY_BASE = 0x7000;
212 private static final int POLICY = POLICY_BASE;
213 private static final int POLICY_ID = POLICY_BASE + 1;
214
Jorge Lugo5a3888f2011-06-01 10:09:26 -0700215 private static final int QUICK_RESPONSE_BASE = 0x8000;
216 private static final int QUICK_RESPONSE = QUICK_RESPONSE_BASE;
217 private static final int QUICK_RESPONSE_ID = QUICK_RESPONSE_BASE + 1;
218 private static final int QUICK_RESPONSE_ACCOUNT_ID = QUICK_RESPONSE_BASE + 2;
219
Marc Blankf3743042009-06-27 12:14:14 -0700220 // MUST ALWAYS EQUAL THE LAST OF THE PREVIOUS BASE CONSTANTS
Jorge Lugo5a3888f2011-06-01 10:09:26 -0700221 private static final int LAST_EMAIL_PROVIDER_DB_BASE = QUICK_RESPONSE_BASE;
Marc Blankf3743042009-06-27 12:14:14 -0700222
223 // DO NOT CHANGE BODY_BASE!!
224 private static final int BODY_BASE = LAST_EMAIL_PROVIDER_DB_BASE + 0x1000;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700225 private static final int BODY = BODY_BASE;
226 private static final int BODY_ID = BODY_BASE + 1;
Marc Blankf3743042009-06-27 12:14:14 -0700227
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700228 private static final int BASE_SHIFT = 12; // 12 bits to the base type: 0, 0x1000, 0x2000, etc.
Marc Blankf3743042009-06-27 12:14:14 -0700229
Marc Blankfab77f12010-10-27 16:50:54 -0700230 // TABLE_NAMES MUST remain in the order of the BASE constants above (e.g. ACCOUNT_BASE = 0x0000,
231 // MESSAGE_BASE = 0x1000, etc.)
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700232 private static final String[] TABLE_NAMES = {
Marc Blankf5418f12011-06-13 15:32:27 -0700233 Account.TABLE_NAME,
Ben Komalo53ea83e2011-05-13 17:26:27 -0700234 Mailbox.TABLE_NAME,
Marc Blank6e418aa2011-06-18 18:03:11 -0700235 Message.TABLE_NAME,
236 Attachment.TABLE_NAME,
Ben Komalo12b82d92011-05-19 15:18:12 -0700237 HostAuth.TABLE_NAME,
Marc Blank6e418aa2011-06-18 18:03:11 -0700238 Message.UPDATED_TABLE_NAME,
239 Message.DELETED_TABLE_NAME,
Marc Blankaeee10e2011-04-27 17:12:06 -0700240 Policy.TABLE_NAME,
Jorge Lugo5a3888f2011-06-01 10:09:26 -0700241 QuickResponse.TABLE_NAME,
Marc Blank6e418aa2011-06-18 18:03:11 -0700242 Body.TABLE_NAME
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700243 };
Marc Blankf3743042009-06-27 12:14:14 -0700244
Marc Blankfab77f12010-10-27 16:50:54 -0700245 // CONTENT_CACHES MUST remain in the order of the BASE constants above
Marc Blank6e418aa2011-06-18 18:03:11 -0700246 private final ContentCache[] mContentCaches = {
247 mCacheAccount,
248 mCacheMailbox,
249 mCacheMessage,
Marc Blankaeee10e2011-04-27 17:12:06 -0700250 null, // Attachment
Marc Blank6e418aa2011-06-18 18:03:11 -0700251 mCacheHostAuth,
Marc Blankaeee10e2011-04-27 17:12:06 -0700252 null, // Updated message
253 null, // Deleted message
Marc Blank6e418aa2011-06-18 18:03:11 -0700254 mCachePolicy,
255 null, // Quick response
256 null // Body
257 };
258
259 // CACHE_PROJECTIONS MUST remain in the order of the BASE constants above
260 private static final String[][] CACHE_PROJECTIONS = {
261 Account.CONTENT_PROJECTION,
262 Mailbox.CONTENT_PROJECTION,
263 Message.CONTENT_PROJECTION,
264 null, // Attachment
265 HostAuth.CONTENT_PROJECTION,
266 null, // Updated message
267 null, // Deleted message
268 Policy.CONTENT_PROJECTION,
Jorge Lugo5a3888f2011-06-01 10:09:26 -0700269 null, // Quick response
Marc Blankaeee10e2011-04-27 17:12:06 -0700270 null // Body
271 };
Marc Blankfab77f12010-10-27 16:50:54 -0700272
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700273 private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
274
Marc Blank6e418aa2011-06-18 18:03:11 -0700275 private static final String MAILBOX_PRE_CACHE_SELECTION = MailboxColumns.TYPE + " IN (" +
276 Mailbox.TYPE_INBOX + "," + Mailbox.TYPE_DRAFTS + "," + Mailbox.TYPE_TRASH + "," +
277 Mailbox.TYPE_SENT + "," + Mailbox.TYPE_SEARCH + "," + Mailbox.TYPE_OUTBOX + ")";
278
Marc Blankf3743042009-06-27 12:14:14 -0700279 /**
280 * Let's only generate these SQL strings once, as they are used frequently
281 * Note that this isn't relevant for table creation strings, since they are used only once
282 */
283 private static final String UPDATED_MESSAGE_INSERT = "insert or ignore into " +
284 Message.UPDATED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
285 EmailContent.RECORD_ID + '=';
286
287 private static final String UPDATED_MESSAGE_DELETE = "delete from " +
288 Message.UPDATED_TABLE_NAME + " where " + EmailContent.RECORD_ID + '=';
289
290 private static final String DELETED_MESSAGE_INSERT = "insert or replace into " +
291 Message.DELETED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
292 EmailContent.RECORD_ID + '=';
293
294 private static final String DELETE_ORPHAN_BODIES = "delete from " + Body.TABLE_NAME +
Mihai Predafb7974f2009-08-03 15:05:50 +0200295 " where " + BodyColumns.MESSAGE_KEY + " in " + "(select " + BodyColumns.MESSAGE_KEY +
Marc Blankf3743042009-06-27 12:14:14 -0700296 " from " + Body.TABLE_NAME + " except select " + EmailContent.RECORD_ID + " from " +
297 Message.TABLE_NAME + ')';
298
299 private static final String DELETE_BODY = "delete from " + Body.TABLE_NAME +
Mihai Predafb7974f2009-08-03 15:05:50 +0200300 " where " + BodyColumns.MESSAGE_KEY + '=';
Marc Blankf3743042009-06-27 12:14:14 -0700301
Marc Blankc0c9c332009-08-19 19:07:29 -0700302 private static final String ID_EQUALS = EmailContent.RECORD_ID + "=?";
303
Marc Blankef832992009-10-13 16:25:00 -0700304 private static final String TRIGGER_MAILBOX_DELETE =
305 "create trigger mailbox_delete before delete on " + Mailbox.TABLE_NAME +
306 " begin" +
307 " delete from " + Message.TABLE_NAME +
308 " where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
309 "; delete from " + Message.UPDATED_TABLE_NAME +
310 " where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
311 "; delete from " + Message.DELETED_TABLE_NAME +
312 " where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
313 "; end";
Marc Blank36796362009-10-19 22:15:45 -0700314
Marc Blankaeee10e2011-04-27 17:12:06 -0700315 private static final String TRIGGER_ACCOUNT_DELETE =
316 "create trigger account_delete before delete on " + Account.TABLE_NAME +
317 " begin delete from " + Mailbox.TABLE_NAME +
318 " where " + MailboxColumns.ACCOUNT_KEY + "=old." + EmailContent.RECORD_ID +
319 "; delete from " + HostAuth.TABLE_NAME +
320 " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_RECV +
321 "; delete from " + HostAuth.TABLE_NAME +
322 " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_SEND +
323 "; delete from " + Policy.TABLE_NAME +
324 " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.POLICY_KEY +
325 "; end";
326
Makoto Onuki261d6c32010-09-14 16:28:50 -0700327 private static final ContentValues CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
328
Marc Blankc81bef62010-10-13 19:04:46 -0700329 public static final String MESSAGE_URI_PARAMETER_MAILBOX_ID = "mailboxId";
330
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700331 static {
332 // Email URI matching table
333 UriMatcher matcher = sURIMatcher;
Marc Blankf3743042009-06-27 12:14:14 -0700334
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700335 // All accounts
Marc Blank31d9acb2011-02-11 15:05:17 -0800336 matcher.addURI(EmailContent.AUTHORITY, "account", ACCOUNT);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700337 // A specific account
Marc Blank758a5322009-07-30 11:41:31 -0700338 // insert into this URI causes a mailbox to be added to the account
Marc Blank31d9acb2011-02-11 15:05:17 -0800339 matcher.addURI(EmailContent.AUTHORITY, "account/#", ACCOUNT_ID);
Marc Blank6e418aa2011-06-18 18:03:11 -0700340 matcher.addURI(EmailContent.AUTHORITY, "account/default", ACCOUNT_DEFAULT_ID);
Marc Blankf3743042009-06-27 12:14:14 -0700341
Makoto Onuki261d6c32010-09-14 16:28:50 -0700342 // Special URI to reset the new message count. Only update works, and content values
343 // will be ignored.
Marc Blank31d9acb2011-02-11 15:05:17 -0800344 matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount",
345 ACCOUNT_RESET_NEW_COUNT);
346 matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount/#",
347 ACCOUNT_RESET_NEW_COUNT_ID);
Makoto Onuki261d6c32010-09-14 16:28:50 -0700348
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700349 // All mailboxes
Marc Blank31d9acb2011-02-11 15:05:17 -0800350 matcher.addURI(EmailContent.AUTHORITY, "mailbox", MAILBOX);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700351 // A specific mailbox
352 // insert into this URI causes a message to be added to the mailbox
353 // ** NOTE For now, the accountKey must be set manually in the values!
Marc Blank31d9acb2011-02-11 15:05:17 -0800354 matcher.addURI(EmailContent.AUTHORITY, "mailbox/#", MAILBOX_ID);
Marc Blank6e418aa2011-06-18 18:03:11 -0700355 matcher.addURI(EmailContent.AUTHORITY, "mailboxIdFromAccountAndType/#/#",
356 MAILBOX_ID_FROM_ACCOUNT_AND_TYPE);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700357 // All messages
Marc Blank31d9acb2011-02-11 15:05:17 -0800358 matcher.addURI(EmailContent.AUTHORITY, "message", MESSAGE);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700359 // A specific message
Marc Blank758a5322009-07-30 11:41:31 -0700360 // insert into this URI causes an attachment to be added to the message
Marc Blank31d9acb2011-02-11 15:05:17 -0800361 matcher.addURI(EmailContent.AUTHORITY, "message/#", MESSAGE_ID);
Marc Blankf3743042009-06-27 12:14:14 -0700362
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700363 // A specific attachment
Marc Blank31d9acb2011-02-11 15:05:17 -0800364 matcher.addURI(EmailContent.AUTHORITY, "attachment", ATTACHMENT);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700365 // A specific attachment (the header information)
Marc Blank31d9acb2011-02-11 15:05:17 -0800366 matcher.addURI(EmailContent.AUTHORITY, "attachment/#", ATTACHMENT_ID);
Andrew Stadler41192182009-07-16 16:03:40 -0700367 // The attachments of a specific message (query only) (insert & delete TBD)
Marc Blank31d9acb2011-02-11 15:05:17 -0800368 matcher.addURI(EmailContent.AUTHORITY, "attachment/message/#",
369 ATTACHMENTS_MESSAGE_ID);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700370
371 // All mail bodies
Marc Blank31d9acb2011-02-11 15:05:17 -0800372 matcher.addURI(EmailContent.AUTHORITY, "body", BODY);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700373 // A specific mail body
Marc Blank31d9acb2011-02-11 15:05:17 -0800374 matcher.addURI(EmailContent.AUTHORITY, "body/#", BODY_ID);
Marc Blankf3743042009-06-27 12:14:14 -0700375
Andrew Stadler41192182009-07-16 16:03:40 -0700376 // All hostauth records
Marc Blank31d9acb2011-02-11 15:05:17 -0800377 matcher.addURI(EmailContent.AUTHORITY, "hostauth", HOSTAUTH);
Andrew Stadler41192182009-07-16 16:03:40 -0700378 // A specific hostauth
Marc Blank31d9acb2011-02-11 15:05:17 -0800379 matcher.addURI(EmailContent.AUTHORITY, "hostauth/#", HOSTAUTH_ID);
Marc Blankf3743042009-06-27 12:14:14 -0700380
Marc Blankc0c9c332009-08-19 19:07:29 -0700381 // Atomically a constant value to a particular field of a mailbox/account
Marc Blank31d9acb2011-02-11 15:05:17 -0800382 matcher.addURI(EmailContent.AUTHORITY, "mailboxIdAddToField/#",
383 MAILBOX_ID_ADD_TO_FIELD);
384 matcher.addURI(EmailContent.AUTHORITY, "accountIdAddToField/#",
385 ACCOUNT_ID_ADD_TO_FIELD);
Marc Blankc0c9c332009-08-19 19:07:29 -0700386
Marc Blankf3743042009-06-27 12:14:14 -0700387 /**
388 * THIS URI HAS SPECIAL SEMANTICS
Marc Blankc0c9c332009-08-19 19:07:29 -0700389 * ITS USE IS INTENDED FOR THE UI APPLICATION TO MARK CHANGES THAT NEED TO BE SYNCED BACK
Marc Blankf3743042009-06-27 12:14:14 -0700390 * TO A SERVER VIA A SYNC ADAPTER
391 */
Marc Blank31d9acb2011-02-11 15:05:17 -0800392 matcher.addURI(EmailContent.AUTHORITY, "syncedMessage/#", SYNCED_MESSAGE_ID);
Marc Blankf3743042009-06-27 12:14:14 -0700393
394 /**
395 * THE URIs BELOW THIS POINT ARE INTENDED TO BE USED BY SYNC ADAPTERS ONLY
396 * THEY REFER TO DATA CREATED AND MAINTAINED BY CALLS TO THE SYNCED_MESSAGE_ID URI
397 * BY THE UI APPLICATION
398 */
399 // All deleted messages
Marc Blank31d9acb2011-02-11 15:05:17 -0800400 matcher.addURI(EmailContent.AUTHORITY, "deletedMessage", DELETED_MESSAGE);
Marc Blankf3743042009-06-27 12:14:14 -0700401 // A specific deleted message
Marc Blank31d9acb2011-02-11 15:05:17 -0800402 matcher.addURI(EmailContent.AUTHORITY, "deletedMessage/#", DELETED_MESSAGE_ID);
Marc Blankf3743042009-06-27 12:14:14 -0700403
404 // All updated messages
Marc Blank31d9acb2011-02-11 15:05:17 -0800405 matcher.addURI(EmailContent.AUTHORITY, "updatedMessage", UPDATED_MESSAGE);
Marc Blankf3743042009-06-27 12:14:14 -0700406 // A specific updated message
Marc Blank31d9acb2011-02-11 15:05:17 -0800407 matcher.addURI(EmailContent.AUTHORITY, "updatedMessage/#", UPDATED_MESSAGE_ID);
Makoto Onuki261d6c32010-09-14 16:28:50 -0700408
409 CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT = new ContentValues();
410 CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT.put(Account.NEW_MESSAGE_COUNT, 0);
Marc Blankaeee10e2011-04-27 17:12:06 -0700411
412 matcher.addURI(EmailContent.AUTHORITY, "policy", POLICY);
413 matcher.addURI(EmailContent.AUTHORITY, "policy/#", POLICY_ID);
Jorge Lugo5a3888f2011-06-01 10:09:26 -0700414
415 // All quick responses
416 matcher.addURI(EmailContent.AUTHORITY, "quickresponse", QUICK_RESPONSE);
417 // A specific quick response
418 matcher.addURI(EmailContent.AUTHORITY, "quickresponse/#", QUICK_RESPONSE_ID);
419 // All quick responses associated with a particular account id
420 matcher.addURI(EmailContent.AUTHORITY, "quickresponse/account/#",
421 QUICK_RESPONSE_ACCOUNT_ID);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700422 }
423
Marc Blanke6a22df2010-12-16 12:28:16 -0800424 /**
425 * Wrap the UriMatcher call so we can throw a runtime exception if an unknown Uri is passed in
426 * @param uri the Uri to match
427 * @return the match value
428 */
429 private static int findMatch(Uri uri, String methodName) {
430 int match = sURIMatcher.match(uri);
431 if (match < 0) {
Marc Blank1c1bd6a2010-12-29 20:51:16 -0800432 throw new IllegalArgumentException("Unknown uri: " + uri);
Makoto Onukibfac9f22011-05-13 11:20:04 -0700433 } else if (Logging.LOGD) {
Marc Blanke6a22df2010-12-16 12:28:16 -0800434 Log.v(TAG, methodName + ": uri=" + uri + ", match is " + match);
435 }
436 return match;
437 }
438
Mihai Preda9627d012009-08-12 12:51:26 +0200439 /*
440 * Internal helper method for index creation.
441 * Example:
442 * "create index message_" + MessageColumns.FLAG_READ
443 * + " on " + Message.TABLE_NAME + " (" + MessageColumns.FLAG_READ + ");"
444 */
445 /* package */
446 static String createIndex(String tableName, String columnName) {
447 return "create index " + tableName.toLowerCase() + '_' + columnName
448 + " on " + tableName + " (" + columnName + ");";
449 }
450
Marc Blanka290f502009-06-15 14:40:06 -0700451 static void createMessageTable(SQLiteDatabase db) {
Marc Blankb6493a02009-07-05 12:54:49 -0700452 String messageColumns = MessageColumns.DISPLAY_NAME + " text, "
453 + MessageColumns.TIMESTAMP + " integer, "
454 + MessageColumns.SUBJECT + " text, "
Marc Blankb6493a02009-07-05 12:54:49 -0700455 + MessageColumns.FLAG_READ + " integer, "
456 + MessageColumns.FLAG_LOADED + " integer, "
457 + MessageColumns.FLAG_FAVORITE + " integer, "
458 + MessageColumns.FLAG_ATTACHMENT + " integer, "
459 + MessageColumns.FLAGS + " integer, "
Marc Blankb6493a02009-07-05 12:54:49 -0700460 + MessageColumns.CLIENT_ID + " integer, "
461 + MessageColumns.MESSAGE_ID + " text, "
Marc Blankb6493a02009-07-05 12:54:49 -0700462 + MessageColumns.MAILBOX_KEY + " integer, "
463 + MessageColumns.ACCOUNT_KEY + " integer, "
Marc Blankb6493a02009-07-05 12:54:49 -0700464 + MessageColumns.FROM_LIST + " text, "
465 + MessageColumns.TO_LIST + " text, "
466 + MessageColumns.CC_LIST + " text, "
467 + MessageColumns.BCC_LIST + " text, "
Marc Blank4006e5f2010-02-15 16:01:38 -0800468 + MessageColumns.REPLY_TO_LIST + " text, "
Marc Blanke7b9e4a2010-09-01 19:06:15 -0700469 + MessageColumns.MEETING_INFO + " text, "
Marc Blank9a013532011-06-23 10:52:21 -0700470 + MessageColumns.SNIPPET + " text, "
471 + MessageColumns.PROTOCOL_SEARCH_INFO + " text"
Marc Blankb6493a02009-07-05 12:54:49 -0700472 + ");";
473
474 // This String and the following String MUST have the same columns, except for the type
475 // of those columns!
476 String createString = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
Andrew Stadler0d008892009-09-22 18:31:10 -0700477 + SyncColumns.SERVER_ID + " text, "
478 + SyncColumns.SERVER_TIMESTAMP + " integer, "
Marc Blankb6493a02009-07-05 12:54:49 -0700479 + messageColumns;
480
481 // For the updated and deleted tables, the id is assigned, but we do want to keep track
482 // of the ORDER of updates using an autoincrement primary key. We use the DATA column
483 // at this point; it has no other function
Marc Blank6b158f72009-07-14 13:08:19 -0700484 String altCreateString = " (" + EmailContent.RECORD_ID + " integer unique, "
Andrew Stadler0d008892009-09-22 18:31:10 -0700485 + SyncColumns.SERVER_ID + " text, "
486 + SyncColumns.SERVER_TIMESTAMP + " integer, "
Marc Blankb6493a02009-07-05 12:54:49 -0700487 + messageColumns;
Marc Blankf3743042009-06-27 12:14:14 -0700488
489 // The three tables have the same schema
Marc Blankb6493a02009-07-05 12:54:49 -0700490 db.execSQL("create table " + Message.TABLE_NAME + createString);
491 db.execSQL("create table " + Message.UPDATED_TABLE_NAME + altCreateString);
492 db.execSQL("create table " + Message.DELETED_TABLE_NAME + altCreateString);
Marc Blankf3743042009-06-27 12:14:14 -0700493
Mihai Preda9627d012009-08-12 12:51:26 +0200494 String indexColumns[] = {
495 MessageColumns.TIMESTAMP,
496 MessageColumns.FLAG_READ,
497 MessageColumns.FLAG_LOADED,
498 MessageColumns.MAILBOX_KEY,
499 SyncColumns.SERVER_ID
500 };
501
502 for (String columnName : indexColumns) {
503 db.execSQL(createIndex(Message.TABLE_NAME, columnName));
504 }
Marc Blank2c67f1f2009-06-16 12:03:45 -0700505
Marc Blankf3743042009-06-27 12:14:14 -0700506 // Deleting a Message deletes all associated Attachments
Marc Blank2c67f1f2009-06-16 12:03:45 -0700507 // Deleting the associated Body cannot be done in a trigger, because the Body is stored
508 // in a separate database, and trigger cannot operate on attached databases.
Marc Blank758a5322009-07-30 11:41:31 -0700509 db.execSQL("create trigger message_delete before delete on " + Message.TABLE_NAME +
Marc Blank2c67f1f2009-06-16 12:03:45 -0700510 " begin delete from " + Attachment.TABLE_NAME +
Marc Blank758a5322009-07-30 11:41:31 -0700511 " where " + AttachmentColumns.MESSAGE_KEY + "=old." + EmailContent.RECORD_ID +
512 "; end");
513
514 // Add triggers to keep unread count accurate per mailbox
515
Makoto Onuki574854b2010-07-30 13:53:59 -0700516 // NOTE: SQLite's before triggers are not safe when recursive triggers are involved.
517 // Use caution when changing them.
518
Marc Blank758a5322009-07-30 11:41:31 -0700519 // Insert a message; if flagRead is zero, add to the unread count of the message's mailbox
520 db.execSQL("create trigger unread_message_insert before insert on " + Message.TABLE_NAME +
521 " when NEW." + MessageColumns.FLAG_READ + "=0" +
522 " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
523 '=' + MailboxColumns.UNREAD_COUNT + "+1" +
524 " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
525 "; end");
526
527 // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
528 db.execSQL("create trigger unread_message_delete before delete on " + Message.TABLE_NAME +
529 " when OLD." + MessageColumns.FLAG_READ + "=0" +
530 " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
531 '=' + MailboxColumns.UNREAD_COUNT + "-1" +
532 " where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
533 "; end");
534
535 // Change a message's mailbox
536 db.execSQL("create trigger unread_message_move before update of " +
537 MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
538 " when OLD." + MessageColumns.FLAG_READ + "=0" +
539 " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
540 '=' + MailboxColumns.UNREAD_COUNT + "-1" +
541 " where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
542 "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
543 '=' + MailboxColumns.UNREAD_COUNT + "+1" +
544 " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
545 "; end");
546
547 // Change a message's read state
Vasu Norib720ed32009-12-03 18:32:58 -0800548 db.execSQL("create trigger unread_message_read before update of " +
Marc Blank758a5322009-07-30 11:41:31 -0700549 MessageColumns.FLAG_READ + " on " + Message.TABLE_NAME +
550 " when OLD." + MessageColumns.FLAG_READ + "!=NEW." + MessageColumns.FLAG_READ +
551 " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
552 '=' + MailboxColumns.UNREAD_COUNT + "+ case OLD." + MessageColumns.FLAG_READ +
553 " when 0 then -1 else 1 end" +
554 " where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
555 "; end");
Makoto Onuki574854b2010-07-30 13:53:59 -0700556
557 // Add triggers to update message count per mailbox
558
559 // Insert a message.
560 db.execSQL("create trigger message_count_message_insert after insert on " +
561 Message.TABLE_NAME +
562 " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
563 '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
564 " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
565 "; end");
566
567 // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
568 db.execSQL("create trigger message_count_message_delete after delete on " +
569 Message.TABLE_NAME +
570 " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
571 '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
572 " where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
573 "; end");
574
575 // Change a message's mailbox
576 db.execSQL("create trigger message_count_message_move after update of " +
577 MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
578 " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
579 '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
580 " where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
581 "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
582 '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
583 " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
584 "; end");
585 }
Marc Blanka290f502009-06-15 14:40:06 -0700586
Marc Blanke7e1ca42009-09-15 19:27:05 -0700587 static void resetMessageTable(SQLiteDatabase db, int oldVersion, int newVersion) {
Andrew Stadlerddc871d2009-06-29 23:08:40 -0700588 try {
589 db.execSQL("drop table " + Message.TABLE_NAME);
590 db.execSQL("drop table " + Message.UPDATED_TABLE_NAME);
591 db.execSQL("drop table " + Message.DELETED_TABLE_NAME);
592 } catch (SQLException e) {
593 }
Marc Blanka290f502009-06-15 14:40:06 -0700594 createMessageTable(db);
595 }
596
Todd Kennedybf30f942011-05-06 11:31:10 -0700597 @SuppressWarnings("deprecation")
Marc Blanka290f502009-06-15 14:40:06 -0700598 static void createAccountTable(SQLiteDatabase db) {
Marc Blank758a5322009-07-30 11:41:31 -0700599 String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
Marc Blanka290f502009-06-15 14:40:06 -0700600 + AccountColumns.DISPLAY_NAME + " text, "
601 + AccountColumns.EMAIL_ADDRESS + " text, "
602 + AccountColumns.SYNC_KEY + " text, "
603 + AccountColumns.SYNC_LOOKBACK + " integer, "
Andrew Stadler9e2c6bd2009-07-22 15:13:30 -0700604 + AccountColumns.SYNC_INTERVAL + " text, "
Marc Blanka290f502009-06-15 14:40:06 -0700605 + AccountColumns.HOST_AUTH_KEY_RECV + " integer, "
606 + AccountColumns.HOST_AUTH_KEY_SEND + " integer, "
607 + AccountColumns.FLAGS + " integer, "
608 + AccountColumns.IS_DEFAULT + " integer, "
609 + AccountColumns.COMPATIBILITY_UUID + " text, "
610 + AccountColumns.SENDER_NAME + " text, "
Marc Blank53093872009-07-17 16:29:35 -0700611 + AccountColumns.RINGTONE_URI + " text, "
Andrew Stadler4a8c70c2009-08-18 12:14:15 -0700612 + AccountColumns.PROTOCOL_VERSION + " text, "
Andrew Stadlerfc8d9432010-01-21 11:48:02 -0800613 + AccountColumns.NEW_MESSAGE_COUNT + " integer, "
Andrew Stadler345fb8b2010-01-26 17:24:15 -0800614 + AccountColumns.SECURITY_FLAGS + " integer, "
615 + AccountColumns.SECURITY_SYNC_KEY + " text, "
Marc Blankaeee10e2011-04-27 17:12:06 -0700616 + AccountColumns.SIGNATURE + " text, "
Marc Blankaca94262011-07-19 18:19:59 -0700617 + AccountColumns.POLICY_KEY + " integer, "
618 + AccountColumns.NOTIFIED_MESSAGE_ID + " integer, "
619 + AccountColumns.NOTIFIED_MESSAGE_COUNT + " integer"
Marc Blanka290f502009-06-15 14:40:06 -0700620 + ");";
621 db.execSQL("create table " + Account.TABLE_NAME + s);
Marc Blank2c67f1f2009-06-16 12:03:45 -0700622 // Deleting an account deletes associated Mailboxes and HostAuth's
Marc Blankaeee10e2011-04-27 17:12:06 -0700623 db.execSQL(TRIGGER_ACCOUNT_DELETE);
Marc Blankf3743042009-06-27 12:14:14 -0700624 }
Marc Blanka290f502009-06-15 14:40:06 -0700625
Marc Blanke7e1ca42009-09-15 19:27:05 -0700626 static void resetAccountTable(SQLiteDatabase db, int oldVersion, int newVersion) {
Marc Blanka290f502009-06-15 14:40:06 -0700627 try {
628 db.execSQL("drop table " + Account.TABLE_NAME);
629 } catch (SQLException e) {
630 }
631 createAccountTable(db);
632 }
Marc Blankf3743042009-06-27 12:14:14 -0700633
Marc Blankaeee10e2011-04-27 17:12:06 -0700634 static void createPolicyTable(SQLiteDatabase db) {
635 String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
636 + PolicyColumns.PASSWORD_MODE + " integer, "
637 + PolicyColumns.PASSWORD_MIN_LENGTH + " integer, "
638 + PolicyColumns.PASSWORD_EXPIRATION_DAYS + " integer, "
639 + PolicyColumns.PASSWORD_HISTORY + " integer, "
640 + PolicyColumns.PASSWORD_COMPLEX_CHARS + " integer, "
641 + PolicyColumns.PASSWORD_MAX_FAILS + " integer, "
642 + PolicyColumns.MAX_SCREEN_LOCK_TIME + " integer, "
643 + PolicyColumns.REQUIRE_REMOTE_WIPE + " integer, "
644 + PolicyColumns.REQUIRE_ENCRYPTION + " integer, "
Marc Blankf91a03f2011-05-05 10:34:29 -0700645 + PolicyColumns.REQUIRE_ENCRYPTION_EXTERNAL + " integer, "
646 + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING + " integer, "
647 + PolicyColumns.DONT_ALLOW_CAMERA + " integer, "
648 + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer, "
649 + PolicyColumns.DONT_ALLOW_HTML + " integer, "
650 + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer, "
651 + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE + " integer, "
652 + PolicyColumns.MAX_HTML_TRUNCATION_SIZE + " integer, "
653 + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer, "
654 + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer, "
Marc Blank2736c1a2011-10-20 10:13:02 -0700655 + PolicyColumns.PASSWORD_RECOVERY_ENABLED + " integer, "
656 + PolicyColumns.PROTOCOL_POLICIES_ENFORCED + " text, "
657 + PolicyColumns.PROTOCOL_POLICIES_UNSUPPORTED + " text"
Marc Blankaeee10e2011-04-27 17:12:06 -0700658 + ");";
659 db.execSQL("create table " + Policy.TABLE_NAME + s);
660 }
661
Marc Blanka290f502009-06-15 14:40:06 -0700662 static void createHostAuthTable(SQLiteDatabase db) {
Marc Blank758a5322009-07-30 11:41:31 -0700663 String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
Marc Blanka290f502009-06-15 14:40:06 -0700664 + HostAuthColumns.PROTOCOL + " text, "
665 + HostAuthColumns.ADDRESS + " text, "
666 + HostAuthColumns.PORT + " integer, "
667 + HostAuthColumns.FLAGS + " integer, "
668 + HostAuthColumns.LOGIN + " text, "
669 + HostAuthColumns.PASSWORD + " text, "
670 + HostAuthColumns.DOMAIN + " text, "
Ben Komalo313586c2011-06-07 11:39:16 -0700671 + HostAuthColumns.ACCOUNT_KEY + " integer,"
672 + HostAuthColumns.CLIENT_CERT_ALIAS + " text"
Marc Blanka290f502009-06-15 14:40:06 -0700673 + ");";
674 db.execSQL("create table " + HostAuth.TABLE_NAME + s);
675 }
676
Marc Blanke7e1ca42009-09-15 19:27:05 -0700677 static void resetHostAuthTable(SQLiteDatabase db, int oldVersion, int newVersion) {
Marc Blanka290f502009-06-15 14:40:06 -0700678 try {
679 db.execSQL("drop table " + HostAuth.TABLE_NAME);
680 } catch (SQLException e) {
681 }
682 createHostAuthTable(db);
683 }
684
Marc Blankf3743042009-06-27 12:14:14 -0700685 static void createMailboxTable(SQLiteDatabase db) {
Marc Blank758a5322009-07-30 11:41:31 -0700686 String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
Marc Blanka290f502009-06-15 14:40:06 -0700687 + MailboxColumns.DISPLAY_NAME + " text, "
Marc Blank9be10e62009-09-03 16:42:20 -0700688 + MailboxColumns.SERVER_ID + " text, "
Marc Blanka290f502009-06-15 14:40:06 -0700689 + MailboxColumns.PARENT_SERVER_ID + " text, "
Andy Stadler3a585092011-03-01 10:45:50 -0800690 + MailboxColumns.PARENT_KEY + " integer, "
Marc Blanka290f502009-06-15 14:40:06 -0700691 + MailboxColumns.ACCOUNT_KEY + " integer, "
692 + MailboxColumns.TYPE + " integer, "
693 + MailboxColumns.DELIMITER + " integer, "
694 + MailboxColumns.SYNC_KEY + " text, "
695 + MailboxColumns.SYNC_LOOKBACK + " integer, "
Andrew Stadler9e2c6bd2009-07-22 15:13:30 -0700696 + MailboxColumns.SYNC_INTERVAL + " integer, "
Marc Blanka290f502009-06-15 14:40:06 -0700697 + MailboxColumns.SYNC_TIME + " integer, "
698 + MailboxColumns.UNREAD_COUNT + " integer, "
699 + MailboxColumns.FLAG_VISIBLE + " integer, "
700 + MailboxColumns.FLAGS + " integer, "
Marc Blank9b598922009-08-05 08:41:16 -0700701 + MailboxColumns.VISIBLE_LIMIT + " integer, "
Makoto Onuki574854b2010-07-30 13:53:59 -0700702 + MailboxColumns.SYNC_STATUS + " text, "
Todd Kennedya9ac20b2011-05-06 13:37:02 -0700703 + MailboxColumns.MESSAGE_COUNT + " integer not null default 0, "
Todd Kennedy2e112b22011-06-03 16:47:39 -0700704 + MailboxColumns.LAST_SEEN_MESSAGE_KEY + " integer, "
705 + MailboxColumns.LAST_TOUCHED_TIME + " integer default 0"
Marc Blankb6493a02009-07-05 12:54:49 -0700706 + ");";
Marc Blankf3743042009-06-27 12:14:14 -0700707 db.execSQL("create table " + Mailbox.TABLE_NAME + s);
Marc Blank758a5322009-07-30 11:41:31 -0700708 db.execSQL("create index mailbox_" + MailboxColumns.SERVER_ID
Marc Blanka290f502009-06-15 14:40:06 -0700709 + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.SERVER_ID + ")");
Marc Blank758a5322009-07-30 11:41:31 -0700710 db.execSQL("create index mailbox_" + MailboxColumns.ACCOUNT_KEY
Marc Blanka290f502009-06-15 14:40:06 -0700711 + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.ACCOUNT_KEY + ")");
Marc Blankef832992009-10-13 16:25:00 -0700712 // Deleting a Mailbox deletes associated Messages in all three tables
713 db.execSQL(TRIGGER_MAILBOX_DELETE);
Marc Blanka290f502009-06-15 14:40:06 -0700714 }
715
Marc Blanke7e1ca42009-09-15 19:27:05 -0700716 static void resetMailboxTable(SQLiteDatabase db, int oldVersion, int newVersion) {
Marc Blanka290f502009-06-15 14:40:06 -0700717 try {
718 db.execSQL("drop table " + Mailbox.TABLE_NAME);
719 } catch (SQLException e) {
720 }
721 createMailboxTable(db);
722 }
Marc Blankf3743042009-06-27 12:14:14 -0700723
Marc Blanka290f502009-06-15 14:40:06 -0700724 static void createAttachmentTable(SQLiteDatabase db) {
Marc Blank758a5322009-07-30 11:41:31 -0700725 String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
Marc Blanka290f502009-06-15 14:40:06 -0700726 + AttachmentColumns.FILENAME + " text, "
727 + AttachmentColumns.MIME_TYPE + " text, "
728 + AttachmentColumns.SIZE + " integer, "
729 + AttachmentColumns.CONTENT_ID + " text, "
730 + AttachmentColumns.CONTENT_URI + " text, "
731 + AttachmentColumns.MESSAGE_KEY + " integer, "
732 + AttachmentColumns.LOCATION + " text, "
Andrew Stadler3aaba9e2010-02-22 12:57:33 -0800733 + AttachmentColumns.ENCODING + " text, "
734 + AttachmentColumns.CONTENT + " text, "
Makoto Onuki20225d52010-03-12 13:30:26 -0800735 + AttachmentColumns.FLAGS + " integer, "
Marc Blank75a873b2010-12-08 17:11:04 -0800736 + AttachmentColumns.CONTENT_BYTES + " blob, "
737 + AttachmentColumns.ACCOUNT_KEY + " integer"
Marc Blanka290f502009-06-15 14:40:06 -0700738 + ");";
739 db.execSQL("create table " + Attachment.TABLE_NAME + s);
Mihai Preda9627d012009-08-12 12:51:26 +0200740 db.execSQL(createIndex(Attachment.TABLE_NAME, AttachmentColumns.MESSAGE_KEY));
Marc Blanka290f502009-06-15 14:40:06 -0700741 }
742
Marc Blanke7e1ca42009-09-15 19:27:05 -0700743 static void resetAttachmentTable(SQLiteDatabase db, int oldVersion, int newVersion) {
Marc Blanka290f502009-06-15 14:40:06 -0700744 try {
745 db.execSQL("drop table " + Attachment.TABLE_NAME);
746 } catch (SQLException e) {
747 }
748 createAttachmentTable(db);
749 }
750
Jorge Lugo5a3888f2011-06-01 10:09:26 -0700751 static void createQuickResponseTable(SQLiteDatabase db) {
752 String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
753 + QuickResponseColumns.TEXT + " text, "
754 + QuickResponseColumns.ACCOUNT_KEY + " integer"
755 + ");";
756 db.execSQL("create table " + QuickResponse.TABLE_NAME + s);
757 }
758
Marc Blanka290f502009-06-15 14:40:06 -0700759 static void createBodyTable(SQLiteDatabase db) {
Marc Blank758a5322009-07-30 11:41:31 -0700760 String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
Marc Blanka290f502009-06-15 14:40:06 -0700761 + BodyColumns.MESSAGE_KEY + " integer, "
762 + BodyColumns.HTML_CONTENT + " text, "
Andrew Stadler936babc2009-09-01 23:19:12 -0700763 + BodyColumns.TEXT_CONTENT + " text, "
764 + BodyColumns.HTML_REPLY + " text, "
Marc Blanke2569832009-09-07 16:03:02 -0700765 + BodyColumns.TEXT_REPLY + " text, "
Marc Blank5fc57ec2009-09-22 18:38:28 -0700766 + BodyColumns.SOURCE_MESSAGE_KEY + " text, "
767 + BodyColumns.INTRO_TEXT + " text"
Marc Blanka290f502009-06-15 14:40:06 -0700768 + ");";
769 db.execSQL("create table " + Body.TABLE_NAME + s);
Mihai Preda9627d012009-08-12 12:51:26 +0200770 db.execSQL(createIndex(Body.TABLE_NAME, BodyColumns.MESSAGE_KEY));
Marc Blanka290f502009-06-15 14:40:06 -0700771 }
772
773 static void upgradeBodyTable(SQLiteDatabase db, int oldVersion, int newVersion) {
Marc Blank657de3b2009-09-18 20:44:26 -0700774 if (oldVersion < 5) {
Marc Blanke2569832009-09-07 16:03:02 -0700775 try {
776 db.execSQL("drop table " + Body.TABLE_NAME);
777 createBodyTable(db);
778 } catch (SQLException e) {
779 }
Marc Blank5fc57ec2009-09-22 18:38:28 -0700780 } else if (oldVersion == 5) {
781 try {
782 db.execSQL("alter table " + Body.TABLE_NAME
783 + " add " + BodyColumns.INTRO_TEXT + " text");
784 } catch (SQLException e) {
785 // Shouldn't be needed unless we're debugging and interrupt the process
786 Log.w(TAG, "Exception upgrading EmailProviderBody.db from v5 to v6", e);
787 }
788 oldVersion = 6;
Marc Blanke7e1ca42009-09-15 19:27:05 -0700789 }
Andrew Stadlerf3d5b202009-05-26 16:40:34 -0700790 }
791
Marc Blanka290f502009-06-15 14:40:06 -0700792 private SQLiteDatabase mDatabase;
793 private SQLiteDatabase mBodyDatabase;
Marc Blankf3743042009-06-27 12:14:14 -0700794
Marc Blank2bdf7ee2011-06-30 16:03:36 -0700795 /**
796 * Orphan record deletion utility. Generates a sqlite statement like:
797 * delete from <table> where <column> not in (select <foreignColumn> from <foreignTable>)
798 * @param db the EmailProvider database
799 * @param table the table whose orphans are to be removed
800 * @param column the column deletion will be based on
801 * @param foreignColumn the column in the foreign table whose absence will trigger the deletion
802 * @param foreignTable the foreign table
803 */
804 @VisibleForTesting
805 void deleteUnlinked(SQLiteDatabase db, String table, String column, String foreignColumn,
806 String foreignTable) {
807 int count = db.delete(table, column + " not in (select " + foreignColumn + " from " +
808 foreignTable + ")", null);
809 if (count > 0) {
810 Log.w(TAG, "Found " + count + " orphaned row(s) in " + table);
811 }
812 }
813
Makoto Onuki9dad9ad2011-06-20 18:10:10 -0700814 @VisibleForTesting
815 synchronized SQLiteDatabase getDatabase(Context context) {
Marc Blank0e1595c2009-11-18 17:11:33 -0800816 // Always return the cached database, if we've got one
817 if (mDatabase != null) {
Marc Blanka290f502009-06-15 14:40:06 -0700818 return mDatabase;
819 }
Marc Blank0e1595c2009-11-18 17:11:33 -0800820
821 // Whenever we create or re-cache the databases, make sure that we haven't lost one
822 // to corruption
823 checkDatabases();
824
Marc Blanka290f502009-06-15 14:40:06 -0700825 DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
826 mDatabase = helper.getWritableDatabase();
Makoto Onuki369905c2011-06-20 19:57:56 -0700827 mDatabase.setLockingEnabled(true);
828 BodyDatabaseHelper bodyHelper = new BodyDatabaseHelper(context, BODY_DATABASE_NAME);
829 mBodyDatabase = bodyHelper.getWritableDatabase();
830 if (mBodyDatabase != null) {
831 mBodyDatabase.setLockingEnabled(true);
832 String bodyFileName = mBodyDatabase.getPath();
833 mDatabase.execSQL("attach \"" + bodyFileName + "\" as BodyDatabase");
Marc Blanka290f502009-06-15 14:40:06 -0700834 }
Marc Blankef832992009-10-13 16:25:00 -0700835
Makoto Onuki369905c2011-06-20 19:57:56 -0700836 // Restore accounts if the database is corrupted...
837 restoreIfNeeded(context, mDatabase);
838
Marc Blank2bdf7ee2011-06-30 16:03:36 -0700839 if (Email.DEBUG) {
840 Log.d(TAG, "Deleting orphans...");
841 }
Marc Blankef832992009-10-13 16:25:00 -0700842 // Check for any orphaned Messages in the updated/deleted tables
Marc Blank2bdf7ee2011-06-30 16:03:36 -0700843 deleteMessageOrphans(mDatabase, Message.UPDATED_TABLE_NAME);
844 deleteMessageOrphans(mDatabase, Message.DELETED_TABLE_NAME);
845 // Delete orphaned mailboxes/messages/policies (account no longer exists)
846 deleteUnlinked(mDatabase, Mailbox.TABLE_NAME, MailboxColumns.ACCOUNT_KEY, AccountColumns.ID,
847 Account.TABLE_NAME);
848 deleteUnlinked(mDatabase, Message.TABLE_NAME, MessageColumns.ACCOUNT_KEY, AccountColumns.ID,
849 Account.TABLE_NAME);
850 deleteUnlinked(mDatabase, Policy.TABLE_NAME, PolicyColumns.ID, AccountColumns.POLICY_KEY,
851 Account.TABLE_NAME);
852
Marc Blank6e418aa2011-06-18 18:03:11 -0700853 if (Email.DEBUG) {
854 Log.d(TAG, "EmailProvider pre-caching...");
855 }
856 preCacheData();
857 if (Email.DEBUG) {
Marc Blank2bdf7ee2011-06-30 16:03:36 -0700858 Log.d(TAG, "EmailProvider ready.");
Marc Blank6e418aa2011-06-18 18:03:11 -0700859 }
Marc Blanka290f502009-06-15 14:40:06 -0700860 return mDatabase;
861 }
862
Marc Blank6e418aa2011-06-18 18:03:11 -0700863 /**
864 * Pre-cache all of the items in a given table meeting the selection criteria
865 * @param tableUri the table uri
866 * @param baseProjection the base projection of that table
867 * @param selection the selection criteria
868 */
869 private void preCacheTable(Uri tableUri, String[] baseProjection, String selection) {
870 Cursor c = query(tableUri, EmailContent.ID_PROJECTION, selection, null, null);
871 try {
872 while (c.moveToNext()) {
873 long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN);
874 Cursor cachedCursor = query(ContentUris.withAppendedId(
875 tableUri, id), baseProjection, null, null, null);
876 if (cachedCursor != null) {
877 // For accounts, create a mailbox type map entry (if necessary)
878 if (tableUri == Account.CONTENT_URI) {
879 getOrCreateAccountMailboxTypeMap(id);
880 }
881 cachedCursor.close();
882 }
883 }
884 } finally {
885 c.close();
886 }
887 }
888
Marc Blank5d7ff852011-06-27 20:11:24 -0700889 private final HashMap<Long, HashMap<Integer, Long>> mMailboxTypeMap =
Marc Blank6e418aa2011-06-18 18:03:11 -0700890 new HashMap<Long, HashMap<Integer, Long>>();
891
Marc Blank5d7ff852011-06-27 20:11:24 -0700892 private HashMap<Integer, Long> getOrCreateAccountMailboxTypeMap(long accountId) {
893 synchronized(mMailboxTypeMap) {
894 HashMap<Integer, Long> accountMailboxTypeMap = mMailboxTypeMap.get(accountId);
895 if (accountMailboxTypeMap == null) {
896 accountMailboxTypeMap = new HashMap<Integer, Long>();
897 mMailboxTypeMap.put(accountId, accountMailboxTypeMap);
898 }
899 return accountMailboxTypeMap;
Marc Blank6e418aa2011-06-18 18:03:11 -0700900 }
Marc Blank6e418aa2011-06-18 18:03:11 -0700901 }
902
Marc Blank5d7ff852011-06-27 20:11:24 -0700903 private void addToMailboxTypeMap(Cursor c) {
Marc Blank6e418aa2011-06-18 18:03:11 -0700904 long accountId = c.getLong(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN);
905 int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
Marc Blank5d7ff852011-06-27 20:11:24 -0700906 synchronized(mMailboxTypeMap) {
907 HashMap<Integer, Long> accountMailboxTypeMap =
908 getOrCreateAccountMailboxTypeMap(accountId);
909 accountMailboxTypeMap.put(type, c.getLong(Mailbox.CONTENT_ID_COLUMN));
910 }
911 }
912
913 private long getMailboxIdFromMailboxTypeMap(long accountId, int type) {
914 synchronized(mMailboxTypeMap) {
915 HashMap<Integer, Long> accountMap = mMailboxTypeMap.get(accountId);
Marc Blankc0a9fa92011-06-28 10:58:22 -0700916 Long mailboxId = null;
Marc Blank5d7ff852011-06-27 20:11:24 -0700917 if (accountMap != null) {
918 mailboxId = accountMap.get(type);
919 }
Marc Blankc0a9fa92011-06-28 10:58:22 -0700920 if (mailboxId == null) return Mailbox.NO_MAILBOX;
Marc Blank5d7ff852011-06-27 20:11:24 -0700921 return mailboxId;
922 }
Marc Blank6e418aa2011-06-18 18:03:11 -0700923 }
924
925 private void preCacheData() {
Marc Blank5d7ff852011-06-27 20:11:24 -0700926 synchronized(mMailboxTypeMap) {
927 mMailboxTypeMap.clear();
Marc Blank6e418aa2011-06-18 18:03:11 -0700928
Marc Blank5d7ff852011-06-27 20:11:24 -0700929 // Pre-cache accounts, host auth's, policies, and special mailboxes
930 preCacheTable(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null);
931 preCacheTable(HostAuth.CONTENT_URI, HostAuth.CONTENT_PROJECTION, null);
932 preCacheTable(Policy.CONTENT_URI, Policy.CONTENT_PROJECTION, null);
933 preCacheTable(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
934 MAILBOX_PRE_CACHE_SELECTION);
Marc Blank6e418aa2011-06-18 18:03:11 -0700935
Marc Blank5d7ff852011-06-27 20:11:24 -0700936 // Create a map from account,type to a mailbox
937 Map<String, Cursor> snapshot = mCacheMailbox.getSnapshot();
938 Collection<Cursor> values = snapshot.values();
939 if (values != null) {
940 for (Cursor c: values) {
941 if (c.moveToFirst()) {
942 addToMailboxTypeMap(c);
943 }
944 }
Marc Blank6e418aa2011-06-18 18:03:11 -0700945 }
946 }
947 }
948
Marc Blankef832992009-10-13 16:25:00 -0700949 /*package*/ static SQLiteDatabase getReadableDatabase(Context context) {
Makoto Onuki9dad9ad2011-06-20 18:10:10 -0700950 DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
Marc Blankef832992009-10-13 16:25:00 -0700951 return helper.getReadableDatabase();
952 }
953
Makoto Onuki9dad9ad2011-06-20 18:10:10 -0700954 /**
955 * Restore user Account and HostAuth data from our backup database
956 */
957 public static void restoreIfNeeded(Context context, SQLiteDatabase mainDatabase) {
958 if (Email.DEBUG) {
959 Log.w(TAG, "restoreIfNeeded...");
960 }
961 // Check for legacy backup
962 String legacyBackup = Preferences.getLegacyBackupPreference(context);
963 // If there's a legacy backup, create a new-style backup and delete the legacy backup
964 // In the 1:1000000000 chance that the user gets an app update just as his database becomes
965 // corrupt, oh well...
966 if (!TextUtils.isEmpty(legacyBackup)) {
967 backupAccounts(context, mainDatabase);
968 Preferences.clearLegacyBackupPreference(context);
969 Log.w(TAG, "Created new EmailProvider backup database");
970 return;
971 }
972
973 // If we have accounts, we're done
974 Cursor c = mainDatabase.query(Account.TABLE_NAME, EmailContent.ID_PROJECTION, null, null,
975 null, null, null);
976 if (c.moveToFirst()) {
977 if (Email.DEBUG) {
978 Log.w(TAG, "restoreIfNeeded: Account exists.");
979 }
980 return; // At least one account exists.
981 }
982 restoreAccounts(context, mainDatabase);
983 }
984
Makoto Onuki6c36b4c2010-08-20 14:56:44 -0700985 /** {@inheritDoc} */
986 @Override
987 public void shutdown() {
988 if (mDatabase != null) {
989 mDatabase.close();
990 mDatabase = null;
991 }
992 if (mBodyDatabase != null) {
993 mBodyDatabase.close();
994 mBodyDatabase = null;
995 }
996 }
997
Marc Blank2bdf7ee2011-06-30 16:03:36 -0700998 /*package*/ static void deleteMessageOrphans(SQLiteDatabase database, String tableName) {
Marc Blankef832992009-10-13 16:25:00 -0700999 if (database != null) {
1000 // We'll look at all of the items in the table; there won't be many typically
1001 Cursor c = database.query(tableName, ORPHANS_PROJECTION, null, null, null, null, null);
1002 // Usually, there will be nothing in these tables, so make a quick check
1003 try {
1004 if (c.getCount() == 0) return;
1005 ArrayList<Long> foundMailboxes = new ArrayList<Long>();
1006 ArrayList<Long> notFoundMailboxes = new ArrayList<Long>();
1007 ArrayList<Long> deleteList = new ArrayList<Long>();
1008 String[] bindArray = new String[1];
1009 while (c.moveToNext()) {
1010 // Get the mailbox key and see if we've already found this mailbox
1011 // If so, we're fine
1012 long mailboxId = c.getLong(ORPHANS_MAILBOX_KEY);
1013 // If we already know this mailbox doesn't exist, mark the message for deletion
1014 if (notFoundMailboxes.contains(mailboxId)) {
1015 deleteList.add(c.getLong(ORPHANS_ID));
1016 // If we don't know about this mailbox, we'll try to find it
1017 } else if (!foundMailboxes.contains(mailboxId)) {
1018 bindArray[0] = Long.toString(mailboxId);
1019 Cursor boxCursor = database.query(Mailbox.TABLE_NAME,
1020 Mailbox.ID_PROJECTION, WHERE_ID, bindArray, null, null, null);
1021 try {
1022 // If it exists, we'll add it to the "found" mailboxes
1023 if (boxCursor.moveToFirst()) {
1024 foundMailboxes.add(mailboxId);
1025 // Otherwise, we'll add to "not found" and mark the message for deletion
1026 } else {
1027 notFoundMailboxes.add(mailboxId);
1028 deleteList.add(c.getLong(ORPHANS_ID));
1029 }
1030 } finally {
1031 boxCursor.close();
1032 }
1033 }
1034 }
1035 // Now, delete the orphan messages
1036 for (long messageId: deleteList) {
1037 bindArray[0] = Long.toString(messageId);
1038 database.delete(tableName, WHERE_ID, bindArray);
1039 }
1040 } finally {
1041 c.close();
1042 }
1043 }
1044 }
1045
Marc Blanka290f502009-06-15 14:40:06 -07001046 private class BodyDatabaseHelper extends SQLiteOpenHelper {
1047 BodyDatabaseHelper(Context context, String name) {
Andrew Stadler0d008892009-09-22 18:31:10 -07001048 super(context, name, null, BODY_DATABASE_VERSION);
Marc Blanka290f502009-06-15 14:40:06 -07001049 }
1050
1051 @Override
1052 public void onCreate(SQLiteDatabase db) {
Marc Blank0e1595c2009-11-18 17:11:33 -08001053 Log.d(TAG, "Creating EmailProviderBody database");
Marc Blanka290f502009-06-15 14:40:06 -07001054 createBodyTable(db);
1055 }
1056
1057 @Override
1058 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1059 upgradeBodyTable(db, oldVersion, newVersion);
1060 }
1061
1062 @Override
1063 public void onOpen(SQLiteDatabase db) {
1064 }
1065 }
Marc Blankf3743042009-06-27 12:14:14 -07001066
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07001067 private static class DatabaseHelper extends SQLiteOpenHelper {
Marc Blanke7e1ca42009-09-15 19:27:05 -07001068 Context mContext;
1069
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001070 DatabaseHelper(Context context, String name) {
Andrew Stadler0d008892009-09-22 18:31:10 -07001071 super(context, name, null, DATABASE_VERSION);
Marc Blanke7e1ca42009-09-15 19:27:05 -07001072 mContext = context;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001073 }
1074
1075 @Override
1076 public void onCreate(SQLiteDatabase db) {
Marc Blank0e1595c2009-11-18 17:11:33 -08001077 Log.d(TAG, "Creating EmailProvider database");
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001078 // Create all tables here; each class has its own method
Marc Blanka290f502009-06-15 14:40:06 -07001079 createMessageTable(db);
1080 createAttachmentTable(db);
1081 createMailboxTable(db);
1082 createHostAuthTable(db);
1083 createAccountTable(db);
Marc Blankaeee10e2011-04-27 17:12:06 -07001084 createPolicyTable(db);
Jorge Lugo5a3888f2011-06-01 10:09:26 -07001085 createQuickResponseTable(db);
Marc Blankf3743042009-06-27 12:14:14 -07001086 }
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001087
1088 @Override
Todd Kennedybf30f942011-05-06 11:31:10 -07001089 @SuppressWarnings("deprecation")
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001090 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Marc Blank657de3b2009-09-18 20:44:26 -07001091 // For versions prior to 5, delete all data
1092 // Versions >= 5 require that data be preserved!
1093 if (oldVersion < 5) {
Makoto Onukifaed6172010-02-01 15:34:03 -08001094 android.accounts.Account[] accounts = AccountManager.get(mContext)
Marc Blank3a5c1fb2011-02-12 18:56:09 -08001095 .getAccountsByType(AccountManagerTypes.TYPE_EXCHANGE);
Marc Blanke7e1ca42009-09-15 19:27:05 -07001096 for (android.accounts.Account account: accounts) {
1097 AccountManager.get(mContext).removeAccount(account, null, null);
1098 }
1099 resetMessageTable(db, oldVersion, newVersion);
1100 resetAttachmentTable(db, oldVersion, newVersion);
1101 resetMailboxTable(db, oldVersion, newVersion);
1102 resetHostAuthTable(db, oldVersion, newVersion);
1103 resetAccountTable(db, oldVersion, newVersion);
Andrew Stadler0d008892009-09-22 18:31:10 -07001104 return;
1105 }
1106 if (oldVersion == 5) {
1107 // Message Tables: Add SyncColumns.SERVER_TIMESTAMP
Marc Blank5fc57ec2009-09-22 18:38:28 -07001108 try {
1109 db.execSQL("alter table " + Message.TABLE_NAME
1110 + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1111 db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1112 + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1113 db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1114 + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1115 } catch (SQLException e) {
1116 // Shouldn't be needed unless we're debugging and interrupt the process
1117 Log.w(TAG, "Exception upgrading EmailProvider.db from v5 to v6", e);
1118 }
Andrew Stadler0d008892009-09-22 18:31:10 -07001119 oldVersion = 6;
Marc Blanke7e1ca42009-09-15 19:27:05 -07001120 }
Marc Blankef832992009-10-13 16:25:00 -07001121 if (oldVersion == 6) {
1122 // Use the newer mailbox_delete trigger
Marc Blank36796362009-10-19 22:15:45 -07001123 db.execSQL("drop trigger mailbox_delete;");
Marc Blankef832992009-10-13 16:25:00 -07001124 db.execSQL(TRIGGER_MAILBOX_DELETE);
1125 oldVersion = 7;
1126 }
Andrew Stadlerfc8d9432010-01-21 11:48:02 -08001127 if (oldVersion == 7) {
1128 // add the security (provisioning) column
1129 try {
1130 db.execSQL("alter table " + Account.TABLE_NAME
1131 + " add column " + AccountColumns.SECURITY_FLAGS + " integer" + ";");
1132 } catch (SQLException e) {
1133 // Shouldn't be needed unless we're debugging and interrupt the process
1134 Log.w(TAG, "Exception upgrading EmailProvider.db from 7 to 8 " + e);
1135 }
1136 oldVersion = 8;
1137 }
Andrew Stadler345fb8b2010-01-26 17:24:15 -08001138 if (oldVersion == 8) {
1139 // accounts: add security sync key & user signature columns
1140 try {
1141 db.execSQL("alter table " + Account.TABLE_NAME
1142 + " add column " + AccountColumns.SECURITY_SYNC_KEY + " text" + ";");
1143 db.execSQL("alter table " + Account.TABLE_NAME
1144 + " add column " + AccountColumns.SIGNATURE + " text" + ";");
1145 } catch (SQLException e) {
1146 // Shouldn't be needed unless we're debugging and interrupt the process
1147 Log.w(TAG, "Exception upgrading EmailProvider.db from 8 to 9 " + e);
1148 }
1149 oldVersion = 9;
1150 }
Marc Blank4006e5f2010-02-15 16:01:38 -08001151 if (oldVersion == 9) {
1152 // Message: add meeting info column into Message tables
1153 try {
1154 db.execSQL("alter table " + Message.TABLE_NAME
1155 + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1156 db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1157 + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1158 db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1159 + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1160 } catch (SQLException e) {
1161 // Shouldn't be needed unless we're debugging and interrupt the process
1162 Log.w(TAG, "Exception upgrading EmailProvider.db from 9 to 10 " + e);
1163 }
1164 oldVersion = 10;
1165 }
Andrew Stadler3aaba9e2010-02-22 12:57:33 -08001166 if (oldVersion == 10) {
1167 // Attachment: add content and flags columns
1168 try {
1169 db.execSQL("alter table " + Attachment.TABLE_NAME
1170 + " add column " + AttachmentColumns.CONTENT + " text" + ";");
1171 db.execSQL("alter table " + Attachment.TABLE_NAME
1172 + " add column " + AttachmentColumns.FLAGS + " integer" + ";");
1173 } catch (SQLException e) {
1174 // Shouldn't be needed unless we're debugging and interrupt the process
1175 Log.w(TAG, "Exception upgrading EmailProvider.db from 10 to 11 " + e);
1176 }
1177 oldVersion = 11;
1178 }
Makoto Onuki20225d52010-03-12 13:30:26 -08001179 if (oldVersion == 11) {
1180 // Attachment: add content_bytes
1181 try {
1182 db.execSQL("alter table " + Attachment.TABLE_NAME
1183 + " add column " + AttachmentColumns.CONTENT_BYTES + " blob" + ";");
1184 } catch (SQLException e) {
1185 // Shouldn't be needed unless we're debugging and interrupt the process
1186 Log.w(TAG, "Exception upgrading EmailProvider.db from 11 to 12 " + e);
1187 }
1188 oldVersion = 12;
1189 }
Makoto Onuki574854b2010-07-30 13:53:59 -07001190 if (oldVersion == 12) {
1191 try {
1192 db.execSQL("alter table " + Mailbox.TABLE_NAME
1193 + " add column " + Mailbox.MESSAGE_COUNT
1194 +" integer not null default 0" + ";");
1195 recalculateMessageCount(db);
1196 } catch (SQLException e) {
1197 // Shouldn't be needed unless we're debugging and interrupt the process
1198 Log.w(TAG, "Exception upgrading EmailProvider.db from 12 to 13 " + e);
1199 }
1200 oldVersion = 13;
1201 }
Marc Blanke7b9e4a2010-09-01 19:06:15 -07001202 if (oldVersion == 13) {
1203 try {
1204 db.execSQL("alter table " + Message.TABLE_NAME
1205 + " add column " + Message.SNIPPET
1206 +" text" + ";");
1207 } catch (SQLException e) {
1208 // Shouldn't be needed unless we're debugging and interrupt the process
1209 Log.w(TAG, "Exception upgrading EmailProvider.db from 13 to 14 " + e);
1210 }
1211 oldVersion = 14;
1212 }
Makoto Onukiddc8dea2010-09-07 12:36:48 -07001213 if (oldVersion == 14) {
1214 try {
1215 db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1216 + " add column " + Message.SNIPPET +" text" + ";");
1217 db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1218 + " add column " + Message.SNIPPET +" text" + ";");
1219 } catch (SQLException e) {
1220 // Shouldn't be needed unless we're debugging and interrupt the process
1221 Log.w(TAG, "Exception upgrading EmailProvider.db from 14 to 15 " + e);
1222 }
1223 oldVersion = 15;
1224 }
Marc Blank75a873b2010-12-08 17:11:04 -08001225 if (oldVersion == 15) {
1226 try {
1227 db.execSQL("alter table " + Attachment.TABLE_NAME
1228 + " add column " + Attachment.ACCOUNT_KEY +" integer" + ";");
1229 // Update all existing attachments to add the accountKey data
1230 db.execSQL("update " + Attachment.TABLE_NAME + " set " +
1231 Attachment.ACCOUNT_KEY + "= (SELECT " + Message.TABLE_NAME + "." +
1232 Message.ACCOUNT_KEY + " from " + Message.TABLE_NAME + " where " +
1233 Message.TABLE_NAME + "." + Message.RECORD_ID + " = " +
1234 Attachment.TABLE_NAME + "." + Attachment.MESSAGE_KEY + ")");
1235 } catch (SQLException e) {
1236 // Shouldn't be needed unless we're debugging and interrupt the process
1237 Log.w(TAG, "Exception upgrading EmailProvider.db from 15 to 16 " + e);
1238 }
1239 oldVersion = 16;
1240 }
Andy Stadler3a585092011-03-01 10:45:50 -08001241 if (oldVersion == 16) {
1242 try {
1243 db.execSQL("alter table " + Mailbox.TABLE_NAME
1244 + " add column " + Mailbox.PARENT_KEY + " integer;");
1245 } catch (SQLException e) {
1246 // Shouldn't be needed unless we're debugging and interrupt the process
1247 Log.w(TAG, "Exception upgrading EmailProvider.db from 16 to 17 " + e);
1248 }
1249 oldVersion = 17;
1250 }
Todd Kennedy22208772011-04-22 15:45:11 -07001251 if (oldVersion == 17) {
1252 upgradeFromVersion17ToVersion18(db);
1253 oldVersion = 18;
1254 }
Marc Blankaeee10e2011-04-27 17:12:06 -07001255 if (oldVersion == 18) {
Marc Blankaeee10e2011-04-27 17:12:06 -07001256 try {
1257 db.execSQL("alter table " + Account.TABLE_NAME
1258 + " add column " + Account.POLICY_KEY + " integer;");
1259 db.execSQL("drop trigger account_delete;");
1260 db.execSQL(TRIGGER_ACCOUNT_DELETE);
1261 createPolicyTable(db);
1262 convertPolicyFlagsToPolicyTable(db);
1263 } catch (SQLException e) {
1264 // Shouldn't be needed unless we're debugging and interrupt the process
1265 Log.w(TAG, "Exception upgrading EmailProvider.db from 18 to 19 " + e);
1266 }
1267 oldVersion = 19;
1268 }
Marc Blankf91a03f2011-05-05 10:34:29 -07001269 if (oldVersion == 19) {
1270 try {
1271 db.execSQL("alter table " + Policy.TABLE_NAME
1272 + " add column " + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING +
1273 " integer;");
1274 db.execSQL("alter table " + Policy.TABLE_NAME
1275 + " add column " + PolicyColumns.DONT_ALLOW_CAMERA + " integer;");
1276 db.execSQL("alter table " + Policy.TABLE_NAME
1277 + " add column " + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer;");
1278 db.execSQL("alter table " + Policy.TABLE_NAME
1279 + " add column " + PolicyColumns.DONT_ALLOW_HTML + " integer;");
1280 db.execSQL("alter table " + Policy.TABLE_NAME
1281 + " add column " + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer;");
1282 db.execSQL("alter table " + Policy.TABLE_NAME
1283 + " add column " + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE +
1284 " integer;");
1285 db.execSQL("alter table " + Policy.TABLE_NAME
1286 + " add column " + PolicyColumns.MAX_HTML_TRUNCATION_SIZE +
1287 " integer;");
1288 db.execSQL("alter table " + Policy.TABLE_NAME
1289 + " add column " + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer;");
1290 db.execSQL("alter table " + Policy.TABLE_NAME
1291 + " add column " + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer;");
1292 db.execSQL("alter table " + Policy.TABLE_NAME
1293 + " add column " + PolicyColumns.PASSWORD_RECOVERY_ENABLED +
1294 " integer;");
1295 } catch (SQLException e) {
1296 // Shouldn't be needed unless we're debugging and interrupt the process
Todd Kennedya9ac20b2011-05-06 13:37:02 -07001297 Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " + e);
Marc Blankf91a03f2011-05-05 10:34:29 -07001298 }
1299 oldVersion = 20;
1300 }
Todd Kennedya9ac20b2011-05-06 13:37:02 -07001301 if (oldVersion == 20) {
1302 upgradeFromVersion20ToVersion21(db);
1303 oldVersion = 21;
1304 }
Marc Blankf3ff0ba2011-05-19 14:14:14 -07001305 if (oldVersion == 21) {
1306 upgradeFromVersion21ToVersion22(db, mContext);
1307 oldVersion = 22;
1308 }
Todd Kennedy9dcb72e2011-06-03 08:51:25 -07001309 if (oldVersion == 22) {
1310 upgradeFromVersion22ToVersion23(db);
1311 oldVersion = 23;
1312 }
Ben Komalo313586c2011-06-07 11:39:16 -07001313 if (oldVersion == 23) {
1314 upgradeFromVersion23ToVersion24(db);
1315 oldVersion = 24;
1316 }
Jorge Lugo5a3888f2011-06-01 10:09:26 -07001317 if (oldVersion == 24) {
1318 upgradeFromVersion24ToVersion25(db);
1319 oldVersion = 25;
1320 }
Marc Blankdeb345a2011-06-23 10:22:25 -07001321 if (oldVersion == 25) {
1322 upgradeFromVersion25ToVersion26(db);
1323 oldVersion = 26;
1324 }
Marc Blank9a013532011-06-23 10:52:21 -07001325 if (oldVersion == 26) {
1326 try {
1327 db.execSQL("alter table " + Message.TABLE_NAME
1328 + " add column " + Message.PROTOCOL_SEARCH_INFO + " text;");
1329 db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1330 + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
1331 db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1332 + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
1333 } catch (SQLException e) {
1334 // Shouldn't be needed unless we're debugging and interrupt the process
1335 Log.w(TAG, "Exception upgrading EmailProvider.db from 26 to 27 " + e);
1336 }
1337 oldVersion = 27;
1338 }
Marc Blankaca94262011-07-19 18:19:59 -07001339 if (oldVersion == 27) {
1340 try {
1341 db.execSQL("alter table " + Account.TABLE_NAME
1342 + " add column " + Account.NOTIFIED_MESSAGE_ID + " integer;");
1343 db.execSQL("alter table " + Account.TABLE_NAME
1344 + " add column " + Account.NOTIFIED_MESSAGE_COUNT + " integer;");
1345 } catch (SQLException e) {
1346 // Shouldn't be needed unless we're debugging and interrupt the process
Marc Blank2736c1a2011-10-20 10:13:02 -07001347 Log.w(TAG, "Exception upgrading EmailProvider.db from 27 to 28 " + e);
Marc Blankaca94262011-07-19 18:19:59 -07001348 }
1349 oldVersion = 28;
1350 }
Marc Blank2736c1a2011-10-20 10:13:02 -07001351 if (oldVersion == 28) {
1352 try {
1353 db.execSQL("alter table " + Policy.TABLE_NAME
1354 + " add column " + Policy.PROTOCOL_POLICIES_ENFORCED + " text;");
1355 db.execSQL("alter table " + Policy.TABLE_NAME
1356 + " add column " + Policy.PROTOCOL_POLICIES_UNSUPPORTED + " text;");
1357 } catch (SQLException e) {
1358 // Shouldn't be needed unless we're debugging and interrupt the process
1359 Log.w(TAG, "Exception upgrading EmailProvider.db from 28 to 29 " + e);
1360 }
1361 oldVersion = 29;
1362 }
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001363 }
1364
1365 @Override
1366 public void onOpen(SQLiteDatabase db) {
1367 }
1368 }
1369
1370 @Override
1371 public int delete(Uri uri, String selection, String[] selectionArgs) {
Marc Blanke6a22df2010-12-16 12:28:16 -08001372 final int match = findMatch(uri, "delete");
Marc Blanka290f502009-06-15 14:40:06 -07001373 Context context = getContext();
Marc Blankcba3a482009-08-05 17:31:50 -07001374 // Pick the correct database for this operation
1375 // If we're in a transaction already (which would happen during applyBatch), then the
1376 // body database is already attached to the email database and any attempt to use the
1377 // body database directly will result in a SQLiteException (the database is locked)
Marc Blanka867ebb2009-08-18 11:44:27 -07001378 SQLiteDatabase db = getDatabase(context);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001379 int table = match >> BASE_SHIFT;
Marc Blank2c67f1f2009-06-16 12:03:45 -07001380 String id = "0";
Marc Blankcba3a482009-08-05 17:31:50 -07001381 boolean messageDeletion = false;
Marc Blank1b9337e2010-09-23 09:19:44 -07001382 ContentResolver resolver = context.getContentResolver();
Marc Blankf3743042009-06-27 12:14:14 -07001383
Marc Blank6e418aa2011-06-18 18:03:11 -07001384 ContentCache cache = mContentCaches[table];
Marc Blankfab77f12010-10-27 16:50:54 -07001385 String tableName = TABLE_NAMES[table];
Marc Blankb6493a02009-07-05 12:54:49 -07001386 int result = -1;
Marc Blankf3743042009-06-27 12:14:14 -07001387
Marc Blank2c67f1f2009-06-16 12:03:45 -07001388 try {
1389 switch (match) {
1390 // These are cases in which one or more Messages might get deleted, either by
1391 // cascade or explicitly
1392 case MAILBOX_ID:
1393 case MAILBOX:
1394 case ACCOUNT_ID:
1395 case ACCOUNT:
1396 case MESSAGE:
Marc Blankf3743042009-06-27 12:14:14 -07001397 case SYNCED_MESSAGE_ID:
Marc Blank2c67f1f2009-06-16 12:03:45 -07001398 case MESSAGE_ID:
1399 // Handle lost Body records here, since this cannot be done in a trigger
1400 // The process is:
Marc Blanka867ebb2009-08-18 11:44:27 -07001401 // 1) Begin a transaction, ensuring that both databases are affected atomically
1402 // 2) Do the requested deletion, with cascading deletions handled in triggers
1403 // 3) End the transaction, committing all changes atomically
Andrew Stadler6c219422009-09-10 11:52:36 -07001404 //
1405 // Bodies are auto-deleted here; Attachments are auto-deleted via trigger
Marc Blankcba3a482009-08-05 17:31:50 -07001406 messageDeletion = true;
Marc Blank8587aa62009-09-18 20:36:15 -07001407 db.beginTransaction();
Marc Blank2c67f1f2009-06-16 12:03:45 -07001408 break;
1409 }
1410 switch (match) {
1411 case BODY_ID:
Marc Blankf3743042009-06-27 12:14:14 -07001412 case DELETED_MESSAGE_ID:
1413 case SYNCED_MESSAGE_ID:
Marc Blank2c67f1f2009-06-16 12:03:45 -07001414 case MESSAGE_ID:
1415 case UPDATED_MESSAGE_ID:
1416 case ATTACHMENT_ID:
1417 case MAILBOX_ID:
1418 case ACCOUNT_ID:
1419 case HOSTAUTH_ID:
Marc Blankaeee10e2011-04-27 17:12:06 -07001420 case POLICY_ID:
Jorge Lugo5a3888f2011-06-01 10:09:26 -07001421 case QUICK_RESPONSE_ID:
Marc Blank2c67f1f2009-06-16 12:03:45 -07001422 id = uri.getPathSegments().get(1);
Marc Blankf3743042009-06-27 12:14:14 -07001423 if (match == SYNCED_MESSAGE_ID) {
1424 // For synced messages, first copy the old message to the deleted table and
1425 // delete it from the updated table (in case it was updated first)
1426 // Note that this is all within a transaction, for atomicity
1427 db.execSQL(DELETED_MESSAGE_INSERT + id);
1428 db.execSQL(UPDATED_MESSAGE_DELETE + id);
1429 }
Marc Blankfab77f12010-10-27 16:50:54 -07001430 if (cache != null) {
1431 cache.lock(id);
1432 }
1433 try {
1434 result = db.delete(tableName, whereWithId(id, selection), selectionArgs);
1435 if (cache != null) {
1436 switch(match) {
1437 case ACCOUNT_ID:
1438 // Account deletion will clear all of the caches, as HostAuth's,
1439 // Mailboxes, and Messages will be deleted in the process
Marc Blank6e418aa2011-06-18 18:03:11 -07001440 mCacheMailbox.invalidate("Delete", uri, selection);
1441 mCacheHostAuth.invalidate("Delete", uri, selection);
1442 mCachePolicy.invalidate("Delete", uri, selection);
Marc Blankfab77f12010-10-27 16:50:54 -07001443 //$FALL-THROUGH$
1444 case MAILBOX_ID:
1445 // Mailbox deletion will clear the Message cache
Marc Blank6e418aa2011-06-18 18:03:11 -07001446 mCacheMessage.invalidate("Delete", uri, selection);
Marc Blankfab77f12010-10-27 16:50:54 -07001447 //$FALL-THROUGH$
1448 case SYNCED_MESSAGE_ID:
1449 case MESSAGE_ID:
1450 case HOSTAUTH_ID:
Marc Blank6e418aa2011-06-18 18:03:11 -07001451 case POLICY_ID:
Marc Blankfab77f12010-10-27 16:50:54 -07001452 cache.invalidate("Delete", uri, selection);
Marc Blank6e418aa2011-06-18 18:03:11 -07001453 // Make sure all data is properly cached
1454 if (match != MESSAGE_ID) {
1455 preCacheData();
1456 }
Marc Blankfab77f12010-10-27 16:50:54 -07001457 break;
1458 }
1459 }
1460 } finally {
1461 if (cache != null) {
1462 cache.unlock(id);
1463 }
Todd Kennedybf30f942011-05-06 11:31:10 -07001464 }
Marc Blank2c67f1f2009-06-16 12:03:45 -07001465 break;
Andrew Stadler6c219422009-09-10 11:52:36 -07001466 case ATTACHMENTS_MESSAGE_ID:
1467 // All attachments for the given message
1468 id = uri.getPathSegments().get(2);
Marc Blankfab77f12010-10-27 16:50:54 -07001469 result = db.delete(tableName,
Andrew Stadler6c219422009-09-10 11:52:36 -07001470 whereWith(Attachment.MESSAGE_KEY + "=" + id, selection), selectionArgs);
1471 break;
1472
Marc Blank2c67f1f2009-06-16 12:03:45 -07001473 case BODY:
1474 case MESSAGE:
Marc Blankf3743042009-06-27 12:14:14 -07001475 case DELETED_MESSAGE:
Marc Blank2c67f1f2009-06-16 12:03:45 -07001476 case UPDATED_MESSAGE:
1477 case ATTACHMENT:
1478 case MAILBOX:
1479 case ACCOUNT:
1480 case HOSTAUTH:
Marc Blankaeee10e2011-04-27 17:12:06 -07001481 case POLICY:
Marc Blankfab77f12010-10-27 16:50:54 -07001482 switch(match) {
1483 // See the comments above for deletion of ACCOUNT_ID, etc
1484 case ACCOUNT:
Marc Blank6e418aa2011-06-18 18:03:11 -07001485 mCacheMailbox.invalidate("Delete", uri, selection);
1486 mCacheHostAuth.invalidate("Delete", uri, selection);
1487 mCachePolicy.invalidate("Delete", uri, selection);
Marc Blankfab77f12010-10-27 16:50:54 -07001488 //$FALL-THROUGH$
1489 case MAILBOX:
Marc Blank6e418aa2011-06-18 18:03:11 -07001490 mCacheMessage.invalidate("Delete", uri, selection);
Marc Blankfab77f12010-10-27 16:50:54 -07001491 //$FALL-THROUGH$
1492 case MESSAGE:
1493 case HOSTAUTH:
Marc Blank6e418aa2011-06-18 18:03:11 -07001494 case POLICY:
Marc Blankfab77f12010-10-27 16:50:54 -07001495 cache.invalidate("Delete", uri, selection);
1496 break;
1497 }
1498 result = db.delete(tableName, selection, selectionArgs);
Marc Blank6e418aa2011-06-18 18:03:11 -07001499 switch(match) {
1500 case ACCOUNT:
1501 case MAILBOX:
1502 case HOSTAUTH:
1503 case POLICY:
1504 // Make sure all data is properly cached
1505 preCacheData();
1506 break;
1507 }
Marc Blank2c67f1f2009-06-16 12:03:45 -07001508 break;
Andrew Stadler6c219422009-09-10 11:52:36 -07001509
Marc Blank2c67f1f2009-06-16 12:03:45 -07001510 default:
1511 throw new IllegalArgumentException("Unknown URI " + uri);
1512 }
Marc Blankcba3a482009-08-05 17:31:50 -07001513 if (messageDeletion) {
Mihai Predafb7974f2009-08-03 15:05:50 +02001514 if (match == MESSAGE_ID) {
Andrew Stadler5f4dbd62009-06-24 12:48:57 -07001515 // Delete the Body record associated with the deleted message
Marc Blankf3743042009-06-27 12:14:14 -07001516 db.execSQL(DELETE_BODY + id);
Mihai Predafb7974f2009-08-03 15:05:50 +02001517 } else {
1518 // Delete any orphaned Body records
1519 db.execSQL(DELETE_ORPHAN_BODIES);
Marc Blankcba3a482009-08-05 17:31:50 -07001520 }
Marc Blank8587aa62009-09-18 20:36:15 -07001521 db.setTransactionSuccessful();
Andrew Stadler5f4dbd62009-06-24 12:48:57 -07001522 }
Marc Blank0e1595c2009-11-18 17:11:33 -08001523 } catch (SQLiteException e) {
1524 checkDatabases();
1525 throw e;
Marc Blank2c67f1f2009-06-16 12:03:45 -07001526 } finally {
Marc Blankcba3a482009-08-05 17:31:50 -07001527 if (messageDeletion) {
Marc Blank8587aa62009-09-18 20:36:15 -07001528 db.endTransaction();
Andrew Stadler5f4dbd62009-06-24 12:48:57 -07001529 }
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001530 }
Makoto Onuki261d6c32010-09-14 16:28:50 -07001531
Todd Kennedybf30f942011-05-06 11:31:10 -07001532 // Notify all notifier cursors
Todd Kennedye7fb4ac2011-05-11 15:29:24 -07001533 sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_DELETE, id);
Todd Kennedybf30f942011-05-06 11:31:10 -07001534
1535 // Notify all email content cursors
Marc Blank1b9337e2010-09-23 09:19:44 -07001536 resolver.notifyChange(EmailContent.CONTENT_URI, null);
Andrew Stadler626f3e42009-06-01 14:34:16 -07001537 return result;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001538 }
1539
1540 @Override
1541 // Use the email- prefix because message, mailbox, and account are so generic (e.g. SMS, IM)
1542 public String getType(Uri uri) {
Marc Blanke6a22df2010-12-16 12:28:16 -08001543 int match = findMatch(uri, "getType");
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001544 switch (match) {
Marc Blanka290f502009-06-15 14:40:06 -07001545 case BODY_ID:
1546 return "vnd.android.cursor.item/email-body";
1547 case BODY:
Marc Blankc81bef62010-10-13 19:04:46 -07001548 return "vnd.android.cursor.dir/email-body";
Marc Blanke34525d2009-06-17 10:22:37 -07001549 case UPDATED_MESSAGE_ID:
Marc Blanka290f502009-06-15 14:40:06 -07001550 case MESSAGE_ID:
Marc Blankc81bef62010-10-13 19:04:46 -07001551 // NOTE: According to the framework folks, we're supposed to invent mime types as
1552 // a way of passing information to drag & drop recipients.
1553 // If there's a mailboxId parameter in the url, we respond with a mime type that
1554 // has -n appended, where n is the mailboxId of the message. The drag & drop code
1555 // uses this information to know not to allow dragging the item to its own mailbox
1556 String mimeType = EMAIL_MESSAGE_MIME_TYPE;
1557 String mailboxId = uri.getQueryParameter(MESSAGE_URI_PARAMETER_MAILBOX_ID);
1558 if (mailboxId != null) {
1559 mimeType += "-" + mailboxId;
1560 }
1561 return mimeType;
Marc Blanke34525d2009-06-17 10:22:37 -07001562 case UPDATED_MESSAGE:
Marc Blankfae47272009-05-29 14:24:34 -07001563 case MESSAGE:
Marc Blanka290f502009-06-15 14:40:06 -07001564 return "vnd.android.cursor.dir/email-message";
Marc Blankfae47272009-05-29 14:24:34 -07001565 case MAILBOX:
1566 return "vnd.android.cursor.dir/email-mailbox";
1567 case MAILBOX_ID:
1568 return "vnd.android.cursor.item/email-mailbox";
1569 case ACCOUNT:
1570 return "vnd.android.cursor.dir/email-account";
1571 case ACCOUNT_ID:
1572 return "vnd.android.cursor.item/email-account";
Andrew Stadler41192182009-07-16 16:03:40 -07001573 case ATTACHMENTS_MESSAGE_ID:
Marc Blankfae47272009-05-29 14:24:34 -07001574 case ATTACHMENT:
1575 return "vnd.android.cursor.dir/email-attachment";
1576 case ATTACHMENT_ID:
Marc Blank09fd4d02010-08-09 17:48:53 -07001577 return EMAIL_ATTACHMENT_MIME_TYPE;
Marc Blankfae47272009-05-29 14:24:34 -07001578 case HOSTAUTH:
1579 return "vnd.android.cursor.dir/email-hostauth";
1580 case HOSTAUTH_ID:
1581 return "vnd.android.cursor.item/email-hostauth";
1582 default:
1583 throw new IllegalArgumentException("Unknown URI " + uri);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001584 }
1585 }
1586
1587 @Override
1588 public Uri insert(Uri uri, ContentValues values) {
Marc Blanke6a22df2010-12-16 12:28:16 -08001589 int match = findMatch(uri, "insert");
Marc Blanka290f502009-06-15 14:40:06 -07001590 Context context = getContext();
Marc Blank1b9337e2010-09-23 09:19:44 -07001591 ContentResolver resolver = context.getContentResolver();
1592
Marc Blankcba3a482009-08-05 17:31:50 -07001593 // See the comment at delete(), above
Marc Blanka867ebb2009-08-18 11:44:27 -07001594 SQLiteDatabase db = getDatabase(context);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001595 int table = match >> BASE_SHIFT;
Todd Kennedybf30f942011-05-06 11:31:10 -07001596 String id = "0";
1597 long longId;
Marc Blankf3743042009-06-27 12:14:14 -07001598
Makoto Onuki5b0c2c72010-09-10 14:37:01 -07001599 // We do NOT allow setting of unreadCount/messageCount via the provider
1600 // These columns are maintained via triggers
1601 if (match == MAILBOX_ID || match == MAILBOX) {
1602 values.put(MailboxColumns.UNREAD_COUNT, 0);
1603 values.put(MailboxColumns.MESSAGE_COUNT, 0);
1604 }
Makoto Onukif678a8e2010-09-10 13:06:07 -07001605
Andrew Stadler626f3e42009-06-01 14:34:16 -07001606 Uri resultUri = null;
Marc Blankf3743042009-06-27 12:14:14 -07001607
Marc Blank0e1595c2009-11-18 17:11:33 -08001608 try {
1609 switch (match) {
Marc Blank6e418aa2011-06-18 18:03:11 -07001610 // NOTE: It is NOT legal for production code to insert directly into UPDATED_MESSAGE
1611 // or DELETED_MESSAGE; see the comment below for details
Marc Blank0e1595c2009-11-18 17:11:33 -08001612 case UPDATED_MESSAGE:
1613 case DELETED_MESSAGE:
Marc Blank6e418aa2011-06-18 18:03:11 -07001614 case MESSAGE:
Marc Blank0e1595c2009-11-18 17:11:33 -08001615 case BODY:
Marc Blank0e1595c2009-11-18 17:11:33 -08001616 case ATTACHMENT:
1617 case MAILBOX:
1618 case ACCOUNT:
1619 case HOSTAUTH:
Marc Blankaeee10e2011-04-27 17:12:06 -07001620 case POLICY:
Jorge Lugo5a3888f2011-06-01 10:09:26 -07001621 case QUICK_RESPONSE:
Todd Kennedybf30f942011-05-06 11:31:10 -07001622 longId = db.insert(TABLE_NAMES[table], "foo", values);
1623 resultUri = ContentUris.withAppendedId(uri, longId);
Marc Blank6e418aa2011-06-18 18:03:11 -07001624 switch(match) {
1625 case MAILBOX:
1626 if (values.containsKey(MailboxColumns.TYPE)) {
1627 // Only cache special mailbox types
1628 int type = values.getAsInteger(MailboxColumns.TYPE);
1629 if (type != Mailbox.TYPE_INBOX && type != Mailbox.TYPE_OUTBOX &&
1630 type != Mailbox.TYPE_DRAFTS && type != Mailbox.TYPE_SENT &&
1631 type != Mailbox.TYPE_TRASH && type != Mailbox.TYPE_SEARCH) {
1632 break;
1633 }
1634 }
1635 //$FALL-THROUGH$
1636 case ACCOUNT:
1637 case HOSTAUTH:
1638 case POLICY:
1639 // Cache new account, host auth, policy, and some mailbox rows
1640 Cursor c = query(resultUri, CACHE_PROJECTIONS[table], null, null, null);
1641 if (c != null) {
1642 if (match == MAILBOX) {
1643 addToMailboxTypeMap(c);
1644 } else if (match == ACCOUNT) {
1645 getOrCreateAccountMailboxTypeMap(longId);
1646 }
1647 c.close();
1648 }
1649 break;
1650 }
Marc Blank0e1595c2009-11-18 17:11:33 -08001651 // Clients shouldn't normally be adding rows to these tables, as they are
1652 // maintained by triggers. However, we need to be able to do this for unit
1653 // testing, so we allow the insert and then throw the same exception that we
1654 // would if this weren't allowed.
1655 if (match == UPDATED_MESSAGE || match == DELETED_MESSAGE) {
1656 throw new IllegalArgumentException("Unknown URL " + uri);
1657 }
Marc Blank09fd4d02010-08-09 17:48:53 -07001658 if (match == ATTACHMENT) {
Marc Blank75a873b2010-12-08 17:11:04 -08001659 int flags = 0;
Marc Blank09fd4d02010-08-09 17:48:53 -07001660 if (values.containsKey(Attachment.FLAGS)) {
Marc Blank75a873b2010-12-08 17:11:04 -08001661 flags = values.getAsInteger(Attachment.FLAGS);
Marc Blank09fd4d02010-08-09 17:48:53 -07001662 }
Marc Blank75a873b2010-12-08 17:11:04 -08001663 // Report all new attachments to the download service
Ben Komalo32bed4b2011-08-23 18:02:11 -07001664 mAttachmentService.attachmentChanged(getContext(), longId, flags);
Marc Blank09fd4d02010-08-09 17:48:53 -07001665 }
Marc Blank0e1595c2009-11-18 17:11:33 -08001666 break;
1667 case MAILBOX_ID:
1668 // This implies adding a message to a mailbox
1669 // Hmm, a problem here is that we can't link the account as well, so it must be
1670 // already in the values...
Todd Kennedybf30f942011-05-06 11:31:10 -07001671 longId = Long.parseLong(uri.getPathSegments().get(1));
1672 values.put(MessageColumns.MAILBOX_KEY, longId);
Makoto Onuki261d6c32010-09-14 16:28:50 -07001673 return insert(Message.CONTENT_URI, values); // Recurse
Marc Blank0e1595c2009-11-18 17:11:33 -08001674 case MESSAGE_ID:
1675 // This implies adding an attachment to a message.
Todd Kennedybf30f942011-05-06 11:31:10 -07001676 id = uri.getPathSegments().get(1);
1677 longId = Long.parseLong(id);
1678 values.put(AttachmentColumns.MESSAGE_KEY, longId);
Makoto Onuki261d6c32010-09-14 16:28:50 -07001679 return insert(Attachment.CONTENT_URI, values); // Recurse
Marc Blank0e1595c2009-11-18 17:11:33 -08001680 case ACCOUNT_ID:
1681 // This implies adding a mailbox to an account.
Todd Kennedybf30f942011-05-06 11:31:10 -07001682 longId = Long.parseLong(uri.getPathSegments().get(1));
1683 values.put(MailboxColumns.ACCOUNT_KEY, longId);
Makoto Onuki261d6c32010-09-14 16:28:50 -07001684 return insert(Mailbox.CONTENT_URI, values); // Recurse
Marc Blank0e1595c2009-11-18 17:11:33 -08001685 case ATTACHMENTS_MESSAGE_ID:
Todd Kennedybf30f942011-05-06 11:31:10 -07001686 longId = db.insert(TABLE_NAMES[table], "foo", values);
1687 resultUri = ContentUris.withAppendedId(Attachment.CONTENT_URI, longId);
Marc Blank0e1595c2009-11-18 17:11:33 -08001688 break;
1689 default:
Marc Blankef832992009-10-13 16:25:00 -07001690 throw new IllegalArgumentException("Unknown URL " + uri);
Marc Blank0e1595c2009-11-18 17:11:33 -08001691 }
1692 } catch (SQLiteException e) {
1693 checkDatabases();
1694 throw e;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001695 }
Marc Blankf3743042009-06-27 12:14:14 -07001696
Todd Kennedybf30f942011-05-06 11:31:10 -07001697 // Notify all notifier cursors
Todd Kennedye7fb4ac2011-05-11 15:29:24 -07001698 sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_INSERT, id);
Todd Kennedybf30f942011-05-06 11:31:10 -07001699
Makoto Onuki261d6c32010-09-14 16:28:50 -07001700 // Notify all existing cursors.
Marc Blank1b9337e2010-09-23 09:19:44 -07001701 resolver.notifyChange(EmailContent.CONTENT_URI, null);
Andrew Stadler626f3e42009-06-01 14:34:16 -07001702 return resultUri;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001703 }
1704
1705 @Override
1706 public boolean onCreate() {
Marc Blank0e1595c2009-11-18 17:11:33 -08001707 checkDatabases();
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001708 return false;
1709 }
1710
Marc Blank0e1595c2009-11-18 17:11:33 -08001711 /**
1712 * The idea here is that the two databases (EmailProvider.db and EmailProviderBody.db must
1713 * always be in sync (i.e. there are two database or NO databases). This code will delete
1714 * any "orphan" database, so that both will be created together. Note that an "orphan" database
1715 * will exist after either of the individual databases is deleted due to data corruption.
1716 */
1717 public void checkDatabases() {
1718 // Uncache the databases
1719 if (mDatabase != null) {
1720 mDatabase = null;
1721 }
1722 if (mBodyDatabase != null) {
1723 mBodyDatabase = null;
1724 }
1725 // Look for orphans, and delete as necessary; these must always be in sync
1726 File databaseFile = getContext().getDatabasePath(DATABASE_NAME);
1727 File bodyFile = getContext().getDatabasePath(BODY_DATABASE_NAME);
1728
1729 // TODO Make sure attachments are deleted
1730 if (databaseFile.exists() && !bodyFile.exists()) {
1731 Log.w(TAG, "Deleting orphaned EmailProvider database...");
1732 databaseFile.delete();
1733 } else if (bodyFile.exists() && !databaseFile.exists()) {
1734 Log.w(TAG, "Deleting orphaned EmailProviderBody database...");
1735 bodyFile.delete();
1736 }
1737 }
1738
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001739 @Override
Marc Blank758a5322009-07-30 11:41:31 -07001740 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
Marc Blankfae47272009-05-29 14:24:34 -07001741 String sortOrder) {
Marc Blankfab77f12010-10-27 16:50:54 -07001742 long time = 0L;
1743 if (Email.DEBUG) {
1744 time = System.nanoTime();
1745 }
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001746 Cursor c = null;
Marc Blankd306ba32010-12-30 14:55:27 -08001747 int match;
1748 try {
1749 match = findMatch(uri, "query");
1750 } catch (IllegalArgumentException e) {
1751 String uriString = uri.toString();
1752 // If we were passed an illegal uri, see if it ends in /-1
1753 // if so, and if substituting 0 for -1 results in a valid uri, return an empty cursor
1754 if (uriString != null && uriString.endsWith("/-1")) {
1755 uri = Uri.parse(uriString.substring(0, uriString.length() - 2) + "0");
1756 match = findMatch(uri, "query");
1757 switch (match) {
1758 case BODY_ID:
1759 case MESSAGE_ID:
1760 case DELETED_MESSAGE_ID:
1761 case UPDATED_MESSAGE_ID:
1762 case ATTACHMENT_ID:
1763 case MAILBOX_ID:
1764 case ACCOUNT_ID:
1765 case HOSTAUTH_ID:
Marc Blankaeee10e2011-04-27 17:12:06 -07001766 case POLICY_ID:
Marc Blankd306ba32010-12-30 14:55:27 -08001767 return new MatrixCursor(projection, 0);
1768 }
1769 }
1770 throw e;
1771 }
Marc Blanka290f502009-06-15 14:40:06 -07001772 Context context = getContext();
Marc Blankcba3a482009-08-05 17:31:50 -07001773 // See the comment at delete(), above
Marc Blanka867ebb2009-08-18 11:44:27 -07001774 SQLiteDatabase db = getDatabase(context);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001775 int table = match >> BASE_SHIFT;
Marc Blank07597e52010-09-29 08:43:31 -07001776 String limit = uri.getQueryParameter(EmailContent.PARAMETER_LIMIT);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001777 String id;
Marc Blankf3743042009-06-27 12:14:14 -07001778
Marc Blankfab77f12010-10-27 16:50:54 -07001779 // Find the cache for this query's table (if any)
1780 ContentCache cache = null;
1781 String tableName = TABLE_NAMES[table];
1782 // We can only use the cache if there's no selection
1783 if (selection == null) {
Marc Blank6e418aa2011-06-18 18:03:11 -07001784 cache = mContentCaches[table];
Marc Blankfab77f12010-10-27 16:50:54 -07001785 }
1786 if (cache == null) {
1787 ContentCache.notCacheable(uri, selection);
1788 }
1789
Marc Blank0e1595c2009-11-18 17:11:33 -08001790 try {
1791 switch (match) {
Marc Blank6e418aa2011-06-18 18:03:11 -07001792 case ACCOUNT_DEFAULT_ID:
1793 // Start with a snapshot of the cache
1794 Map<String, Cursor> accountCache = mCacheAccount.getSnapshot();
1795 long accountId = Account.NO_ACCOUNT;
Ben Komalo4de538b2011-07-13 14:43:21 -07001796 // Find the account with "isDefault" set, or the lowest account ID otherwise.
1797 // Note that the snapshot from the cached isn't guaranteed to be sorted in any
1798 // way.
Marc Blank6e418aa2011-06-18 18:03:11 -07001799 Collection<Cursor> accounts = accountCache.values();
Marc Blank6e418aa2011-06-18 18:03:11 -07001800 for (Cursor accountCursor: accounts) {
Marc Blankc09ca392011-06-22 18:36:28 -07001801 // For now, at least, we can have zero count cursors (e.g. if someone looks
1802 // up a non-existent id); we need to skip these
1803 if (accountCursor.moveToFirst()) {
1804 boolean isDefault =
1805 accountCursor.getInt(Account.CONTENT_IS_DEFAULT_COLUMN) == 1;
Ben Komalo4de538b2011-07-13 14:43:21 -07001806 long iterId = accountCursor.getLong(Account.CONTENT_ID_COLUMN);
Marc Blankc09ca392011-06-22 18:36:28 -07001807 // We'll remember this one if it's the default or the first one we see
Ben Komalo4de538b2011-07-13 14:43:21 -07001808 if (isDefault) {
1809 accountId = iterId;
1810 break;
1811 } else if ((accountId == Account.NO_ACCOUNT) || (iterId < accountId)) {
1812 accountId = iterId;
Marc Blankc09ca392011-06-22 18:36:28 -07001813 }
Marc Blank6e418aa2011-06-18 18:03:11 -07001814 }
1815 }
1816 // Return a cursor with an id projection
1817 MatrixCursor mc = new MatrixCursor(EmailContent.ID_PROJECTION);
1818 mc.addRow(new Object[] {accountId});
Marc Blank0306da12011-07-27 21:57:06 -07001819 c = mc;
1820 break;
Marc Blank6e418aa2011-06-18 18:03:11 -07001821 case MAILBOX_ID_FROM_ACCOUNT_AND_TYPE:
1822 // Get accountId and type and find the mailbox in our map
Marc Blank5d7ff852011-06-27 20:11:24 -07001823 List<String> pathSegments = uri.getPathSegments();
1824 accountId = Long.parseLong(pathSegments.get(1));
1825 int type = Integer.parseInt(pathSegments.get(2));
1826 long mailboxId = getMailboxIdFromMailboxTypeMap(accountId, type);
Marc Blank6e418aa2011-06-18 18:03:11 -07001827 // Return a cursor with an id projection
Marc Blank5d7ff852011-06-27 20:11:24 -07001828 mc = new MatrixCursor(EmailContent.ID_PROJECTION);
Marc Blank6e418aa2011-06-18 18:03:11 -07001829 mc.addRow(new Object[] {mailboxId});
Marc Blank0306da12011-07-27 21:57:06 -07001830 c = mc;
1831 break;
Marc Blank0e1595c2009-11-18 17:11:33 -08001832 case BODY:
1833 case MESSAGE:
1834 case UPDATED_MESSAGE:
1835 case DELETED_MESSAGE:
1836 case ATTACHMENT:
1837 case MAILBOX:
1838 case ACCOUNT:
1839 case HOSTAUTH:
Marc Blankaeee10e2011-04-27 17:12:06 -07001840 case POLICY:
Jorge Lugo5a3888f2011-06-01 10:09:26 -07001841 case QUICK_RESPONSE:
Marc Blank6e418aa2011-06-18 18:03:11 -07001842 // Special-case "count of accounts"; it's common and we always know it
1843 if (match == ACCOUNT && Arrays.equals(projection, EmailContent.COUNT_COLUMNS) &&
1844 selection == null && limit.equals("1")) {
1845 int accountCount = mMailboxTypeMap.size();
1846 // In the rare case there are MAX_CACHED_ACCOUNTS or more, we can't do this
1847 if (accountCount < MAX_CACHED_ACCOUNTS) {
1848 mc = new MatrixCursor(projection, 1);
1849 mc.addRow(new Object[] {accountCount});
Marc Blank577e6042011-08-05 09:50:56 -07001850 c = mc;
1851 break;
Marc Blank6e418aa2011-06-18 18:03:11 -07001852 }
1853 }
Marc Blankfab77f12010-10-27 16:50:54 -07001854 c = db.query(tableName, projection,
Marc Blank0efe7382010-09-27 18:29:50 -07001855 selection, selectionArgs, null, null, sortOrder, limit);
Marc Blank0e1595c2009-11-18 17:11:33 -08001856 break;
1857 case BODY_ID:
1858 case MESSAGE_ID:
1859 case DELETED_MESSAGE_ID:
1860 case UPDATED_MESSAGE_ID:
1861 case ATTACHMENT_ID:
1862 case MAILBOX_ID:
1863 case ACCOUNT_ID:
1864 case HOSTAUTH_ID:
Marc Blankaeee10e2011-04-27 17:12:06 -07001865 case POLICY_ID:
Jorge Lugo5a3888f2011-06-01 10:09:26 -07001866 case QUICK_RESPONSE_ID:
Marc Blank0e1595c2009-11-18 17:11:33 -08001867 id = uri.getPathSegments().get(1);
Marc Blankfab77f12010-10-27 16:50:54 -07001868 if (cache != null) {
1869 c = cache.getCachedCursor(id, projection);
1870 }
1871 if (c == null) {
1872 CacheToken token = null;
1873 if (cache != null) {
1874 token = cache.getCacheToken(id);
1875 }
1876 c = db.query(tableName, projection, whereWithId(id, selection),
1877 selectionArgs, null, null, sortOrder, limit);
1878 if (cache != null) {
1879 c = cache.putCursor(c, id, projection, token);
1880 }
1881 }
Marc Blank0e1595c2009-11-18 17:11:33 -08001882 break;
1883 case ATTACHMENTS_MESSAGE_ID:
1884 // All attachments for the given message
1885 id = uri.getPathSegments().get(2);
1886 c = db.query(Attachment.TABLE_NAME, projection,
1887 whereWith(Attachment.MESSAGE_KEY + "=" + id, selection),
Marc Blank0efe7382010-09-27 18:29:50 -07001888 selectionArgs, null, null, sortOrder, limit);
Marc Blank0e1595c2009-11-18 17:11:33 -08001889 break;
Jorge Lugo5a3888f2011-06-01 10:09:26 -07001890 case QUICK_RESPONSE_ACCOUNT_ID:
1891 // All quick responses for the given account
1892 id = uri.getPathSegments().get(2);
1893 c = db.query(QuickResponse.TABLE_NAME, projection,
1894 whereWith(QuickResponse.ACCOUNT_KEY + "=" + id, selection),
1895 selectionArgs, null, null, sortOrder);
1896 break;
Marc Blank0e1595c2009-11-18 17:11:33 -08001897 default:
1898 throw new IllegalArgumentException("Unknown URI " + uri);
1899 }
1900 } catch (SQLiteException e) {
1901 checkDatabases();
1902 throw e;
Marc Blankfab77f12010-10-27 16:50:54 -07001903 } catch (RuntimeException e) {
1904 checkDatabases();
1905 e.printStackTrace();
1906 throw e;
1907 } finally {
Marc Blank6e418aa2011-06-18 18:03:11 -07001908 if (cache != null && c != null && Email.DEBUG) {
Marc Blankfab77f12010-10-27 16:50:54 -07001909 cache.recordQueryTime(c, System.nanoTime() - time);
1910 }
Marc Blank7390b182011-07-27 16:48:35 -07001911 if (c == null) {
1912 // This should never happen, but let's be sure to log it...
1913 Log.e(TAG, "Query returning null for uri: " + uri + ", selection: " + selection);
1914 }
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001915 }
1916
1917 if ((c != null) && !isTemporary()) {
Makoto Onuki261d6c32010-09-14 16:28:50 -07001918 c.setNotificationUri(getContext().getContentResolver(), uri);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001919 }
1920 return c;
1921 }
1922
1923 private String whereWithId(String id, String selection) {
1924 StringBuilder sb = new StringBuilder(256);
1925 sb.append("_id=");
1926 sb.append(id);
1927 if (selection != null) {
Andrew Stadler6c219422009-09-10 11:52:36 -07001928 sb.append(" AND (");
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001929 sb.append(selection);
Andrew Stadler6c219422009-09-10 11:52:36 -07001930 sb.append(')');
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001931 }
1932 return sb.toString();
1933 }
Marc Blankf3743042009-06-27 12:14:14 -07001934
Andrew Stadler6c219422009-09-10 11:52:36 -07001935 /**
1936 * Combine a locally-generated selection with a user-provided selection
1937 *
1938 * This introduces risk that the local selection might insert incorrect chars
1939 * into the SQL, so use caution.
1940 *
1941 * @param where locally-generated selection, must not be null
1942 * @param selection user-provided selection, may be null
1943 * @return a single selection string
1944 */
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001945 private String whereWith(String where, String selection) {
Andrew Stadler6c219422009-09-10 11:52:36 -07001946 if (selection == null) {
1947 return where;
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001948 }
Andrew Stadler6c219422009-09-10 11:52:36 -07001949 StringBuilder sb = new StringBuilder(where);
1950 sb.append(" AND (");
1951 sb.append(selection);
1952 sb.append(')');
1953
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07001954 return sb.toString();
1955 }
Marc Blankf3743042009-06-27 12:14:14 -07001956
Marc Blank09931902011-05-06 12:07:39 -07001957 /**
1958 * Restore a HostAuth from a database, given its unique id
1959 * @param db the database
1960 * @param id the unique id (_id) of the row
1961 * @return a fully populated HostAuth or null if the row does not exist
1962 */
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07001963 private static HostAuth restoreHostAuth(SQLiteDatabase db, long id) {
Marc Blank09931902011-05-06 12:07:39 -07001964 Cursor c = db.query(HostAuth.TABLE_NAME, HostAuth.CONTENT_PROJECTION,
1965 HostAuth.RECORD_ID + "=?", new String[] {Long.toString(id)}, null, null, null);
1966 try {
1967 if (c.moveToFirst()) {
1968 HostAuth hostAuth = new HostAuth();
1969 hostAuth.restore(c);
1970 return hostAuth;
1971 }
1972 return null;
1973 } finally {
1974 c.close();
1975 }
1976 }
1977
1978 /**
1979 * Copy the Account and HostAuth tables from one database to another
1980 * @param fromDatabase the source database
1981 * @param toDatabase the destination database
1982 * @return the number of accounts copied, or -1 if an error occurred
1983 */
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07001984 private static int copyAccountTables(SQLiteDatabase fromDatabase, SQLiteDatabase toDatabase) {
Marc Blank09931902011-05-06 12:07:39 -07001985 if (fromDatabase == null || toDatabase == null) return -1;
1986 int copyCount = 0;
1987 try {
1988 // Lock both databases; for the "from" database, we don't want anyone changing it from
1989 // under us; for the "to" database, we want to make the operation atomic
1990 fromDatabase.beginTransaction();
1991 toDatabase.beginTransaction();
1992 // Delete anything hanging around here
1993 toDatabase.delete(Account.TABLE_NAME, null, null);
1994 toDatabase.delete(HostAuth.TABLE_NAME, null, null);
1995 // Get our account cursor
1996 Cursor c = fromDatabase.query(Account.TABLE_NAME, Account.CONTENT_PROJECTION,
1997 null, null, null, null, null);
1998 boolean noErrors = true;
1999 try {
2000 // Loop through accounts, copying them and associated host auth's
2001 while (c.moveToNext()) {
2002 Account account = new Account();
2003 account.restore(c);
2004
2005 // Clear security sync key and sync key, as these were specific to the state of
2006 // the account, and we've reset that...
2007 // Clear policy key so that we can re-establish policies from the server
2008 // TODO This is pretty EAS specific, but there's a lot of that around
2009 account.mSecuritySyncKey = null;
2010 account.mSyncKey = null;
2011 account.mPolicyKey = 0;
2012
2013 // Copy host auth's and update foreign keys
2014 HostAuth hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeyRecv);
2015 // The account might have gone away, though very unlikely
2016 if (hostAuth == null) continue;
2017 account.mHostAuthKeyRecv = toDatabase.insert(HostAuth.TABLE_NAME, null,
2018 hostAuth.toContentValues());
2019 // EAS accounts have no send HostAuth
2020 if (account.mHostAuthKeySend > 0) {
2021 hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeySend);
2022 // Belt and suspenders; I can't imagine that this is possible, since we
2023 // checked the validity of the account above, and the database is now locked
2024 if (hostAuth == null) continue;
2025 account.mHostAuthKeySend = toDatabase.insert(HostAuth.TABLE_NAME, null,
2026 hostAuth.toContentValues());
2027 }
2028 // Now, create the account in the "to" database
2029 toDatabase.insert(Account.TABLE_NAME, null, account.toContentValues());
2030 copyCount++;
2031 }
2032 } catch (SQLiteException e) {
2033 noErrors = false;
2034 copyCount = -1;
2035 } finally {
2036 fromDatabase.endTransaction();
2037 if (noErrors) {
2038 // Say it's ok to commit
2039 toDatabase.setTransactionSuccessful();
2040 }
2041 toDatabase.endTransaction();
2042 c.close();
2043 }
2044 } catch (SQLiteException e) {
2045 copyCount = -1;
2046 }
2047 return copyCount;
2048 }
2049
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07002050 private static SQLiteDatabase getBackupDatabase(Context context) {
Marc Blank09931902011-05-06 12:07:39 -07002051 DatabaseHelper helper = new DatabaseHelper(context, BACKUP_DATABASE_NAME);
2052 return helper.getWritableDatabase();
2053 }
2054
2055 /**
2056 * Backup account data, returning the number of accounts backed up
2057 */
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07002058 private static int backupAccounts(Context context, SQLiteDatabase mainDatabase) {
2059 if (Email.DEBUG) {
2060 Log.d(TAG, "backupAccounts...");
2061 }
Marc Blank09931902011-05-06 12:07:39 -07002062 SQLiteDatabase backupDatabase = getBackupDatabase(context);
2063 try {
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07002064 int numBackedUp = copyAccountTables(mainDatabase, backupDatabase);
2065 if (numBackedUp < 0) {
2066 Log.e(TAG, "Account backup failed!");
2067 } else if (Email.DEBUG) {
2068 Log.d(TAG, "Backed up " + numBackedUp + " accounts...");
2069 }
2070 return numBackedUp;
Marc Blank09931902011-05-06 12:07:39 -07002071 } finally {
2072 if (backupDatabase != null) {
2073 backupDatabase.close();
2074 }
2075 }
2076 }
2077
2078 /**
2079 * Restore account data, returning the number of accounts restored
2080 */
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07002081 private static int restoreAccounts(Context context, SQLiteDatabase mainDatabase) {
2082 if (Email.DEBUG) {
2083 Log.d(TAG, "restoreAccounts...");
2084 }
Marc Blank09931902011-05-06 12:07:39 -07002085 SQLiteDatabase backupDatabase = getBackupDatabase(context);
2086 try {
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07002087 int numRecovered = copyAccountTables(backupDatabase, mainDatabase);
2088 if (numRecovered > 0) {
2089 Log.e(TAG, "Recovered " + numRecovered + " accounts!");
2090 } else if (numRecovered < 0) {
2091 Log.e(TAG, "Account recovery failed?");
2092 } else if (Email.DEBUG) {
2093 Log.d(TAG, "No accounts to restore...");
2094 }
2095 return numRecovered;
Marc Blank09931902011-05-06 12:07:39 -07002096 } finally {
2097 if (backupDatabase != null) {
2098 backupDatabase.close();
2099 }
2100 }
2101 }
2102
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07002103 @Override
2104 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Makoto Onukif678a8e2010-09-10 13:06:07 -07002105 // Handle this special case the fastest possible way
2106 if (uri == INTEGRITY_CHECK_URI) {
2107 checkDatabases();
2108 return 0;
Marc Blank09931902011-05-06 12:07:39 -07002109 } else if (uri == ACCOUNT_BACKUP_URI) {
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07002110 return backupAccounts(getContext(), getDatabase(getContext()));
Makoto Onukif678a8e2010-09-10 13:06:07 -07002111 }
2112
Makoto Onuki261d6c32010-09-14 16:28:50 -07002113 // Notify all existing cursors, except for ACCOUNT_RESET_NEW_COUNT(_ID)
2114 Uri notificationUri = EmailContent.CONTENT_URI;
2115
Marc Blanke6a22df2010-12-16 12:28:16 -08002116 int match = findMatch(uri, "update");
Marc Blanka290f502009-06-15 14:40:06 -07002117 Context context = getContext();
Marc Blank1b9337e2010-09-23 09:19:44 -07002118 ContentResolver resolver = context.getContentResolver();
Marc Blankcba3a482009-08-05 17:31:50 -07002119 // See the comment at delete(), above
Marc Blanka867ebb2009-08-18 11:44:27 -07002120 SQLiteDatabase db = getDatabase(context);
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07002121 int table = match >> BASE_SHIFT;
Andrew Stadler626f3e42009-06-01 14:34:16 -07002122 int result;
Marc Blanka290f502009-06-15 14:40:06 -07002123
Makoto Onuki5b0c2c72010-09-10 14:37:01 -07002124 // We do NOT allow setting of unreadCount/messageCount via the provider
2125 // These columns are maintained via triggers
2126 if (match == MAILBOX_ID || match == MAILBOX) {
2127 values.remove(MailboxColumns.UNREAD_COUNT);
2128 values.remove(MailboxColumns.MESSAGE_COUNT);
2129 }
Marc Blank0e1595c2009-11-18 17:11:33 -08002130
Marc Blank6e418aa2011-06-18 18:03:11 -07002131 ContentCache cache = mContentCaches[table];
Marc Blankfab77f12010-10-27 16:50:54 -07002132 String tableName = TABLE_NAMES[table];
Todd Kennedybf30f942011-05-06 11:31:10 -07002133 String id = "0";
Marc Blankfab77f12010-10-27 16:50:54 -07002134
Marc Blank0e1595c2009-11-18 17:11:33 -08002135 try {
Marc Blank6e418aa2011-06-18 18:03:11 -07002136outer:
Marc Blank0e1595c2009-11-18 17:11:33 -08002137 switch (match) {
2138 case MAILBOX_ID_ADD_TO_FIELD:
2139 case ACCOUNT_ID_ADD_TO_FIELD:
Marc Blank0e1595c2009-11-18 17:11:33 -08002140 id = uri.getPathSegments().get(1);
2141 String field = values.getAsString(EmailContent.FIELD_COLUMN_NAME);
2142 Long add = values.getAsLong(EmailContent.ADD_COLUMN_NAME);
2143 if (field == null || add == null) {
2144 throw new IllegalArgumentException("No field/add specified " + uri);
Marc Blankc0c9c332009-08-19 19:07:29 -07002145 }
Makoto Onuki9d5aaea2010-12-02 16:33:49 -08002146 ContentValues actualValues = new ContentValues();
Makoto Onukiedb8af82010-12-02 15:19:14 -08002147 if (cache != null) {
2148 cache.lock(id);
Marc Blank0e1595c2009-11-18 17:11:33 -08002149 }
Makoto Onukiedb8af82010-12-02 15:19:14 -08002150 try {
Makoto Onuki9d5aaea2010-12-02 16:33:49 -08002151 db.beginTransaction();
Makoto Onukiedb8af82010-12-02 15:19:14 -08002152 try {
Makoto Onuki9d5aaea2010-12-02 16:33:49 -08002153 Cursor c = db.query(tableName,
2154 new String[] {EmailContent.RECORD_ID, field},
2155 whereWithId(id, selection),
2156 selectionArgs, null, null, null);
2157 try {
2158 result = 0;
2159 String[] bind = new String[1];
2160 if (c.moveToNext()) {
2161 bind[0] = c.getString(0); // _id
2162 long value = c.getLong(1) + add;
2163 actualValues.put(field, value);
2164 result = db.update(tableName, actualValues, ID_EQUALS, bind);
2165 }
2166 db.setTransactionSuccessful();
2167 } finally {
2168 c.close();
Makoto Onukiedb8af82010-12-02 15:19:14 -08002169 }
2170 } finally {
Makoto Onuki9d5aaea2010-12-02 16:33:49 -08002171 db.endTransaction();
Makoto Onukiedb8af82010-12-02 15:19:14 -08002172 }
Makoto Onukiedb8af82010-12-02 15:19:14 -08002173 } finally {
2174 if (cache != null) {
2175 cache.unlock(id, actualValues);
2176 }
2177 }
Marc Blank0e1595c2009-11-18 17:11:33 -08002178 break;
Marc Blank0e1595c2009-11-18 17:11:33 -08002179 case SYNCED_MESSAGE_ID:
2180 case UPDATED_MESSAGE_ID:
Marc Blank1b9337e2010-09-23 09:19:44 -07002181 case MESSAGE_ID:
2182 case BODY_ID:
Marc Blank0e1595c2009-11-18 17:11:33 -08002183 case ATTACHMENT_ID:
2184 case MAILBOX_ID:
2185 case ACCOUNT_ID:
2186 case HOSTAUTH_ID:
Jorge Lugo5a3888f2011-06-01 10:09:26 -07002187 case QUICK_RESPONSE_ID:
Marc Blank6e418aa2011-06-18 18:03:11 -07002188 case POLICY_ID:
Marc Blank0e1595c2009-11-18 17:11:33 -08002189 id = uri.getPathSegments().get(1);
Marc Blankfab77f12010-10-27 16:50:54 -07002190 if (cache != null) {
2191 cache.lock(id);
Marc Blank0e1595c2009-11-18 17:11:33 -08002192 }
Marc Blankfab77f12010-10-27 16:50:54 -07002193 try {
2194 if (match == SYNCED_MESSAGE_ID) {
2195 // For synced messages, first copy the old message to the updated table
2196 // Note the insert or ignore semantics, guaranteeing that only the first
2197 // update will be reflected in the updated message table; therefore this
2198 // row will always have the "original" data
2199 db.execSQL(UPDATED_MESSAGE_INSERT + id);
2200 } else if (match == MESSAGE_ID) {
2201 db.execSQL(UPDATED_MESSAGE_DELETE + id);
2202 }
2203 result = db.update(tableName, values, whereWithId(id, selection),
2204 selectionArgs);
2205 } catch (SQLiteException e) {
2206 // Null out values (so they aren't cached) and re-throw
2207 values = null;
2208 throw e;
2209 } finally {
2210 if (cache != null) {
2211 cache.unlock(id, values);
2212 }
2213 }
Marc Blank09fd4d02010-08-09 17:48:53 -07002214 if (match == ATTACHMENT_ID) {
2215 if (values.containsKey(Attachment.FLAGS)) {
2216 int flags = values.getAsInteger(Attachment.FLAGS);
Ben Komalo32bed4b2011-08-23 18:02:11 -07002217 mAttachmentService.attachmentChanged(getContext(),
Marc Blank09fd4d02010-08-09 17:48:53 -07002218 Integer.parseInt(id), flags);
2219 }
2220 }
Marc Blank0e1595c2009-11-18 17:11:33 -08002221 break;
2222 case BODY:
2223 case MESSAGE:
2224 case UPDATED_MESSAGE:
2225 case ATTACHMENT:
2226 case MAILBOX:
2227 case ACCOUNT:
2228 case HOSTAUTH:
Marc Blank6e418aa2011-06-18 18:03:11 -07002229 case POLICY:
Marc Blankfab77f12010-10-27 16:50:54 -07002230 switch(match) {
Marc Blank6e418aa2011-06-18 18:03:11 -07002231 // To avoid invalidating the cache on updates, we execute them one at a
2232 // time using the XXX_ID uri; these are all executed atomically
Marc Blankfab77f12010-10-27 16:50:54 -07002233 case ACCOUNT:
2234 case MAILBOX:
2235 case HOSTAUTH:
Marc Blank6e418aa2011-06-18 18:03:11 -07002236 case POLICY:
2237 Cursor c = db.query(tableName, EmailContent.ID_PROJECTION,
2238 selection, selectionArgs, null, null, null);
2239 db.beginTransaction();
2240 result = 0;
2241 try {
2242 while (c.moveToNext()) {
2243 update(ContentUris.withAppendedId(
2244 uri, c.getLong(EmailContent.ID_PROJECTION_COLUMN)),
2245 values, null, null);
2246 result++;
2247 }
2248 db.setTransactionSuccessful();
2249 } finally {
2250 db.endTransaction();
2251 c.close();
2252 }
2253 break outer;
2254 // Any cached table other than those above should be invalidated here
2255 case MESSAGE:
Marc Blankfab77f12010-10-27 16:50:54 -07002256 // If we're doing some generic update, the whole cache needs to be
2257 // invalidated. This case should be quite rare
2258 cache.invalidate("Update", uri, selection);
Marc Blank6e418aa2011-06-18 18:03:11 -07002259 //$FALL-THROUGH$
2260 default:
2261 result = db.update(tableName, values, selection, selectionArgs);
2262 break outer;
Marc Blankfab77f12010-10-27 16:50:54 -07002263 }
Makoto Onuki261d6c32010-09-14 16:28:50 -07002264 case ACCOUNT_RESET_NEW_COUNT_ID:
2265 id = uri.getPathSegments().get(1);
Makoto Onukiedb8af82010-12-02 15:19:14 -08002266 if (cache != null) {
2267 cache.lock(id);
2268 }
Todd Kennedyc4cdb112011-05-03 14:42:26 -07002269 ContentValues newMessageCount = CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
2270 if (values != null) {
2271 Long set = values.getAsLong(EmailContent.SET_COLUMN_NAME);
2272 if (set != null) {
2273 newMessageCount = new ContentValues();
2274 newMessageCount.put(Account.NEW_MESSAGE_COUNT, set);
2275 }
2276 }
Makoto Onukiedb8af82010-12-02 15:19:14 -08002277 try {
Todd Kennedyc4cdb112011-05-03 14:42:26 -07002278 result = db.update(tableName, newMessageCount,
Makoto Onukiedb8af82010-12-02 15:19:14 -08002279 whereWithId(id, selection), selectionArgs);
2280 } finally {
2281 if (cache != null) {
2282 cache.unlock(id, values);
2283 }
2284 }
Makoto Onuki261d6c32010-09-14 16:28:50 -07002285 notificationUri = Account.CONTENT_URI; // Only notify account cursors.
2286 break;
2287 case ACCOUNT_RESET_NEW_COUNT:
Marc Blankfab77f12010-10-27 16:50:54 -07002288 result = db.update(tableName, CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT,
Makoto Onuki261d6c32010-09-14 16:28:50 -07002289 selection, selectionArgs);
Makoto Onukiedb8af82010-12-02 15:19:14 -08002290 // Affects all accounts. Just invalidate all account cache.
Makoto Onukiedb8af82010-12-02 15:19:14 -08002291 cache.invalidate("Reset all new counts", null, null);
Makoto Onuki261d6c32010-09-14 16:28:50 -07002292 notificationUri = Account.CONTENT_URI; // Only notify account cursors.
2293 break;
Marc Blank0e1595c2009-11-18 17:11:33 -08002294 default:
2295 throw new IllegalArgumentException("Unknown URI " + uri);
2296 }
2297 } catch (SQLiteException e) {
2298 checkDatabases();
2299 throw e;
Marc Blankfae47272009-05-29 14:24:34 -07002300 }
Marc Blanka290f502009-06-15 14:40:06 -07002301
Todd Kennedybf30f942011-05-06 11:31:10 -07002302 // Notify all notifier cursors
Todd Kennedye7fb4ac2011-05-11 15:29:24 -07002303 sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_UPDATE, id);
Todd Kennedybf30f942011-05-06 11:31:10 -07002304
Marc Blank1b9337e2010-09-23 09:19:44 -07002305 resolver.notifyChange(notificationUri, null);
Andrew Stadler626f3e42009-06-01 14:34:16 -07002306 return result;
Marc Blankfae47272009-05-29 14:24:34 -07002307 }
Marc Blankf3743042009-06-27 12:14:14 -07002308
Todd Kennedybf30f942011-05-06 11:31:10 -07002309 /**
Todd Kennedye7fb4ac2011-05-11 15:29:24 -07002310 * Returns the base notification URI for the given content type.
2311 *
2312 * @param match The type of content that was modified.
2313 */
2314 private Uri getBaseNotificationUri(int match) {
2315 Uri baseUri = null;
2316 switch (match) {
2317 case MESSAGE:
2318 case MESSAGE_ID:
2319 case SYNCED_MESSAGE_ID:
2320 baseUri = Message.NOTIFIER_URI;
2321 break;
2322 case ACCOUNT:
2323 case ACCOUNT_ID:
2324 baseUri = Account.NOTIFIER_URI;
2325 break;
2326 }
2327 return baseUri;
2328 }
2329
2330 /**
Todd Kennedybf30f942011-05-06 11:31:10 -07002331 * Sends a change notification to any cursors observers of the given base URI. The final
2332 * notification URI is dynamically built to contain the specified information. It will be
2333 * of the format <<baseURI>>/<<op>>/<<id>>; where <<op>> and <<id>> are optional depending
2334 * upon the given values.
2335 * NOTE: If <<op>> is specified, notifications for <<baseURI>>/<<id>> will NOT be invoked.
2336 * If this is necessary, it can be added. However, due to the implementation of
2337 * {@link ContentObserver}, observers of <<baseURI>> will receive multiple notifications.
2338 *
2339 * @param baseUri The base URI to send notifications to. Must be able to take appended IDs.
2340 * @param op Optional operation to be appended to the URI.
2341 * @param id If a positive value, the ID to append to the base URI. Otherwise, no ID will be
2342 * appended to the base URI.
Marc Blankfae47272009-05-29 14:24:34 -07002343 */
Todd Kennedybf30f942011-05-06 11:31:10 -07002344 private void sendNotifierChange(Uri baseUri, String op, String id) {
Todd Kennedye7fb4ac2011-05-11 15:29:24 -07002345 if (baseUri == null) return;
2346
Todd Kennedybf30f942011-05-06 11:31:10 -07002347 final ContentResolver resolver = getContext().getContentResolver();
2348
2349 // Append the operation, if specified
2350 if (op != null) {
2351 baseUri = baseUri.buildUpon().appendEncodedPath(op).build();
2352 }
2353
2354 long longId = 0L;
2355 try {
2356 longId = Long.valueOf(id);
2357 } catch (NumberFormatException ignore) {}
2358 if (longId > 0) {
2359 resolver.notifyChange(ContentUris.withAppendedId(baseUri, longId), null);
2360 } else {
2361 resolver.notifyChange(baseUri, null);
2362 }
2363 }
2364
Marc Blank758a5322009-07-30 11:41:31 -07002365 @Override
Fred Quintana84969fb2009-06-01 12:55:50 -07002366 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Marc Blankb6493a02009-07-05 12:54:49 -07002367 throws OperationApplicationException {
Marc Blankcba3a482009-08-05 17:31:50 -07002368 Context context = getContext();
2369 SQLiteDatabase db = getDatabase(context);
Marc Blankfae47272009-05-29 14:24:34 -07002370 db.beginTransaction();
2371 try {
2372 ContentProviderResult[] results = super.applyBatch(operations);
2373 db.setTransactionSuccessful();
2374 return results;
2375 } finally {
2376 db.endTransaction();
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07002377 }
2378 }
Makoto Onuki574854b2010-07-30 13:53:59 -07002379
Todd Kennedy22208772011-04-22 15:45:11 -07002380 /** Counts the number of messages in each mailbox, and updates the message count column. */
2381 @VisibleForTesting
2382 static void recalculateMessageCount(SQLiteDatabase db) {
Makoto Onuki574854b2010-07-30 13:53:59 -07002383 db.execSQL("update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
2384 "= (select count(*) from " + Message.TABLE_NAME +
2385 " where " + Message.MAILBOX_KEY + " = " +
2386 Mailbox.TABLE_NAME + "." + EmailContent.RECORD_ID + ")");
2387 }
Todd Kennedy22208772011-04-22 15:45:11 -07002388
Marc Blankaeee10e2011-04-27 17:12:06 -07002389 @VisibleForTesting
Todd Kennedybf30f942011-05-06 11:31:10 -07002390 @SuppressWarnings("deprecation")
Makoto Onuki9dad9ad2011-06-20 18:10:10 -07002391 static void convertPolicyFlagsToPolicyTable(SQLiteDatabase db) {
Marc Blankaeee10e2011-04-27 17:12:06 -07002392 Cursor c = db.query(Account.TABLE_NAME,
2393 new String[] {EmailContent.RECORD_ID /*0*/, AccountColumns.SECURITY_FLAGS /*1*/},
2394 AccountColumns.SECURITY_FLAGS + ">0", null, null, null, null);
2395 ContentValues cv = new ContentValues();
2396 String[] args = new String[1];
2397 while (c.moveToNext()) {
2398 long securityFlags = c.getLong(1 /*SECURITY_FLAGS*/);
2399 Policy policy = LegacyPolicySet.flagsToPolicy(securityFlags);
2400 long policyId = db.insert(Policy.TABLE_NAME, null, policy.toContentValues());
2401 cv.put(AccountColumns.POLICY_KEY, policyId);
2402 cv.putNull(AccountColumns.SECURITY_FLAGS);
2403 args[0] = Long.toString(c.getLong(0 /*RECORD_ID*/));
2404 db.update(Account.TABLE_NAME, cv, EmailContent.RECORD_ID + "=?", args);
2405 }
2406 }
2407
Todd Kennedy22208772011-04-22 15:45:11 -07002408 /** Upgrades the database from v17 to v18 */
2409 @VisibleForTesting
2410 static void upgradeFromVersion17ToVersion18(SQLiteDatabase db) {
2411 // Copy the displayName column to the serverId column. In v18 of the database,
2412 // we use the serverId for IMAP/POP3 mailboxes instead of overloading the
2413 // display name.
2414 //
2415 // For posterity; this is the command we're executing:
2416 //sqlite> UPDATE mailbox SET serverid=displayname WHERE mailbox._id in (
2417 // ...> SELECT mailbox._id FROM mailbox,account,hostauth WHERE
Ben Komalo2c57e702011-09-13 17:11:39 -07002418 // ...> (mailbox.parentkey isnull OR mailbox.parentkey=0) AND
2419 // ...> mailbox.accountkey=account._id AND
Todd Kennedy22208772011-04-22 15:45:11 -07002420 // ...> account.hostauthkeyrecv=hostauth._id AND
2421 // ...> (hostauth.protocol='imap' OR hostauth.protocol='pop3'));
2422 try {
2423 db.execSQL(
2424 "UPDATE " + Mailbox.TABLE_NAME + " SET "
2425 + MailboxColumns.SERVER_ID + "=" + MailboxColumns.DISPLAY_NAME
2426 + " WHERE "
2427 + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " IN ( SELECT "
2428 + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " FROM "
2429 + Mailbox.TABLE_NAME + "," + Account.TABLE_NAME + ","
2430 + HostAuth.TABLE_NAME + " WHERE "
Ben Komalo2c57e702011-09-13 17:11:39 -07002431 + "("
2432 + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + " isnull OR "
2433 + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + "=0 "
2434 + ") AND "
Todd Kennedy22208772011-04-22 15:45:11 -07002435 + Mailbox.TABLE_NAME + "." + MailboxColumns.ACCOUNT_KEY + "="
2436 + Account.TABLE_NAME + "." + AccountColumns.ID + " AND "
2437 + Account.TABLE_NAME + "." + AccountColumns.HOST_AUTH_KEY_RECV + "="
2438 + HostAuth.TABLE_NAME + "." + HostAuthColumns.ID + " AND ( "
2439 + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='imap' OR "
2440 + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='pop3' ) )");
2441 } catch (SQLException e) {
2442 // Shouldn't be needed unless we're debugging and interrupt the process
2443 Log.w(TAG, "Exception upgrading EmailProvider.db from 17 to 18 " + e);
2444 }
Marc Blank6e418aa2011-06-18 18:03:11 -07002445 ContentCache.invalidateAllCaches();
Todd Kennedy22208772011-04-22 15:45:11 -07002446 }
Todd Kennedya9ac20b2011-05-06 13:37:02 -07002447
2448 /** Upgrades the database from v20 to v21 */
2449 private static void upgradeFromVersion20ToVersion21(SQLiteDatabase db) {
2450 try {
2451 db.execSQL("alter table " + Mailbox.TABLE_NAME
2452 + " add column " + Mailbox.LAST_SEEN_MESSAGE_KEY + " integer;");
2453 } catch (SQLException e) {
2454 // Shouldn't be needed unless we're debugging and interrupt the process
2455 Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
2456 }
2457 }
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002458
2459 /**
2460 * Upgrade the database from v21 to v22
2461 * This entails creating AccountManager accounts for all pop3 and imap accounts
2462 */
2463
Marc Blank27a04fe2011-07-29 21:53:44 -07002464 private static final String[] V21_ACCOUNT_PROJECTION =
Marc Blank20b511f2011-08-02 14:01:58 -07002465 new String[] {AccountColumns.HOST_AUTH_KEY_RECV, AccountColumns.EMAIL_ADDRESS};
Marc Blank27a04fe2011-07-29 21:53:44 -07002466 private static final int V21_ACCOUNT_RECV = 0;
Marc Blank20b511f2011-08-02 14:01:58 -07002467 private static final int V21_ACCOUNT_EMAIL = 1;
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002468
Marc Blank27a04fe2011-07-29 21:53:44 -07002469 private static final String[] V21_HOSTAUTH_PROJECTION =
Marc Blank20b511f2011-08-02 14:01:58 -07002470 new String[] {HostAuthColumns.PROTOCOL, HostAuthColumns.PASSWORD};
Marc Blank27a04fe2011-07-29 21:53:44 -07002471 private static final int V21_HOSTAUTH_PROTOCOL = 0;
Marc Blank20b511f2011-08-02 14:01:58 -07002472 private static final int V21_HOSTAUTH_PASSWORD = 1;
Marc Blank27a04fe2011-07-29 21:53:44 -07002473
2474 static private void createAccountManagerAccount(Context context, String login,
2475 String password) {
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002476 AccountManager accountManager = AccountManager.get(context);
2477 android.accounts.Account amAccount =
Marc Blank27a04fe2011-07-29 21:53:44 -07002478 new android.accounts.Account(login, AccountManagerTypes.TYPE_POP_IMAP);
2479 accountManager.addAccountExplicitly(amAccount, password, null);
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002480 ContentResolver.setIsSyncable(amAccount, EmailContent.AUTHORITY, 1);
2481 ContentResolver.setSyncAutomatically(amAccount, EmailContent.AUTHORITY, true);
2482 ContentResolver.setIsSyncable(amAccount, ContactsContract.AUTHORITY, 0);
2483 ContentResolver.setIsSyncable(amAccount, CalendarProviderStub.AUTHORITY, 0);
2484 }
2485
2486 @VisibleForTesting
2487 static void upgradeFromVersion21ToVersion22(SQLiteDatabase db, Context accountManagerContext) {
2488 try {
2489 // Loop through accounts, looking for pop/imap accounts
Marc Blank27a04fe2011-07-29 21:53:44 -07002490 Cursor accountCursor = db.query(Account.TABLE_NAME, V21_ACCOUNT_PROJECTION, null,
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002491 null, null, null, null);
2492 try {
2493 String[] hostAuthArgs = new String[1];
2494 while (accountCursor.moveToNext()) {
Marc Blank27a04fe2011-07-29 21:53:44 -07002495 hostAuthArgs[0] = accountCursor.getString(V21_ACCOUNT_RECV);
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002496 // Get the "receive" HostAuth for this account
2497 Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
Marc Blank27a04fe2011-07-29 21:53:44 -07002498 V21_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002499 null, null, null);
2500 try {
2501 if (hostAuthCursor.moveToFirst()) {
Marc Blank27a04fe2011-07-29 21:53:44 -07002502 String protocol = hostAuthCursor.getString(V21_HOSTAUTH_PROTOCOL);
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002503 // If this is a pop3 or imap account, create the account manager account
Marc Blank36aef9f2011-08-02 11:44:41 -07002504 if (HostAuth.SCHEME_IMAP.equals(protocol) ||
2505 HostAuth.SCHEME_POP3.equals(protocol)) {
Ben Komalo32bed4b2011-08-23 18:02:11 -07002506 if (Email.DEBUG) {
Marc Blank36aef9f2011-08-02 11:44:41 -07002507 Log.d(TAG, "Create AccountManager account for " + protocol +
Marc Blank20b511f2011-08-02 14:01:58 -07002508 "account: " +
2509 accountCursor.getString(V21_ACCOUNT_EMAIL));
Marc Blank36aef9f2011-08-02 11:44:41 -07002510 }
Marc Blank27a04fe2011-07-29 21:53:44 -07002511 createAccountManagerAccount(accountManagerContext,
Marc Blank20b511f2011-08-02 14:01:58 -07002512 accountCursor.getString(V21_ACCOUNT_EMAIL),
Marc Blank27a04fe2011-07-29 21:53:44 -07002513 hostAuthCursor.getString(V21_HOSTAUTH_PASSWORD));
Marc Blankf3ff0ba2011-05-19 14:14:14 -07002514 }
2515 }
2516 } finally {
2517 hostAuthCursor.close();
2518 }
2519 }
2520 } finally {
2521 accountCursor.close();
2522 }
2523 } catch (SQLException e) {
2524 // Shouldn't be needed unless we're debugging and interrupt the process
2525 Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
2526 }
2527 }
Todd Kennedy9dcb72e2011-06-03 08:51:25 -07002528
2529 /** Upgrades the database from v22 to v23 */
2530 private static void upgradeFromVersion22ToVersion23(SQLiteDatabase db) {
2531 try {
2532 db.execSQL("alter table " + Mailbox.TABLE_NAME
2533 + " add column " + Mailbox.LAST_TOUCHED_TIME + " integer default 0;");
2534 } catch (SQLException e) {
2535 // Shouldn't be needed unless we're debugging and interrupt the process
2536 Log.w(TAG, "Exception upgrading EmailProvider.db from 22 to 23 " + e);
2537 }
2538 }
Ben Komalo313586c2011-06-07 11:39:16 -07002539
2540 /** Adds in a column for information about a client certificate to use. */
2541 private static void upgradeFromVersion23ToVersion24(SQLiteDatabase db) {
2542 try {
2543 db.execSQL("alter table " + HostAuth.TABLE_NAME
2544 + " add column " + HostAuth.CLIENT_CERT_ALIAS + " text;");
2545 } catch (SQLException e) {
2546 // Shouldn't be needed unless we're debugging and interrupt the process
2547 Log.w(TAG, "Exception upgrading EmailProvider.db from 23 to 24 " + e);
2548 }
2549 }
Jorge Lugo5a3888f2011-06-01 10:09:26 -07002550
2551 /** Upgrades the database from v24 to v25 by creating table for quick responses */
2552 private static void upgradeFromVersion24ToVersion25(SQLiteDatabase db) {
2553 try {
2554 createQuickResponseTable(db);
2555 } catch (SQLException e) {
2556 // Shouldn't be needed unless we're debugging and interrupt the process
2557 Log.w(TAG, "Exception upgrading EmailProvider.db from 24 to 25 " + e);
2558 }
2559 }
Marc Blank6e418aa2011-06-18 18:03:11 -07002560
Marc Blank27a04fe2011-07-29 21:53:44 -07002561 private static final String[] V25_ACCOUNT_PROJECTION =
Marc Blankdeb345a2011-06-23 10:22:25 -07002562 new String[] {AccountColumns.ID, AccountColumns.FLAGS, AccountColumns.HOST_AUTH_KEY_RECV};
Marc Blank27a04fe2011-07-29 21:53:44 -07002563 private static final int V25_ACCOUNT_ID = 0;
2564 private static final int V25_ACCOUNT_FLAGS = 1;
2565 private static final int V25_ACCOUNT_RECV = 2;
2566
2567 private static final String[] V25_HOSTAUTH_PROJECTION = new String[] {HostAuthColumns.PROTOCOL};
2568 private static final int V25_HOSTAUTH_PROTOCOL = 0;
Marc Blankdeb345a2011-06-23 10:22:25 -07002569
2570 /** Upgrades the database from v25 to v26 by adding FLAG_SUPPORTS_SEARCH to IMAP accounts */
2571 private static void upgradeFromVersion25ToVersion26(SQLiteDatabase db) {
2572 try {
2573 // Loop through accounts, looking for imap accounts
Marc Blank27a04fe2011-07-29 21:53:44 -07002574 Cursor accountCursor = db.query(Account.TABLE_NAME, V25_ACCOUNT_PROJECTION, null,
Marc Blankdeb345a2011-06-23 10:22:25 -07002575 null, null, null, null);
2576 ContentValues cv = new ContentValues();
2577 try {
2578 String[] hostAuthArgs = new String[1];
2579 while (accountCursor.moveToNext()) {
Marc Blank27a04fe2011-07-29 21:53:44 -07002580 hostAuthArgs[0] = accountCursor.getString(V25_ACCOUNT_RECV);
Marc Blankdeb345a2011-06-23 10:22:25 -07002581 // Get the "receive" HostAuth for this account
2582 Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
Marc Blank27a04fe2011-07-29 21:53:44 -07002583 V25_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
Marc Blankdeb345a2011-06-23 10:22:25 -07002584 null, null, null);
2585 try {
2586 if (hostAuthCursor.moveToFirst()) {
Marc Blank27a04fe2011-07-29 21:53:44 -07002587 String protocol = hostAuthCursor.getString(V25_HOSTAUTH_PROTOCOL);
Marc Blankdeb345a2011-06-23 10:22:25 -07002588 // If this is an imap account, add the search flag
Marc Blank27a04fe2011-07-29 21:53:44 -07002589 if (HostAuth.SCHEME_IMAP.equals(protocol)) {
2590 String id = accountCursor.getString(V25_ACCOUNT_ID);
2591 int flags = accountCursor.getInt(V25_ACCOUNT_FLAGS);
Marc Blankdeb345a2011-06-23 10:22:25 -07002592 cv.put(AccountColumns.FLAGS, flags | Account.FLAGS_SUPPORTS_SEARCH);
2593 db.update(Account.TABLE_NAME, cv, Account.RECORD_ID + "=?",
2594 new String[] {id});
2595 }
2596 }
2597 } finally {
2598 hostAuthCursor.close();
2599 }
2600 }
2601 } finally {
2602 accountCursor.close();
2603 }
2604 } catch (SQLException e) {
2605 // Shouldn't be needed unless we're debugging and interrupt the process
2606 Log.w(TAG, "Exception upgrading EmailProvider.db from 25 to 26 " + e);
2607 }
2608 }
2609
Marc Blank6e418aa2011-06-18 18:03:11 -07002610 /**
2611 * For testing purposes, check whether a given row is cached
2612 * @param baseUri the base uri of the EmailContent
2613 * @param id the row id of the EmailContent
2614 * @return whether or not the row is currently cached
2615 */
2616 @VisibleForTesting
2617 protected boolean isCached(Uri baseUri, long id) {
2618 int match = findMatch(baseUri, "isCached");
2619 int table = match >> BASE_SHIFT;
2620 ContentCache cache = mContentCaches[table];
2621 if (cache == null) return false;
2622 Cursor cc = cache.get(Long.toString(id));
2623 return (cc != null);
2624 }
Ben Komalo32bed4b2011-08-23 18:02:11 -07002625
2626 public static interface AttachmentService {
2627 /**
2628 * Notify the service that an attachment has changed.
2629 */
2630 void attachmentChanged(Context context, long id, int flags);
2631 }
2632
2633 private final AttachmentService DEFAULT_ATTACHMENT_SERVICE = new AttachmentService() {
2634 @Override
2635 public void attachmentChanged(Context context, long id, int flags) {
2636 // The default implementation delegates to the real service.
2637 AttachmentDownloadService.attachmentChanged(context, id, flags);
2638 }
2639 };
2640 private AttachmentService mAttachmentService = DEFAULT_ATTACHMENT_SERVICE;
2641
2642 /**
2643 * Injects a custom attachment service handler. If null is specified, will reset to the
2644 * default service.
2645 */
2646 public void injectAttachmentService(AttachmentService as) {
2647 mAttachmentService = (as == null) ? DEFAULT_ATTACHMENT_SERVICE : as;
2648 }
Andrew Stadlerf3d5b202009-05-26 16:40:34 -07002649}