EmailProvider.java revision 936babc145e2e6eb2e222f2ce5e3da8f9e4fb9f2
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.email.provider;
18
19import com.android.email.Email;
20import com.android.email.provider.EmailContent.Account;
21import com.android.email.provider.EmailContent.AccountColumns;
22import com.android.email.provider.EmailContent.Attachment;
23import com.android.email.provider.EmailContent.AttachmentColumns;
24import com.android.email.provider.EmailContent.Body;
25import com.android.email.provider.EmailContent.BodyColumns;
26import com.android.email.provider.EmailContent.HostAuth;
27import com.android.email.provider.EmailContent.HostAuthColumns;
28import com.android.email.provider.EmailContent.Mailbox;
29import com.android.email.provider.EmailContent.MailboxColumns;
30import com.android.email.provider.EmailContent.Message;
31import com.android.email.provider.EmailContent.MessageColumns;
32import com.android.email.provider.EmailContent.SyncColumns;
33
34import android.content.ContentProvider;
35import android.content.ContentProviderOperation;
36import android.content.ContentProviderResult;
37import android.content.ContentUris;
38import android.content.ContentValues;
39import android.content.Context;
40import android.content.OperationApplicationException;
41import android.content.UriMatcher;
42import android.database.Cursor;
43import android.database.SQLException;
44import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteOpenHelper;
46import android.net.Uri;
47import android.util.Log;
48
49import java.util.ArrayList;
50
51public class EmailProvider extends ContentProvider {
52
53    private static final String TAG = "EmailProvider";
54
55    static final String DATABASE_NAME = "EmailProvider.db";
56    static final String BODY_DATABASE_NAME = "EmailProviderBody.db";
57
58    // Any changes to the database format *must* include update-in-place code.
59
60    public static final int DATABASE_VERSION = 2;
61    public static final int BODY_DATABASE_VERSION = 2;
62
63    public static final String EMAIL_AUTHORITY = "com.android.email.provider";
64
65    private static final int ACCOUNT_BASE = 0;
66    private static final int ACCOUNT = ACCOUNT_BASE;
67    private static final int ACCOUNT_MAILBOXES = ACCOUNT_BASE + 1;
68    private static final int ACCOUNT_ID = ACCOUNT_BASE + 2;
69    private static final int ACCOUNT_ID_ADD_TO_FIELD = ACCOUNT_BASE + 3;
70
71    private static final int MAILBOX_BASE = 0x1000;
72    private static final int MAILBOX = MAILBOX_BASE;
73    private static final int MAILBOX_MESSAGES = MAILBOX_BASE + 1;
74    private static final int MAILBOX_ID = MAILBOX_BASE + 2;
75    private static final int MAILBOX_ID_ADD_TO_FIELD = MAILBOX_BASE + 3;
76
77    private static final int MESSAGE_BASE = 0x2000;
78    private static final int MESSAGE = MESSAGE_BASE;
79    private static final int MESSAGE_ID = MESSAGE_BASE + 1;
80    private static final int SYNCED_MESSAGE_ID = MESSAGE_BASE + 2;
81
82    private static final int ATTACHMENT_BASE = 0x3000;
83    private static final int ATTACHMENT = ATTACHMENT_BASE;
84    private static final int ATTACHMENT_CONTENT = ATTACHMENT_BASE + 1;
85    private static final int ATTACHMENT_ID = ATTACHMENT_BASE + 2;
86    private static final int ATTACHMENTS_MESSAGE_ID = ATTACHMENT_BASE + 3;
87
88    private static final int HOSTAUTH_BASE = 0x4000;
89    private static final int HOSTAUTH = HOSTAUTH_BASE;
90    private static final int HOSTAUTH_ID = HOSTAUTH_BASE + 1;
91
92    private static final int UPDATED_MESSAGE_BASE = 0x5000;
93    private static final int UPDATED_MESSAGE = UPDATED_MESSAGE_BASE;
94    private static final int UPDATED_MESSAGE_ID = UPDATED_MESSAGE_BASE + 1;
95
96    private static final int DELETED_MESSAGE_BASE = 0x6000;
97    private static final int DELETED_MESSAGE = DELETED_MESSAGE_BASE;
98    private static final int DELETED_MESSAGE_ID = DELETED_MESSAGE_BASE + 1;
99    private static final int DELETED_MESSAGE_MAILBOX = DELETED_MESSAGE_BASE + 2;
100
101    // MUST ALWAYS EQUAL THE LAST OF THE PREVIOUS BASE CONSTANTS
102    private static final int LAST_EMAIL_PROVIDER_DB_BASE = DELETED_MESSAGE_BASE;
103
104    // DO NOT CHANGE BODY_BASE!!
105    private static final int BODY_BASE = LAST_EMAIL_PROVIDER_DB_BASE + 0x1000;
106    private static final int BODY = BODY_BASE;
107    private static final int BODY_ID = BODY_BASE + 1;
108    private static final int BODY_MESSAGE_ID = BODY_BASE + 2;
109    private static final int BODY_HTML = BODY_BASE + 3;
110    private static final int BODY_TEXT = BODY_BASE + 4;
111
112
113    private static final int BASE_SHIFT = 12;  // 12 bits to the base type: 0, 0x1000, 0x2000, etc.
114
115    private static final String[] TABLE_NAMES = {
116        EmailContent.Account.TABLE_NAME,
117        EmailContent.Mailbox.TABLE_NAME,
118        EmailContent.Message.TABLE_NAME,
119        EmailContent.Attachment.TABLE_NAME,
120        EmailContent.HostAuth.TABLE_NAME,
121        EmailContent.Message.UPDATED_TABLE_NAME,
122        EmailContent.Message.DELETED_TABLE_NAME,
123        EmailContent.Body.TABLE_NAME
124    };
125
126    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
127
128    /**
129     * Let's only generate these SQL strings once, as they are used frequently
130     * Note that this isn't relevant for table creation strings, since they are used only once
131     */
132    private static final String UPDATED_MESSAGE_INSERT = "insert or ignore into " +
133        Message.UPDATED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
134        EmailContent.RECORD_ID + '=';
135
136    private static final String UPDATED_MESSAGE_DELETE = "delete from " +
137        Message.UPDATED_TABLE_NAME + " where " + EmailContent.RECORD_ID + '=';
138
139    private static final String DELETED_MESSAGE_INSERT = "insert or replace into " +
140        Message.DELETED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
141        EmailContent.RECORD_ID + '=';
142
143    private static final String DELETE_ORPHAN_BODIES = "delete from " + Body.TABLE_NAME +
144        " where " + BodyColumns.MESSAGE_KEY + " in " + "(select " + BodyColumns.MESSAGE_KEY +
145        " from " + Body.TABLE_NAME + " except select " + EmailContent.RECORD_ID + " from " +
146        Message.TABLE_NAME + ')';
147
148    private static final String DELETE_BODY = "delete from " + Body.TABLE_NAME +
149        " where " + BodyColumns.MESSAGE_KEY + '=';
150
151    private static final String ID_EQUALS = EmailContent.RECORD_ID + "=?";
152
153    static {
154        // Email URI matching table
155        UriMatcher matcher = sURIMatcher;
156
157        // All accounts
158        matcher.addURI(EMAIL_AUTHORITY, "account", ACCOUNT);
159        // A specific account
160        // insert into this URI causes a mailbox to be added to the account
161        matcher.addURI(EMAIL_AUTHORITY, "account/#", ACCOUNT_ID);
162        // The mailboxes in a specific account
163        matcher.addURI(EMAIL_AUTHORITY, "account/#/mailbox", ACCOUNT_MAILBOXES);
164
165        // All mailboxes
166        matcher.addURI(EMAIL_AUTHORITY, "mailbox", MAILBOX);
167        // A specific mailbox
168        // insert into this URI causes a message to be added to the mailbox
169        // ** NOTE For now, the accountKey must be set manually in the values!
170        matcher.addURI(EMAIL_AUTHORITY, "mailbox/#", MAILBOX_ID);
171        // The messages in a specific mailbox
172        matcher.addURI(EMAIL_AUTHORITY, "mailbox/#/message", MAILBOX_MESSAGES);
173
174        // All messages
175        matcher.addURI(EMAIL_AUTHORITY, "message", MESSAGE);
176        // A specific message
177        // insert into this URI causes an attachment to be added to the message
178        matcher.addURI(EMAIL_AUTHORITY, "message/#", MESSAGE_ID);
179
180        // A specific attachment
181        matcher.addURI(EMAIL_AUTHORITY, "attachment", ATTACHMENT);
182        // A specific attachment (the header information)
183        matcher.addURI(EMAIL_AUTHORITY, "attachment/#", ATTACHMENT_ID);
184        // The content for a specific attachment
185        // NOT IMPLEMENTED
186        matcher.addURI(EMAIL_AUTHORITY, "attachment/content/*", ATTACHMENT_CONTENT);
187        // The attachments of a specific message (query only) (insert & delete TBD)
188        matcher.addURI(EMAIL_AUTHORITY, "attachment/message/#", ATTACHMENTS_MESSAGE_ID);
189
190        // All mail bodies
191        matcher.addURI(EMAIL_AUTHORITY, "body", BODY);
192        // A specific mail body
193        matcher.addURI(EMAIL_AUTHORITY, "body/#", BODY_ID);
194        // The body for a specific message
195        matcher.addURI(EMAIL_AUTHORITY, "body/message/#", BODY_MESSAGE_ID);
196        // The HTML part of a specific mail body
197        matcher.addURI(EMAIL_AUTHORITY, "body/#/html", BODY_HTML);
198        // The plain text part of a specific mail body
199        matcher.addURI(EMAIL_AUTHORITY, "body/#/text", BODY_TEXT);
200
201        // All hostauth records
202        matcher.addURI(EMAIL_AUTHORITY, "hostauth", HOSTAUTH);
203        // A specific hostauth
204        matcher.addURI(EMAIL_AUTHORITY, "hostauth/#", HOSTAUTH_ID);
205
206        // Atomically a constant value to a particular field of a mailbox/account
207        matcher.addURI(EMAIL_AUTHORITY, "mailboxIdAddToField/#", MAILBOX_ID_ADD_TO_FIELD);
208        matcher.addURI(EMAIL_AUTHORITY, "accountIdAddToField/#", ACCOUNT_ID_ADD_TO_FIELD);
209
210        /**
211         * THIS URI HAS SPECIAL SEMANTICS
212         * ITS USE IS INTENDED FOR THE UI APPLICATION TO MARK CHANGES THAT NEED TO BE SYNCED BACK
213         * TO A SERVER VIA A SYNC ADAPTER
214         */
215        matcher.addURI(EMAIL_AUTHORITY, "syncedMessage/#", SYNCED_MESSAGE_ID);
216
217        /**
218         * THE URIs BELOW THIS POINT ARE INTENDED TO BE USED BY SYNC ADAPTERS ONLY
219         * THEY REFER TO DATA CREATED AND MAINTAINED BY CALLS TO THE SYNCED_MESSAGE_ID URI
220         * BY THE UI APPLICATION
221         */
222        // All deleted messages
223        matcher.addURI(EMAIL_AUTHORITY, "deletedMessage", DELETED_MESSAGE);
224        // A specific deleted message
225        matcher.addURI(EMAIL_AUTHORITY, "deletedMessage/#", DELETED_MESSAGE_ID);
226        // All deleted messages from a specific mailbox
227        // NOT IMPLEMENTED; do we need this as a convenience?
228        matcher.addURI(EMAIL_AUTHORITY, "deletedMessage/mailbox/#", DELETED_MESSAGE_MAILBOX);
229
230        // All updated messages
231        matcher.addURI(EMAIL_AUTHORITY, "updatedMessage", UPDATED_MESSAGE);
232        // A specific updated message
233        matcher.addURI(EMAIL_AUTHORITY, "updatedMessage/#", UPDATED_MESSAGE_ID);
234    }
235
236    /*
237     * Internal helper method for index creation.
238     * Example:
239     * "create index message_" + MessageColumns.FLAG_READ
240     * + " on " + Message.TABLE_NAME + " (" + MessageColumns.FLAG_READ + ");"
241     */
242    /* package */
243    static String createIndex(String tableName, String columnName) {
244        return "create index " + tableName.toLowerCase() + '_' + columnName
245            + " on " + tableName + " (" + columnName + ");";
246    }
247
248    static void createMessageTable(SQLiteDatabase db) {
249        String messageColumns = MessageColumns.DISPLAY_NAME + " text, "
250            + MessageColumns.TIMESTAMP + " integer, "
251            + MessageColumns.SUBJECT + " text, "
252            + MessageColumns.FLAG_READ + " integer, "
253            + MessageColumns.FLAG_LOADED + " integer, "
254            + MessageColumns.FLAG_FAVORITE + " integer, "
255            + MessageColumns.FLAG_ATTACHMENT + " integer, "
256            + MessageColumns.FLAGS + " integer, "
257            + MessageColumns.CLIENT_ID + " integer, "
258            + MessageColumns.MESSAGE_ID + " text, "
259            + MessageColumns.MAILBOX_KEY + " integer, "
260            + MessageColumns.ACCOUNT_KEY + " integer, "
261            + MessageColumns.FROM_LIST + " text, "
262            + MessageColumns.TO_LIST + " text, "
263            + MessageColumns.CC_LIST + " text, "
264            + MessageColumns.BCC_LIST + " text, "
265            + MessageColumns.REPLY_TO_LIST + " text"
266            + ");";
267
268        // This String and the following String MUST have the same columns, except for the type
269        // of those columns!
270        String createString = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
271            + SyncColumns.SERVER_ID + " integer, "
272            + messageColumns;
273
274        // For the updated and deleted tables, the id is assigned, but we do want to keep track
275        // of the ORDER of updates using an autoincrement primary key.  We use the DATA column
276        // at this point; it has no other function
277        String altCreateString = " (" + EmailContent.RECORD_ID + " integer unique, "
278            + SyncColumns.SERVER_ID + " integer, "
279            + messageColumns;
280
281        // The three tables have the same schema
282        db.execSQL("create table " + Message.TABLE_NAME + createString);
283        db.execSQL("create table " + Message.UPDATED_TABLE_NAME + altCreateString);
284        db.execSQL("create table " + Message.DELETED_TABLE_NAME + altCreateString);
285
286        String indexColumns[] = {
287            MessageColumns.TIMESTAMP,
288            MessageColumns.FLAG_READ,
289            MessageColumns.FLAG_LOADED,
290            MessageColumns.MAILBOX_KEY,
291            SyncColumns.SERVER_ID
292        };
293
294        for (String columnName : indexColumns) {
295            db.execSQL(createIndex(Message.TABLE_NAME, columnName));
296        }
297
298        // Deleting a Message deletes all associated Attachments
299        // Deleting the associated Body cannot be done in a trigger, because the Body is stored
300        // in a separate database, and trigger cannot operate on attached databases.
301        db.execSQL("create trigger message_delete before delete on " + Message.TABLE_NAME +
302                " begin delete from " + Attachment.TABLE_NAME +
303                "  where " + AttachmentColumns.MESSAGE_KEY + "=old." + EmailContent.RECORD_ID +
304                "; end");
305
306        // Add triggers to keep unread count accurate per mailbox
307
308        // Insert a message; if flagRead is zero, add to the unread count of the message's mailbox
309        db.execSQL("create trigger unread_message_insert before insert on " + Message.TABLE_NAME +
310                " when NEW." + MessageColumns.FLAG_READ + "=0" +
311                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
312                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
313                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
314                "; end");
315
316        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
317        db.execSQL("create trigger unread_message_delete before delete on " + Message.TABLE_NAME +
318                " when OLD." + MessageColumns.FLAG_READ + "=0" +
319                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
320                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
321                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
322                "; end");
323
324        // Change a message's mailbox
325        db.execSQL("create trigger unread_message_move before update of " +
326                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
327                " when OLD." + MessageColumns.FLAG_READ + "=0" +
328                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
329                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
330                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
331                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
332                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
333                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
334                "; end");
335
336        // Change a message's read state
337        db.execSQL("create trigger unread_message_read before update of " +
338                MessageColumns.FLAG_READ + " on " + Message.TABLE_NAME +
339                " when OLD." + MessageColumns.FLAG_READ + "!=NEW." + MessageColumns.FLAG_READ +
340                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
341                '=' + MailboxColumns.UNREAD_COUNT + "+ case OLD." + MessageColumns.FLAG_READ +
342                " when 0 then -1 else 1 end" +
343                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
344                "; end");
345   }
346
347    static void upgradeMessageTable(SQLiteDatabase db, int oldVersion, int newVersion) {
348        try {
349            db.execSQL("drop table " + Message.TABLE_NAME);
350            db.execSQL("drop table " + Message.UPDATED_TABLE_NAME);
351            db.execSQL("drop table " + Message.DELETED_TABLE_NAME);
352        } catch (SQLException e) {
353        }
354        createMessageTable(db);
355    }
356
357    static void createAccountTable(SQLiteDatabase db) {
358        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
359            + AccountColumns.DISPLAY_NAME + " text, "
360            + AccountColumns.EMAIL_ADDRESS + " text, "
361            + AccountColumns.SYNC_KEY + " text, "
362            + AccountColumns.SYNC_LOOKBACK + " integer, "
363            + AccountColumns.SYNC_INTERVAL + " text, "
364            + AccountColumns.HOST_AUTH_KEY_RECV + " integer, "
365            + AccountColumns.HOST_AUTH_KEY_SEND + " integer, "
366            + AccountColumns.FLAGS + " integer, "
367            + AccountColumns.IS_DEFAULT + " integer, "
368            + AccountColumns.COMPATIBILITY_UUID + " text, "
369            + AccountColumns.SENDER_NAME + " text, "
370            + AccountColumns.RINGTONE_URI + " text, "
371            + AccountColumns.PROTOCOL_VERSION + " text, "
372            + AccountColumns.NEW_MESSAGE_COUNT + " integer"
373            + ");";
374        db.execSQL("create table " + Account.TABLE_NAME + s);
375        // Deleting an account deletes associated Mailboxes and HostAuth's
376        db.execSQL("create trigger account_delete before delete on " + Account.TABLE_NAME +
377                " begin delete from " + Mailbox.TABLE_NAME +
378                " where " + MailboxColumns.ACCOUNT_KEY + "=old." + EmailContent.RECORD_ID +
379                "; delete from " + HostAuth.TABLE_NAME +
380                " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_RECV +
381                "; delete from " + HostAuth.TABLE_NAME +
382                " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_SEND +
383        "; end");
384    }
385
386    static void upgradeAccountTable(SQLiteDatabase db, int oldVersion, int newVersion) {
387        try {
388            db.execSQL("drop table " +  Account.TABLE_NAME);
389        } catch (SQLException e) {
390        }
391        createAccountTable(db);
392    }
393
394    static void createHostAuthTable(SQLiteDatabase db) {
395        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
396            + HostAuthColumns.PROTOCOL + " text, "
397            + HostAuthColumns.ADDRESS + " text, "
398            + HostAuthColumns.PORT + " integer, "
399            + HostAuthColumns.FLAGS + " integer, "
400            + HostAuthColumns.LOGIN + " text, "
401            + HostAuthColumns.PASSWORD + " text, "
402            + HostAuthColumns.DOMAIN + " text, "
403            + HostAuthColumns.ACCOUNT_KEY + " integer"
404            + ");";
405        db.execSQL("create table " + HostAuth.TABLE_NAME + s);
406    }
407
408    static void upgradeHostAuthTable(SQLiteDatabase db, int oldVersion, int newVersion) {
409        try {
410            db.execSQL("drop table " + HostAuth.TABLE_NAME);
411        } catch (SQLException e) {
412        }
413        createHostAuthTable(db);
414    }
415
416    static void createMailboxTable(SQLiteDatabase db) {
417        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
418            + MailboxColumns.DISPLAY_NAME + " text, "
419            + MailboxColumns.SERVER_ID + " text unique on conflict replace, "
420            + MailboxColumns.PARENT_SERVER_ID + " text, "
421            + MailboxColumns.ACCOUNT_KEY + " integer, "
422            + MailboxColumns.TYPE + " integer, "
423            + MailboxColumns.DELIMITER + " integer, "
424            + MailboxColumns.SYNC_KEY + " text, "
425            + MailboxColumns.SYNC_LOOKBACK + " integer, "
426            + MailboxColumns.SYNC_INTERVAL + " integer, "
427            + MailboxColumns.SYNC_TIME + " integer, "
428            + MailboxColumns.UNREAD_COUNT + " integer, "
429            + MailboxColumns.FLAG_VISIBLE + " integer, "
430            + MailboxColumns.FLAGS + " integer, "
431            + MailboxColumns.VISIBLE_LIMIT + " integer, "
432            + MailboxColumns.SYNC_STATUS + " text"
433            + ");";
434        db.execSQL("create table " + Mailbox.TABLE_NAME + s);
435        db.execSQL("create index mailbox_" + MailboxColumns.SERVER_ID
436                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.SERVER_ID + ")");
437        db.execSQL("create index mailbox_" + MailboxColumns.ACCOUNT_KEY
438                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.ACCOUNT_KEY + ")");
439        // Deleting a Mailbox deletes associated Messages
440        db.execSQL("create trigger mailbox_delete before delete on " + Mailbox.TABLE_NAME +
441                " begin delete from " + Message.TABLE_NAME +
442                "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
443                "; end");
444    }
445
446    static void upgradeMailboxTable(SQLiteDatabase db, int oldVersion, int newVersion) {
447        try {
448            db.execSQL("drop table " + Mailbox.TABLE_NAME);
449        } catch (SQLException e) {
450        }
451        createMailboxTable(db);
452    }
453
454    static void createAttachmentTable(SQLiteDatabase db) {
455        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
456            + AttachmentColumns.FILENAME + " text, "
457            + AttachmentColumns.MIME_TYPE + " text, "
458            + AttachmentColumns.SIZE + " integer, "
459            + AttachmentColumns.CONTENT_ID + " text, "
460            + AttachmentColumns.CONTENT_URI + " text, "
461            + AttachmentColumns.MESSAGE_KEY + " integer, "
462            + AttachmentColumns.LOCATION + " text, "
463            + AttachmentColumns.ENCODING + " text"
464            + ");";
465        db.execSQL("create table " + Attachment.TABLE_NAME + s);
466        db.execSQL(createIndex(Attachment.TABLE_NAME, AttachmentColumns.MESSAGE_KEY));
467    }
468
469    static void upgradeAttachmentTable(SQLiteDatabase db, int oldVersion, int newVersion) {
470        try {
471            db.execSQL("drop table " + Attachment.TABLE_NAME);
472        } catch (SQLException e) {
473        }
474        createAttachmentTable(db);
475    }
476
477    static void createBodyTable(SQLiteDatabase db) {
478        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
479            + BodyColumns.MESSAGE_KEY + " integer, "
480            + BodyColumns.HTML_CONTENT + " text, "
481            + BodyColumns.TEXT_CONTENT + " text, "
482            + BodyColumns.HTML_REPLY + " text, "
483            + BodyColumns.TEXT_REPLY + " text"
484            + ");";
485        db.execSQL("create table " + Body.TABLE_NAME + s);
486        db.execSQL(createIndex(Body.TABLE_NAME, BodyColumns.MESSAGE_KEY));
487    }
488
489    static void upgradeBodyTable(SQLiteDatabase db, int oldVersion, int newVersion) {
490        try {
491            db.execSQL("drop table " + Body.TABLE_NAME);
492        } catch (SQLException e) {
493        }
494        createBodyTable(db);
495    }
496
497    private final int mDatabaseVersion = DATABASE_VERSION;
498    private final int mBodyDatabaseVersion = BODY_DATABASE_VERSION;
499
500    private SQLiteDatabase mDatabase;
501    private SQLiteDatabase mBodyDatabase;
502    private boolean mInTransaction = false;
503
504    public synchronized SQLiteDatabase getDatabase(Context context) {
505        if (mDatabase !=  null) {
506            return mDatabase;
507        }
508        DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
509        mDatabase = helper.getWritableDatabase();
510        if (mDatabase != null) {
511            mDatabase.setLockingEnabled(true);
512            BodyDatabaseHelper bodyHelper = new BodyDatabaseHelper(context, BODY_DATABASE_NAME);
513            mBodyDatabase = bodyHelper.getWritableDatabase();
514            if (mBodyDatabase != null) {
515                mBodyDatabase.setLockingEnabled(true);
516                String bodyFileName = mBodyDatabase.getPath();
517                mDatabase.execSQL("attach \"" + bodyFileName + "\" as BodyDatabase");
518            }
519        }
520        return mDatabase;
521    }
522
523    private class BodyDatabaseHelper extends SQLiteOpenHelper {
524        BodyDatabaseHelper(Context context, String name) {
525            super(context, name, null, mBodyDatabaseVersion);
526        }
527
528        @Override
529        public void onCreate(SQLiteDatabase db) {
530            // Create all tables here; each class has its own method
531            createBodyTable(db);
532        }
533
534        @Override
535        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
536            upgradeBodyTable(db, oldVersion, newVersion);
537        }
538
539        @Override
540        public void onOpen(SQLiteDatabase db) {
541        }
542    }
543
544    private class DatabaseHelper extends SQLiteOpenHelper {
545        DatabaseHelper(Context context, String name) {
546            super(context, name, null, mDatabaseVersion);
547        }
548
549        @Override
550        public void onCreate(SQLiteDatabase db) {
551            // Create all tables here; each class has its own method
552            createMessageTable(db);
553            createAttachmentTable(db);
554            createMailboxTable(db);
555            createHostAuthTable(db);
556            createAccountTable(db);
557        }
558
559        @Override
560        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
561            upgradeMessageTable(db, oldVersion, newVersion);
562            upgradeAttachmentTable(db, oldVersion, newVersion);
563            upgradeMailboxTable(db, oldVersion, newVersion);
564            upgradeHostAuthTable(db, oldVersion, newVersion);
565            upgradeAccountTable(db, oldVersion, newVersion);
566        }
567
568        @Override
569        public void onOpen(SQLiteDatabase db) {
570        }
571    }
572
573    @Override
574    public int delete(Uri uri, String selection, String[] selectionArgs) {
575        final int match = sURIMatcher.match(uri);
576        Context context = getContext();
577        // Pick the correct database for this operation
578        // If we're in a transaction already (which would happen during applyBatch), then the
579        // body database is already attached to the email database and any attempt to use the
580        // body database directly will result in a SQLiteException (the database is locked)
581        SQLiteDatabase db = getDatabase(context);
582        int table = match >> BASE_SHIFT;
583        String id = "0";
584        boolean messageDeletion = false;
585
586        if (Email.LOGD) {
587            Log.v(TAG, "EmailProvider.delete: uri=" + uri + ", match is " + match);
588        }
589
590        int result = -1;
591
592        try {
593            switch (match) {
594                // These are cases in which one or more Messages might get deleted, either by
595                // cascade or explicitly
596                case MAILBOX_ID:
597                case MAILBOX:
598                case ACCOUNT_ID:
599                case ACCOUNT:
600                case MESSAGE:
601                case SYNCED_MESSAGE_ID:
602                case MESSAGE_ID:
603                    // Handle lost Body records here, since this cannot be done in a trigger
604                    // The process is:
605                    //  1) Begin a transaction, ensuring that both databases are affected atomically
606                    //  2) Do the requested deletion, with cascading deletions handled in triggers
607                    //  3) End the transaction, committing all changes atomically
608
609                    messageDeletion = true;
610                    if (!mInTransaction) {
611                        db.beginTransaction();
612                    }
613                    break;
614            }
615            switch (match) {
616                case BODY_ID:
617                case DELETED_MESSAGE_ID:
618                case SYNCED_MESSAGE_ID:
619                case MESSAGE_ID:
620                case UPDATED_MESSAGE_ID:
621                case ATTACHMENT_ID:
622                case MAILBOX_ID:
623                case ACCOUNT_ID:
624                case HOSTAUTH_ID:
625                    id = uri.getPathSegments().get(1);
626                    if (match == SYNCED_MESSAGE_ID) {
627                        // For synced messages, first copy the old message to the deleted table and
628                        // delete it from the updated table (in case it was updated first)
629                        // Note that this is all within a transaction, for atomicity
630                        db.execSQL(DELETED_MESSAGE_INSERT + id);
631                        db.execSQL(UPDATED_MESSAGE_DELETE + id);
632                    }
633                    result = db.delete(TABLE_NAMES[table], whereWithId(id, selection),
634                            selectionArgs);
635                    break;
636                case BODY:
637                case MESSAGE:
638                case DELETED_MESSAGE:
639                case UPDATED_MESSAGE:
640                case ATTACHMENT:
641                case MAILBOX:
642                case ACCOUNT:
643                case HOSTAUTH:
644                    result = db.delete(TABLE_NAMES[table], selection, selectionArgs);
645                    break;
646                default:
647                    throw new IllegalArgumentException("Unknown URI " + uri);
648            }
649            if (messageDeletion) {
650                if (match == MESSAGE_ID) {
651                    // Delete the Body record associated with the deleted message
652                    db.execSQL(DELETE_BODY + id);
653                } else {
654                    // Delete any orphaned Body records
655                    db.execSQL(DELETE_ORPHAN_BODIES);
656                }
657                if (!mInTransaction) {
658                    db.setTransactionSuccessful();
659                }
660            }
661        } finally {
662            if (messageDeletion) {
663                if (!mInTransaction) {
664                    db.endTransaction();
665                }
666            }
667        }
668        getContext().getContentResolver().notifyChange(uri, null);
669        return result;
670    }
671
672    @Override
673    // Use the email- prefix because message, mailbox, and account are so generic (e.g. SMS, IM)
674    public String getType(Uri uri) {
675        int match = sURIMatcher.match(uri);
676        switch (match) {
677            case BODY_ID:
678                return "vnd.android.cursor.item/email-body";
679            case BODY:
680                return "vnd.android.cursor.dir/email-message";
681            case UPDATED_MESSAGE_ID:
682            case MESSAGE_ID:
683                return "vnd.android.cursor.item/email-message";
684            case MAILBOX_MESSAGES:
685            case UPDATED_MESSAGE:
686            case MESSAGE:
687                return "vnd.android.cursor.dir/email-message";
688            case ACCOUNT_MAILBOXES:
689            case MAILBOX:
690                return "vnd.android.cursor.dir/email-mailbox";
691            case MAILBOX_ID:
692                return "vnd.android.cursor.item/email-mailbox";
693            case ACCOUNT:
694                return "vnd.android.cursor.dir/email-account";
695            case ACCOUNT_ID:
696                return "vnd.android.cursor.item/email-account";
697            case ATTACHMENTS_MESSAGE_ID:
698            case ATTACHMENT:
699                return "vnd.android.cursor.dir/email-attachment";
700            case ATTACHMENT_ID:
701                return "vnd.android.cursor.item/email-attachment";
702            case HOSTAUTH:
703                return "vnd.android.cursor.dir/email-hostauth";
704            case HOSTAUTH_ID:
705                return "vnd.android.cursor.item/email-hostauth";
706            default:
707                throw new IllegalArgumentException("Unknown URI " + uri);
708        }
709    }
710
711    @Override
712    public Uri insert(Uri uri, ContentValues values) {
713        int match = sURIMatcher.match(uri);
714        Context context = getContext();
715        // See the comment at delete(), above
716        SQLiteDatabase db = getDatabase(context);
717        int table = match >> BASE_SHIFT;
718        long id;
719
720        if (Email.LOGD) {
721            Log.v(TAG, "EmailProvider.insert: uri=" + uri + ", match is " + match);
722        }
723
724        Uri resultUri = null;
725
726        switch (match) {
727            case BODY:
728            case MESSAGE:
729            case ATTACHMENT:
730            case MAILBOX:
731            case ACCOUNT:
732            case HOSTAUTH:
733                id = db.insert(TABLE_NAMES[table], "foo", values);
734                resultUri = ContentUris.withAppendedId(uri, id);
735                break;
736            case MAILBOX_ID:
737                // This implies adding a message to a mailbox
738                // Hmm, one problem here is that we can't link the account as well, so it must be
739                // already in the values...
740                id = Long.parseLong(uri.getPathSegments().get(1));
741                values.put(MessageColumns.MAILBOX_KEY, id);
742                resultUri = insert(Message.CONTENT_URI, values);
743                break;
744            case MESSAGE_ID:
745                // This implies adding an attachment to a message.
746                id = Long.parseLong(uri.getPathSegments().get(1));
747                values.put(AttachmentColumns.MESSAGE_KEY, id);
748                resultUri = insert(Attachment.CONTENT_URI, values);
749                break;
750            case ACCOUNT_ID:
751                // This implies adding a mailbox to an account.
752                id = Long.parseLong(uri.getPathSegments().get(1));
753                values.put(MailboxColumns.ACCOUNT_KEY, id);
754                resultUri = insert(Mailbox.CONTENT_URI, values);
755                break;
756            case ATTACHMENTS_MESSAGE_ID:
757                id = db.insert(TABLE_NAMES[table], "foo", values);
758                resultUri = ContentUris.withAppendedId(Attachment.CONTENT_URI, id);
759                break;
760            default:
761                throw new IllegalArgumentException("Unknown URL " + uri);
762        }
763
764        // Notify with the base uri, not the new uri (nobody is watching a new record)
765        getContext().getContentResolver().notifyChange(uri, null);
766        return resultUri;
767    }
768
769    @Override
770    public boolean onCreate() {
771        // TODO Auto-generated method stub
772        return false;
773    }
774
775    @Override
776    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
777            String sortOrder) {
778        Cursor c = null;
779        Uri notificationUri = EmailContent.CONTENT_URI;
780        int match = sURIMatcher.match(uri);
781        Context context = getContext();
782        // See the comment at delete(), above
783        SQLiteDatabase db = getDatabase(context);
784        int table = match >> BASE_SHIFT;
785        String id;
786
787        if (Email.LOGD) {
788            Log.v(TAG, "EmailProvider.query: uri=" + uri + ", match is " + match);
789        }
790
791        switch (match) {
792            case BODY:
793            case MESSAGE:
794            case UPDATED_MESSAGE:
795            case DELETED_MESSAGE:
796            case ATTACHMENT:
797            case MAILBOX:
798            case ACCOUNT:
799            case HOSTAUTH:
800                c = db.query(TABLE_NAMES[table], projection,
801                        selection, selectionArgs, null, null, sortOrder);
802                break;
803            case BODY_ID:
804            case MESSAGE_ID:
805            case DELETED_MESSAGE_ID:
806            case UPDATED_MESSAGE_ID:
807            case ATTACHMENT_ID:
808            case MAILBOX_ID:
809            case ACCOUNT_ID:
810            case HOSTAUTH_ID:
811                id = uri.getPathSegments().get(1);
812                c = db.query(TABLE_NAMES[table], projection,
813                        whereWithId(id, selection), selectionArgs, null, null, sortOrder);
814                break;
815            case ATTACHMENTS_MESSAGE_ID:
816                // All attachments for the given message
817                id = uri.getPathSegments().get(2);
818                c = db.query(Attachment.TABLE_NAME, projection,
819                        whereWith(Attachment.MESSAGE_KEY + "=" + id, selection),
820                        selectionArgs, null, null, sortOrder);
821                break;
822            default:
823                throw new IllegalArgumentException("Unknown URI " + uri);
824        }
825
826        if ((c != null) && !isTemporary()) {
827            c.setNotificationUri(getContext().getContentResolver(), notificationUri);
828        }
829        return c;
830    }
831
832    private String whereWithId(String id, String selection) {
833        StringBuilder sb = new StringBuilder(256);
834        sb.append("_id=");
835        sb.append(id);
836        if (selection != null) {
837            sb.append(" AND ");
838            sb.append(selection);
839        }
840        return sb.toString();
841    }
842
843    private String whereWith(String where, String selection) {
844        StringBuilder sb = new StringBuilder(where);
845        if (selection != null) {
846            sb.append(" AND ");
847            sb.append(selection);
848        }
849        return sb.toString();
850    }
851
852    @Override
853    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
854        int match = sURIMatcher.match(uri);
855        Context context = getContext();
856        // See the comment at delete(), above
857        SQLiteDatabase db = getDatabase(context);
858        int table = match >> BASE_SHIFT;
859        int result;
860
861        if (Email.LOGD) {
862            Log.v(TAG, "EmailProvider.update: uri=" + uri + ", match is " + match);
863        }
864
865        // We do NOT allow setting of unreadCount via the provider
866        // This column is maintained via triggers
867        if (match == MAILBOX_ID || match == MAILBOX) {
868            values.remove(MailboxColumns.UNREAD_COUNT);
869        }
870
871        String id;
872        switch (match) {
873            case MAILBOX_ID_ADD_TO_FIELD:
874            case ACCOUNT_ID_ADD_TO_FIELD:
875                if (!mInTransaction) {
876                    db.beginTransaction();
877                }
878                id = uri.getPathSegments().get(1);
879                String field = values.getAsString(EmailContent.FIELD_COLUMN_NAME);
880                Long add = values.getAsLong(EmailContent.ADD_COLUMN_NAME);
881                if (field == null || add == null) {
882                    throw new IllegalArgumentException("No field/add specified " + uri);
883                }
884                Cursor c = db.query(TABLE_NAMES[table],
885                        new String[] {EmailContent.RECORD_ID, field}, whereWithId(id, selection),
886                        selectionArgs, null, null, null);
887                try {
888                    result = 0;
889                    ContentValues cv = new ContentValues();
890                    String[] bind = new String[1];
891                    while (c.moveToNext()) {
892                        bind[0] = c.getString(0);
893                        long value = c.getLong(1) + add;
894                        cv.put(field, value);
895                        result = db.update(TABLE_NAMES[table], cv, ID_EQUALS, bind);
896                    }
897                } finally {
898                    c.close();
899                }
900                if (!mInTransaction) {
901                    db.setTransactionSuccessful();
902                    db.endTransaction();
903                }
904                break;
905            case BODY_ID:
906            case MESSAGE_ID:
907            case SYNCED_MESSAGE_ID:
908            case UPDATED_MESSAGE_ID:
909            case ATTACHMENT_ID:
910            case MAILBOX_ID:
911            case ACCOUNT_ID:
912            case HOSTAUTH_ID:
913                id = uri.getPathSegments().get(1);
914                if (match == SYNCED_MESSAGE_ID) {
915                    // For synced messages, first copy the old message to the updated table
916                    // Note the insert or ignore semantics, guaranteeing that only the first
917                    // update will be reflected in the updated message table; therefore this row
918                    // will always have the "original" data
919                    db.execSQL(UPDATED_MESSAGE_INSERT + id);
920                } else if (match == MESSAGE_ID) {
921                    db.execSQL(UPDATED_MESSAGE_DELETE + id);
922                }
923                result = db.update(TABLE_NAMES[table], values, whereWithId(id, selection),
924                        selectionArgs);
925                break;
926            case BODY:
927            case MESSAGE:
928            case UPDATED_MESSAGE:
929            case ATTACHMENT:
930            case MAILBOX:
931            case ACCOUNT:
932            case HOSTAUTH:
933                result = db.update(TABLE_NAMES[table], values, selection, selectionArgs);
934                break;
935            default:
936                throw new IllegalArgumentException("Unknown URI " + uri);
937        }
938
939        getContext().getContentResolver().notifyChange(uri, null);
940        return result;
941    }
942
943    /* (non-Javadoc)
944     * @see android.content.ContentProvider#applyBatch(android.content.ContentProviderOperation)
945     */
946    @Override
947    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
948            throws OperationApplicationException {
949        Context context = getContext();
950        SQLiteDatabase db = getDatabase(context);
951        db.beginTransaction();
952        mInTransaction = true;
953        try {
954            ContentProviderResult[] results = super.applyBatch(operations);
955            db.setTransactionSuccessful();
956            return results;
957        } finally {
958            db.endTransaction();
959            mInTransaction = false;
960        }
961    }
962}
963