ContactsProvider2.java revision 80952e03e425a04ea2fd77e3ff44a8453ffdefe1
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.providers.contacts;
18
19import com.android.internal.content.SyncStateContentProviderHelper;
20import com.android.providers.contacts.ContactLookupKey.LookupKeySegment;
21import com.android.providers.contacts.ContactsDatabaseHelper.AggregatedPresenceColumns;
22import com.android.providers.contacts.ContactsDatabaseHelper.AggregationExceptionColumns;
23import com.android.providers.contacts.ContactsDatabaseHelper.Clauses;
24import com.android.providers.contacts.ContactsDatabaseHelper.ContactsColumns;
25import com.android.providers.contacts.ContactsDatabaseHelper.ContactsStatusUpdatesColumns;
26import com.android.providers.contacts.ContactsDatabaseHelper.DataColumns;
27import com.android.providers.contacts.ContactsDatabaseHelper.GroupsColumns;
28import com.android.providers.contacts.ContactsDatabaseHelper.MimetypesColumns;
29import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupColumns;
30import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupType;
31import com.android.providers.contacts.ContactsDatabaseHelper.PhoneColumns;
32import com.android.providers.contacts.ContactsDatabaseHelper.PhoneLookupColumns;
33import com.android.providers.contacts.ContactsDatabaseHelper.PresenceColumns;
34import com.android.providers.contacts.ContactsDatabaseHelper.RawContactsColumns;
35import com.android.providers.contacts.ContactsDatabaseHelper.SettingsColumns;
36import com.android.providers.contacts.ContactsDatabaseHelper.StatusUpdatesColumns;
37import com.android.providers.contacts.ContactsDatabaseHelper.Tables;
38import com.google.android.collect.Lists;
39import com.google.android.collect.Maps;
40import com.google.android.collect.Sets;
41
42import android.accounts.Account;
43import android.accounts.AccountManager;
44import android.accounts.OnAccountsUpdateListener;
45import android.app.Notification;
46import android.app.NotificationManager;
47import android.app.PendingIntent;
48import android.app.SearchManager;
49import android.content.ContentProviderOperation;
50import android.content.ContentProviderResult;
51import android.content.ContentResolver;
52import android.content.ContentUris;
53import android.content.ContentValues;
54import android.content.Context;
55import android.content.IContentService;
56import android.content.Intent;
57import android.content.OperationApplicationException;
58import android.content.SharedPreferences;
59import android.content.SyncAdapterType;
60import android.content.UriMatcher;
61import android.content.res.AssetFileDescriptor;
62import android.content.res.Configuration;
63import android.database.CharArrayBuffer;
64import android.database.Cursor;
65import android.database.CursorWrapper;
66import android.database.DatabaseUtils;
67import android.database.MatrixCursor;
68import android.database.MatrixCursor.RowBuilder;
69import android.database.sqlite.SQLiteConstraintException;
70import android.database.sqlite.SQLiteContentHelper;
71import android.database.sqlite.SQLiteDatabase;
72import android.database.sqlite.SQLiteQueryBuilder;
73import android.database.sqlite.SQLiteStatement;
74import android.net.Uri;
75import android.os.AsyncTask;
76import android.os.Bundle;
77import android.os.MemoryFile;
78import android.os.RemoteException;
79import android.os.SystemProperties;
80import android.pim.vcard.VCardComposer;
81import android.pim.vcard.VCardConfig;
82import android.preference.PreferenceManager;
83import android.provider.BaseColumns;
84import android.provider.ContactsContract;
85import android.provider.LiveFolders;
86import android.provider.OpenableColumns;
87import android.provider.SyncStateContract;
88import android.provider.ContactsContract.AggregationExceptions;
89import android.provider.ContactsContract.ContactCounts;
90import android.provider.ContactsContract.Contacts;
91import android.provider.ContactsContract.Data;
92import android.provider.ContactsContract.DisplayNameSources;
93import android.provider.ContactsContract.FullNameStyle;
94import android.provider.ContactsContract.Groups;
95import android.provider.ContactsContract.Intents;
96import android.provider.ContactsContract.PhoneLookup;
97import android.provider.ContactsContract.PhoneticNameStyle;
98import android.provider.ContactsContract.ProviderStatus;
99import android.provider.ContactsContract.RawContacts;
100import android.provider.ContactsContract.SearchSnippetColumns;
101import android.provider.ContactsContract.Settings;
102import android.provider.ContactsContract.StatusUpdates;
103import android.provider.ContactsContract.CommonDataKinds.BaseTypes;
104import android.provider.ContactsContract.CommonDataKinds.Email;
105import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
106import android.provider.ContactsContract.CommonDataKinds.Im;
107import android.provider.ContactsContract.CommonDataKinds.Nickname;
108import android.provider.ContactsContract.CommonDataKinds.Organization;
109import android.provider.ContactsContract.CommonDataKinds.Phone;
110import android.provider.ContactsContract.CommonDataKinds.Photo;
111import android.provider.ContactsContract.CommonDataKinds.StructuredName;
112import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
113import android.telephony.PhoneNumberUtils;
114import android.text.TextUtils;
115import android.util.Log;
116
117import java.io.ByteArrayOutputStream;
118import java.io.FileNotFoundException;
119import java.io.IOException;
120import java.io.OutputStream;
121import java.text.SimpleDateFormat;
122import java.util.ArrayList;
123import java.util.Collections;
124import java.util.Date;
125import java.util.HashMap;
126import java.util.HashSet;
127import java.util.List;
128import java.util.Locale;
129import java.util.Map;
130import java.util.Set;
131import java.util.concurrent.CountDownLatch;
132
133/**
134 * Contacts content provider. The contract between this provider and applications
135 * is defined in {@link ContactsContract}.
136 */
137public class ContactsProvider2 extends SQLiteContentProvider implements OnAccountsUpdateListener {
138
139    private static final String TAG = "ContactsProvider";
140
141    private static final boolean VERBOSE_LOGGING = Log.isLoggable(TAG, Log.VERBOSE);
142
143    // TODO: carefully prevent all incoming nested queries; they can be gaping security holes
144    // TODO: check for restricted flag during insert(), update(), and delete() calls
145
146    /** Default for the maximum number of returned aggregation suggestions. */
147    private static final int DEFAULT_MAX_SUGGESTIONS = 5;
148
149    private static final String GOOGLE_MY_CONTACTS_GROUP_TITLE = "System Group: My Contacts";
150    /**
151     * Property key for the legacy contact import version. The need for a version
152     * as opposed to a boolean flag is that if we discover bugs in the contact import process,
153     * we can trigger re-import by incrementing the import version.
154     */
155    private static final String PROPERTY_CONTACTS_IMPORTED = "contacts_imported_v1";
156    private static final int PROPERTY_CONTACTS_IMPORT_VERSION = 1;
157    private static final String PREF_LOCALE = "locale";
158
159    private static final String AGGREGATE_CONTACTS = "sync.contacts.aggregate";
160
161    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
162
163    private static final String TIMES_CONTACED_SORT_COLUMN = "times_contacted_sort";
164
165    private static final String STREQUENT_ORDER_BY = Contacts.STARRED + " DESC, "
166            + TIMES_CONTACED_SORT_COLUMN + " DESC, "
167            + Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
168    private static final String STREQUENT_LIMIT =
169            "(SELECT COUNT(1) FROM " + Tables.CONTACTS + " WHERE "
170            + Contacts.STARRED + "=1) + 25";
171
172    /* package */ static final String UPDATE_TIMES_CONTACTED_CONTACTS_TABLE =
173            "UPDATE " + Tables.CONTACTS + " SET " + Contacts.TIMES_CONTACTED + "=" +
174            " CASE WHEN " + Contacts.TIMES_CONTACTED + " IS NULL THEN 1 ELSE " +
175            " (" + Contacts.TIMES_CONTACTED + " + 1) END WHERE " + Contacts._ID + "=?";
176
177    /* package */ static final String UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE =
178            "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.TIMES_CONTACTED + "=" +
179            " CASE WHEN " + RawContacts.TIMES_CONTACTED + " IS NULL THEN 1 ELSE " +
180            " (" + RawContacts.TIMES_CONTACTED + " + 1) END WHERE " + RawContacts.CONTACT_ID + "=?";
181
182    /* package */ static final String PHONEBOOK_COLLATOR_NAME = "PHONEBOOK";
183
184    private static final int CONTACTS = 1000;
185    private static final int CONTACTS_ID = 1001;
186    private static final int CONTACTS_LOOKUP = 1002;
187    private static final int CONTACTS_LOOKUP_ID = 1003;
188    private static final int CONTACTS_DATA = 1004;
189    private static final int CONTACTS_FILTER = 1005;
190    private static final int CONTACTS_STREQUENT = 1006;
191    private static final int CONTACTS_STREQUENT_FILTER = 1007;
192    private static final int CONTACTS_GROUP = 1008;
193    private static final int CONTACTS_PHOTO = 1009;
194    private static final int CONTACTS_AS_VCARD = 1010;
195    private static final int CONTACTS_AS_MULTI_VCARD = 1011;
196
197    private static final int RAW_CONTACTS = 2002;
198    private static final int RAW_CONTACTS_ID = 2003;
199    private static final int RAW_CONTACTS_DATA = 2004;
200    private static final int RAW_CONTACT_ENTITY_ID = 2005;
201
202    private static final int DATA = 3000;
203    private static final int DATA_ID = 3001;
204    private static final int PHONES = 3002;
205    private static final int PHONES_ID = 3003;
206    private static final int PHONES_FILTER = 3004;
207    private static final int EMAILS = 3005;
208    private static final int EMAILS_ID = 3006;
209    private static final int EMAILS_LOOKUP = 3007;
210    private static final int EMAILS_FILTER = 3008;
211    private static final int POSTALS = 3009;
212    private static final int POSTALS_ID = 3010;
213
214    private static final int PHONE_LOOKUP = 4000;
215
216    private static final int AGGREGATION_EXCEPTIONS = 6000;
217    private static final int AGGREGATION_EXCEPTION_ID = 6001;
218
219    private static final int STATUS_UPDATES = 7000;
220    private static final int STATUS_UPDATES_ID = 7001;
221
222    private static final int AGGREGATION_SUGGESTIONS = 8000;
223
224    private static final int SETTINGS = 9000;
225
226    private static final int GROUPS = 10000;
227    private static final int GROUPS_ID = 10001;
228    private static final int GROUPS_SUMMARY = 10003;
229
230    private static final int SYNCSTATE = 11000;
231    private static final int SYNCSTATE_ID = 11001;
232
233    private static final int SEARCH_SUGGESTIONS = 12001;
234    private static final int SEARCH_SHORTCUT = 12002;
235
236    private static final int LIVE_FOLDERS_CONTACTS = 14000;
237    private static final int LIVE_FOLDERS_CONTACTS_WITH_PHONES = 14001;
238    private static final int LIVE_FOLDERS_CONTACTS_FAVORITES = 14002;
239    private static final int LIVE_FOLDERS_CONTACTS_GROUP_NAME = 14003;
240
241    private static final int RAW_CONTACT_ENTITIES = 15001;
242
243    private static final int PROVIDER_STATUS = 16001;
244
245    private interface DataContactsQuery {
246        public static final String TABLE = "data "
247                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
248                + "JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
249
250        public static final String[] PROJECTION = new String[] {
251            RawContactsColumns.CONCRETE_ID,
252            DataColumns.CONCRETE_ID,
253            ContactsColumns.CONCRETE_ID
254        };
255
256        public static final int RAW_CONTACT_ID = 0;
257        public static final int DATA_ID = 1;
258        public static final int CONTACT_ID = 2;
259    }
260
261    private interface DataDeleteQuery {
262        public static final String TABLE = Tables.DATA_JOIN_MIMETYPES;
263
264        public static final String[] CONCRETE_COLUMNS = new String[] {
265            DataColumns.CONCRETE_ID,
266            MimetypesColumns.MIMETYPE,
267            Data.RAW_CONTACT_ID,
268            Data.IS_PRIMARY,
269            Data.DATA1,
270        };
271
272        public static final String[] COLUMNS = new String[] {
273            Data._ID,
274            MimetypesColumns.MIMETYPE,
275            Data.RAW_CONTACT_ID,
276            Data.IS_PRIMARY,
277            Data.DATA1,
278        };
279
280        public static final int _ID = 0;
281        public static final int MIMETYPE = 1;
282        public static final int RAW_CONTACT_ID = 2;
283        public static final int IS_PRIMARY = 3;
284        public static final int DATA1 = 4;
285    }
286
287    private interface DataUpdateQuery {
288        String[] COLUMNS = { Data._ID, Data.RAW_CONTACT_ID, Data.MIMETYPE };
289
290        int _ID = 0;
291        int RAW_CONTACT_ID = 1;
292        int MIMETYPE = 2;
293    }
294
295
296    private interface RawContactsQuery {
297        String TABLE = Tables.RAW_CONTACTS;
298
299        String[] COLUMNS = new String[] {
300                RawContacts.DELETED,
301                RawContacts.ACCOUNT_TYPE,
302                RawContacts.ACCOUNT_NAME,
303        };
304
305        int DELETED = 0;
306        int ACCOUNT_TYPE = 1;
307        int ACCOUNT_NAME = 2;
308    }
309
310    public static final String DEFAULT_ACCOUNT_TYPE = "com.google";
311    public static final String FEATURE_LEGACY_HOSTED_OR_GOOGLE = "legacy_hosted_or_google";
312
313    /** Sql where statement for filtering on groups. */
314    private static final String CONTACTS_IN_GROUP_SELECT =
315            Contacts._ID + " IN "
316                    + "(SELECT " + RawContacts.CONTACT_ID
317                    + " FROM " + Tables.RAW_CONTACTS
318                    + " WHERE " + RawContactsColumns.CONCRETE_ID + " IN "
319                            + "(SELECT " + DataColumns.CONCRETE_RAW_CONTACT_ID
320                            + " FROM " + Tables.DATA_JOIN_MIMETYPES
321                            + " WHERE " + Data.MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
322                                    + "' AND " + GroupMembership.GROUP_ROW_ID + "="
323                                    + "(SELECT " + Tables.GROUPS + "." + Groups._ID
324                                    + " FROM " + Tables.GROUPS
325                                    + " WHERE " + Groups.TITLE + "=?)))";
326
327    /** Sql for updating DIRTY flag on multiple raw contacts */
328    private static final String UPDATE_RAW_CONTACT_SET_DIRTY_SQL =
329            "UPDATE " + Tables.RAW_CONTACTS +
330            " SET " + RawContacts.DIRTY + "=1" +
331            " WHERE " + RawContacts._ID + " IN (";
332
333    /** Sql for updating VERSION on multiple raw contacts */
334    private static final String UPDATE_RAW_CONTACT_SET_VERSION_SQL =
335            "UPDATE " + Tables.RAW_CONTACTS +
336            " SET " + RawContacts.VERSION + " = " + RawContacts.VERSION + " + 1" +
337            " WHERE " + RawContacts._ID + " IN (";
338
339    /** Name lookup types used for contact filtering */
340    private static final String CONTACT_LOOKUP_NAME_TYPES =
341            NameLookupType.NAME_COLLATION_KEY + "," +
342            NameLookupType.EMAIL_BASED_NICKNAME + "," +
343            NameLookupType.NICKNAME + "," +
344            NameLookupType.NAME_SHORTHAND + "," +
345            NameLookupType.ORGANIZATION + "," +
346            NameLookupType.NAME_CONSONANTS;
347
348
349    /** Contains just BaseColumns._COUNT */
350    private static final HashMap<String, String> sCountProjectionMap;
351    /** Contains just the contacts columns */
352    private static final HashMap<String, String> sContactsProjectionMap;
353    /** Contains just the contacts columns */
354    private static final HashMap<String, String> sContactsProjectionWithSnippetMap;
355
356    /** Used for pushing starred contacts to the top of a times contacted list **/
357    private static final HashMap<String, String> sStrequentStarredProjectionMap;
358    private static final HashMap<String, String> sStrequentFrequentProjectionMap;
359    /** Contains just the contacts vCard columns */
360    private static final HashMap<String, String> sContactsVCardProjectionMap;
361    /** Contains just the raw contacts columns */
362    private static final HashMap<String, String> sRawContactsProjectionMap;
363    /** Contains the columns from the raw contacts entity view*/
364    private static final HashMap<String, String> sRawContactsEntityProjectionMap;
365    /** Contains columns from the data view */
366    private static final HashMap<String, String> sDataProjectionMap;
367    /** Contains columns from the data view */
368    private static final HashMap<String, String> sDistinctDataProjectionMap;
369    /** Contains the data and contacts columns, for joined tables */
370    private static final HashMap<String, String> sPhoneLookupProjectionMap;
371    /** Contains the just the {@link Groups} columns */
372    private static final HashMap<String, String> sGroupsProjectionMap;
373    /** Contains {@link Groups} columns along with summary details */
374    private static final HashMap<String, String> sGroupsSummaryProjectionMap;
375    /** Contains the agg_exceptions columns */
376    private static final HashMap<String, String> sAggregationExceptionsProjectionMap;
377    /** Contains the agg_exceptions columns */
378    private static final HashMap<String, String> sSettingsProjectionMap;
379    /** Contains StatusUpdates columns */
380    private static final HashMap<String, String> sStatusUpdatesProjectionMap;
381    /** Contains Live Folders columns */
382    private static final HashMap<String, String> sLiveFoldersProjectionMap;
383
384    // where clause to update the status_updates table
385    private static final String WHERE_CLAUSE_FOR_STATUS_UPDATES_TABLE =
386            StatusUpdatesColumns.DATA_ID + " IN (SELECT Distinct " + StatusUpdates.DATA_ID +
387            " FROM " + Tables.STATUS_UPDATES + " LEFT OUTER JOIN " + Tables.PRESENCE +
388            " ON " + StatusUpdatesColumns.DATA_ID + " = " + StatusUpdates.DATA_ID + " WHERE ";
389
390    private static final String[] EMPTY_STRING_ARRAY = new String[0];
391
392    /**
393     * Notification ID for failure to import contacts.
394     */
395    private static final int LEGACY_IMPORT_FAILED_NOTIFICATION = 1;
396
397    /** Precompiled sql statement for setting a data record to the primary. */
398    private SQLiteStatement mSetPrimaryStatement;
399    /** Precompiled sql statement for setting a data record to the super primary. */
400    private SQLiteStatement mSetSuperPrimaryStatement;
401    /** Precompiled sql statement for updating a contact display name */
402    private SQLiteStatement mRawContactDisplayNameUpdate;
403    /** Precompiled sql statement for updating an aggregated status update */
404    private SQLiteStatement mLastStatusUpdate;
405    private SQLiteStatement mNameLookupInsert;
406    private SQLiteStatement mNameLookupDelete;
407    private SQLiteStatement mStatusUpdateAutoTimestamp;
408    private SQLiteStatement mStatusUpdateInsert;
409    private SQLiteStatement mStatusUpdateReplace;
410    private SQLiteStatement mStatusAttributionUpdate;
411    private SQLiteStatement mStatusUpdateDelete;
412    private SQLiteStatement mResetNameVerifiedForOtherRawContacts;
413
414    private long mMimeTypeIdEmail;
415    private long mMimeTypeIdIm;
416    private long mMimeTypeIdStructuredName;
417    private long mMimeTypeIdOrganization;
418    private long mMimeTypeIdNickname;
419    private long mMimeTypeIdPhone;
420    private StringBuilder mSb = new StringBuilder();
421    private String[] mSelectionArgs1 = new String[1];
422    private String[] mSelectionArgs2 = new String[2];
423    private ArrayList<String> mSelectionArgs = Lists.newArrayList();
424
425    private Account mAccount;
426
427    static {
428        // Contacts URI matching table
429        final UriMatcher matcher = sUriMatcher;
430        matcher.addURI(ContactsContract.AUTHORITY, "contacts", CONTACTS);
431        matcher.addURI(ContactsContract.AUTHORITY, "contacts/#", CONTACTS_ID);
432        matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/data", CONTACTS_DATA);
433        matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions",
434                AGGREGATION_SUGGESTIONS);
435        matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions/*",
436                AGGREGATION_SUGGESTIONS);
437        matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/photo", CONTACTS_PHOTO);
438        matcher.addURI(ContactsContract.AUTHORITY, "contacts/filter/*", CONTACTS_FILTER);
439        matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*", CONTACTS_LOOKUP);
440        matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#", CONTACTS_LOOKUP_ID);
441        matcher.addURI(ContactsContract.AUTHORITY, "contacts/as_vcard/*", CONTACTS_AS_VCARD);
442        matcher.addURI(ContactsContract.AUTHORITY, "contacts/as_multi_vcard/*",
443                CONTACTS_AS_MULTI_VCARD);
444        matcher.addURI(ContactsContract.AUTHORITY, "contacts/strequent/", CONTACTS_STREQUENT);
445        matcher.addURI(ContactsContract.AUTHORITY, "contacts/strequent/filter/*",
446                CONTACTS_STREQUENT_FILTER);
447        matcher.addURI(ContactsContract.AUTHORITY, "contacts/group/*", CONTACTS_GROUP);
448
449        matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts", RAW_CONTACTS);
450        matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#", RAW_CONTACTS_ID);
451        matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/data", RAW_CONTACTS_DATA);
452        matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/entity", RAW_CONTACT_ENTITY_ID);
453
454        matcher.addURI(ContactsContract.AUTHORITY, "raw_contact_entities", RAW_CONTACT_ENTITIES);
455
456        matcher.addURI(ContactsContract.AUTHORITY, "data", DATA);
457        matcher.addURI(ContactsContract.AUTHORITY, "data/#", DATA_ID);
458        matcher.addURI(ContactsContract.AUTHORITY, "data/phones", PHONES);
459        matcher.addURI(ContactsContract.AUTHORITY, "data/phones/#", PHONES_ID);
460        matcher.addURI(ContactsContract.AUTHORITY, "data/phones/filter", PHONES_FILTER);
461        matcher.addURI(ContactsContract.AUTHORITY, "data/phones/filter/*", PHONES_FILTER);
462        matcher.addURI(ContactsContract.AUTHORITY, "data/emails", EMAILS);
463        matcher.addURI(ContactsContract.AUTHORITY, "data/emails/#", EMAILS_ID);
464        matcher.addURI(ContactsContract.AUTHORITY, "data/emails/lookup/*", EMAILS_LOOKUP);
465        matcher.addURI(ContactsContract.AUTHORITY, "data/emails/filter", EMAILS_FILTER);
466        matcher.addURI(ContactsContract.AUTHORITY, "data/emails/filter/*", EMAILS_FILTER);
467        matcher.addURI(ContactsContract.AUTHORITY, "data/postals", POSTALS);
468        matcher.addURI(ContactsContract.AUTHORITY, "data/postals/#", POSTALS_ID);
469
470        matcher.addURI(ContactsContract.AUTHORITY, "groups", GROUPS);
471        matcher.addURI(ContactsContract.AUTHORITY, "groups/#", GROUPS_ID);
472        matcher.addURI(ContactsContract.AUTHORITY, "groups_summary", GROUPS_SUMMARY);
473
474        matcher.addURI(ContactsContract.AUTHORITY, SyncStateContentProviderHelper.PATH, SYNCSTATE);
475        matcher.addURI(ContactsContract.AUTHORITY, SyncStateContentProviderHelper.PATH + "/#",
476                SYNCSTATE_ID);
477
478        matcher.addURI(ContactsContract.AUTHORITY, "phone_lookup/*", PHONE_LOOKUP);
479        matcher.addURI(ContactsContract.AUTHORITY, "aggregation_exceptions",
480                AGGREGATION_EXCEPTIONS);
481        matcher.addURI(ContactsContract.AUTHORITY, "aggregation_exceptions/*",
482                AGGREGATION_EXCEPTION_ID);
483
484        matcher.addURI(ContactsContract.AUTHORITY, "settings", SETTINGS);
485
486        matcher.addURI(ContactsContract.AUTHORITY, "status_updates", STATUS_UPDATES);
487        matcher.addURI(ContactsContract.AUTHORITY, "status_updates/#", STATUS_UPDATES_ID);
488
489        matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,
490                SEARCH_SUGGESTIONS);
491        matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
492                SEARCH_SUGGESTIONS);
493        matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*",
494                SEARCH_SHORTCUT);
495
496        matcher.addURI(ContactsContract.AUTHORITY, "live_folders/contacts",
497                LIVE_FOLDERS_CONTACTS);
498        matcher.addURI(ContactsContract.AUTHORITY, "live_folders/contacts/*",
499                LIVE_FOLDERS_CONTACTS_GROUP_NAME);
500        matcher.addURI(ContactsContract.AUTHORITY, "live_folders/contacts_with_phones",
501                LIVE_FOLDERS_CONTACTS_WITH_PHONES);
502        matcher.addURI(ContactsContract.AUTHORITY, "live_folders/favorites",
503                LIVE_FOLDERS_CONTACTS_FAVORITES);
504
505        matcher.addURI(ContactsContract.AUTHORITY, "provider_status", PROVIDER_STATUS);
506    }
507
508    static {
509        sCountProjectionMap = new HashMap<String, String>();
510        sCountProjectionMap.put(BaseColumns._COUNT, "COUNT(*)");
511
512        sContactsProjectionMap = new HashMap<String, String>();
513        sContactsProjectionMap.put(Contacts._ID, Contacts._ID);
514        sContactsProjectionMap.put(Contacts.DISPLAY_NAME, Contacts.DISPLAY_NAME_PRIMARY);
515        sContactsProjectionMap.put(Contacts.DISPLAY_NAME_ALTERNATIVE,
516                Contacts.DISPLAY_NAME_ALTERNATIVE);
517        sContactsProjectionMap.put(Contacts.DISPLAY_NAME_SOURCE, Contacts.DISPLAY_NAME_SOURCE);
518        sContactsProjectionMap.put(Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME);
519        sContactsProjectionMap.put(Contacts.PHONETIC_NAME_STYLE, Contacts.PHONETIC_NAME_STYLE);
520        sContactsProjectionMap.put(Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_PRIMARY);
521        sContactsProjectionMap.put(Contacts.SORT_KEY_ALTERNATIVE, Contacts.SORT_KEY_ALTERNATIVE);
522        sContactsProjectionMap.put(Contacts.LAST_TIME_CONTACTED, Contacts.LAST_TIME_CONTACTED);
523        sContactsProjectionMap.put(Contacts.TIMES_CONTACTED, Contacts.TIMES_CONTACTED);
524        sContactsProjectionMap.put(Contacts.STARRED, Contacts.STARRED);
525        sContactsProjectionMap.put(Contacts.IN_VISIBLE_GROUP, Contacts.IN_VISIBLE_GROUP);
526        sContactsProjectionMap.put(Contacts.PHOTO_ID, Contacts.PHOTO_ID);
527        sContactsProjectionMap.put(Contacts.CUSTOM_RINGTONE, Contacts.CUSTOM_RINGTONE);
528        sContactsProjectionMap.put(Contacts.HAS_PHONE_NUMBER, Contacts.HAS_PHONE_NUMBER);
529        sContactsProjectionMap.put(Contacts.SEND_TO_VOICEMAIL, Contacts.SEND_TO_VOICEMAIL);
530        sContactsProjectionMap.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY);
531
532        // Handle projections for Contacts-level statuses
533        addProjection(sContactsProjectionMap, Contacts.CONTACT_PRESENCE,
534                Tables.AGGREGATED_PRESENCE + "." + StatusUpdates.PRESENCE);
535        addProjection(sContactsProjectionMap, Contacts.CONTACT_STATUS,
536                ContactsStatusUpdatesColumns.CONCRETE_STATUS);
537        addProjection(sContactsProjectionMap, Contacts.CONTACT_STATUS_TIMESTAMP,
538                ContactsStatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP);
539        addProjection(sContactsProjectionMap, Contacts.CONTACT_STATUS_RES_PACKAGE,
540                ContactsStatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE);
541        addProjection(sContactsProjectionMap, Contacts.CONTACT_STATUS_LABEL,
542                ContactsStatusUpdatesColumns.CONCRETE_STATUS_LABEL);
543        addProjection(sContactsProjectionMap, Contacts.CONTACT_STATUS_ICON,
544                ContactsStatusUpdatesColumns.CONCRETE_STATUS_ICON);
545
546        sContactsProjectionWithSnippetMap = new HashMap<String, String>();
547        sContactsProjectionWithSnippetMap.putAll(sContactsProjectionMap);
548        sContactsProjectionWithSnippetMap.put(SearchSnippetColumns.SNIPPET_MIMETYPE,
549                SearchSnippetColumns.SNIPPET_MIMETYPE);
550        sContactsProjectionWithSnippetMap.put(SearchSnippetColumns.SNIPPET_DATA_ID,
551                SearchSnippetColumns.SNIPPET_DATA_ID);
552        sContactsProjectionWithSnippetMap.put(SearchSnippetColumns.SNIPPET_DATA1,
553                SearchSnippetColumns.SNIPPET_DATA1);
554        sContactsProjectionWithSnippetMap.put(SearchSnippetColumns.SNIPPET_DATA2,
555                SearchSnippetColumns.SNIPPET_DATA2);
556        sContactsProjectionWithSnippetMap.put(SearchSnippetColumns.SNIPPET_DATA3,
557                SearchSnippetColumns.SNIPPET_DATA3);
558        sContactsProjectionWithSnippetMap.put(SearchSnippetColumns.SNIPPET_DATA4,
559                SearchSnippetColumns.SNIPPET_DATA4);
560
561        sStrequentStarredProjectionMap = new HashMap<String, String>(sContactsProjectionMap);
562        sStrequentStarredProjectionMap.put(TIMES_CONTACED_SORT_COLUMN,
563                  Long.MAX_VALUE + " AS " + TIMES_CONTACED_SORT_COLUMN);
564
565        sStrequentFrequentProjectionMap = new HashMap<String, String>(sContactsProjectionMap);
566        sStrequentFrequentProjectionMap.put(TIMES_CONTACED_SORT_COLUMN,
567                  Contacts.TIMES_CONTACTED + " AS " + TIMES_CONTACED_SORT_COLUMN);
568
569        sContactsVCardProjectionMap = Maps.newHashMap();
570        sContactsVCardProjectionMap.put(OpenableColumns.DISPLAY_NAME, Contacts.DISPLAY_NAME
571                + " || '.vcf' AS " + OpenableColumns.DISPLAY_NAME);
572        sContactsVCardProjectionMap.put(OpenableColumns.SIZE, "NULL AS " + OpenableColumns.SIZE);
573
574        sRawContactsProjectionMap = new HashMap<String, String>();
575        sRawContactsProjectionMap.put(RawContacts._ID, RawContacts._ID);
576        sRawContactsProjectionMap.put(RawContacts.CONTACT_ID, RawContacts.CONTACT_ID);
577        sRawContactsProjectionMap.put(RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_NAME);
578        sRawContactsProjectionMap.put(RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_TYPE);
579        sRawContactsProjectionMap.put(RawContacts.SOURCE_ID, RawContacts.SOURCE_ID);
580        sRawContactsProjectionMap.put(RawContacts.VERSION, RawContacts.VERSION);
581        sRawContactsProjectionMap.put(RawContacts.DIRTY, RawContacts.DIRTY);
582        sRawContactsProjectionMap.put(RawContacts.DELETED, RawContacts.DELETED);
583        sRawContactsProjectionMap.put(RawContacts.DISPLAY_NAME_PRIMARY,
584                RawContacts.DISPLAY_NAME_PRIMARY);
585        sRawContactsProjectionMap.put(RawContacts.DISPLAY_NAME_ALTERNATIVE,
586                RawContacts.DISPLAY_NAME_ALTERNATIVE);
587        sRawContactsProjectionMap.put(RawContacts.DISPLAY_NAME_SOURCE,
588                RawContacts.DISPLAY_NAME_SOURCE);
589        sRawContactsProjectionMap.put(RawContacts.PHONETIC_NAME,
590                RawContacts.PHONETIC_NAME);
591        sRawContactsProjectionMap.put(RawContacts.PHONETIC_NAME_STYLE,
592                RawContacts.PHONETIC_NAME_STYLE);
593        sRawContactsProjectionMap.put(RawContacts.NAME_VERIFIED,
594                RawContacts.NAME_VERIFIED);
595        sRawContactsProjectionMap.put(RawContacts.SORT_KEY_PRIMARY,
596                RawContacts.SORT_KEY_PRIMARY);
597        sRawContactsProjectionMap.put(RawContacts.SORT_KEY_ALTERNATIVE,
598                RawContacts.SORT_KEY_ALTERNATIVE);
599        sRawContactsProjectionMap.put(RawContacts.TIMES_CONTACTED, RawContacts.TIMES_CONTACTED);
600        sRawContactsProjectionMap.put(RawContacts.LAST_TIME_CONTACTED,
601                RawContacts.LAST_TIME_CONTACTED);
602        sRawContactsProjectionMap.put(RawContacts.CUSTOM_RINGTONE, RawContacts.CUSTOM_RINGTONE);
603        sRawContactsProjectionMap.put(RawContacts.SEND_TO_VOICEMAIL, RawContacts.SEND_TO_VOICEMAIL);
604        sRawContactsProjectionMap.put(RawContacts.STARRED, RawContacts.STARRED);
605        sRawContactsProjectionMap.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE);
606        sRawContactsProjectionMap.put(RawContacts.SYNC1, RawContacts.SYNC1);
607        sRawContactsProjectionMap.put(RawContacts.SYNC2, RawContacts.SYNC2);
608        sRawContactsProjectionMap.put(RawContacts.SYNC3, RawContacts.SYNC3);
609        sRawContactsProjectionMap.put(RawContacts.SYNC4, RawContacts.SYNC4);
610
611        sDataProjectionMap = new HashMap<String, String>();
612        sDataProjectionMap.put(Data._ID, Data._ID);
613        sDataProjectionMap.put(Data.RAW_CONTACT_ID, Data.RAW_CONTACT_ID);
614        sDataProjectionMap.put(Data.DATA_VERSION, Data.DATA_VERSION);
615        sDataProjectionMap.put(Data.IS_PRIMARY, Data.IS_PRIMARY);
616        sDataProjectionMap.put(Data.IS_SUPER_PRIMARY, Data.IS_SUPER_PRIMARY);
617        sDataProjectionMap.put(Data.RES_PACKAGE, Data.RES_PACKAGE);
618        sDataProjectionMap.put(Data.MIMETYPE, Data.MIMETYPE);
619        sDataProjectionMap.put(Data.DATA1, Data.DATA1);
620        sDataProjectionMap.put(Data.DATA2, Data.DATA2);
621        sDataProjectionMap.put(Data.DATA3, Data.DATA3);
622        sDataProjectionMap.put(Data.DATA4, Data.DATA4);
623        sDataProjectionMap.put(Data.DATA5, Data.DATA5);
624        sDataProjectionMap.put(Data.DATA6, Data.DATA6);
625        sDataProjectionMap.put(Data.DATA7, Data.DATA7);
626        sDataProjectionMap.put(Data.DATA8, Data.DATA8);
627        sDataProjectionMap.put(Data.DATA9, Data.DATA9);
628        sDataProjectionMap.put(Data.DATA10, Data.DATA10);
629        sDataProjectionMap.put(Data.DATA11, Data.DATA11);
630        sDataProjectionMap.put(Data.DATA12, Data.DATA12);
631        sDataProjectionMap.put(Data.DATA13, Data.DATA13);
632        sDataProjectionMap.put(Data.DATA14, Data.DATA14);
633        sDataProjectionMap.put(Data.DATA15, Data.DATA15);
634        sDataProjectionMap.put(Data.SYNC1, Data.SYNC1);
635        sDataProjectionMap.put(Data.SYNC2, Data.SYNC2);
636        sDataProjectionMap.put(Data.SYNC3, Data.SYNC3);
637        sDataProjectionMap.put(Data.SYNC4, Data.SYNC4);
638        sDataProjectionMap.put(Data.CONTACT_ID, Data.CONTACT_ID);
639        sDataProjectionMap.put(RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_NAME);
640        sDataProjectionMap.put(RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_TYPE);
641        sDataProjectionMap.put(RawContacts.SOURCE_ID, RawContacts.SOURCE_ID);
642        sDataProjectionMap.put(RawContacts.VERSION, RawContacts.VERSION);
643        sDataProjectionMap.put(RawContacts.DIRTY, RawContacts.DIRTY);
644        sDataProjectionMap.put(RawContacts.NAME_VERIFIED, RawContacts.NAME_VERIFIED);
645        sDataProjectionMap.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY);
646        sDataProjectionMap.put(Contacts.DISPLAY_NAME, Contacts.DISPLAY_NAME);
647        sDataProjectionMap.put(Contacts.DISPLAY_NAME_ALTERNATIVE,
648                Contacts.DISPLAY_NAME_ALTERNATIVE);
649        sDataProjectionMap.put(Contacts.DISPLAY_NAME_SOURCE, Contacts.DISPLAY_NAME_SOURCE);
650        sDataProjectionMap.put(Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME);
651        sDataProjectionMap.put(Contacts.PHONETIC_NAME_STYLE, Contacts.PHONETIC_NAME_STYLE);
652        sDataProjectionMap.put(Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_PRIMARY);
653        sDataProjectionMap.put(Contacts.SORT_KEY_ALTERNATIVE, Contacts.SORT_KEY_ALTERNATIVE);
654        sDataProjectionMap.put(Contacts.CUSTOM_RINGTONE, Contacts.CUSTOM_RINGTONE);
655        sDataProjectionMap.put(Contacts.SEND_TO_VOICEMAIL, Contacts.SEND_TO_VOICEMAIL);
656        sDataProjectionMap.put(Contacts.LAST_TIME_CONTACTED, Contacts.LAST_TIME_CONTACTED);
657        sDataProjectionMap.put(Contacts.TIMES_CONTACTED, Contacts.TIMES_CONTACTED);
658        sDataProjectionMap.put(Contacts.STARRED, Contacts.STARRED);
659        sDataProjectionMap.put(Contacts.PHOTO_ID, Contacts.PHOTO_ID);
660        sDataProjectionMap.put(Contacts.IN_VISIBLE_GROUP, Contacts.IN_VISIBLE_GROUP);
661        sDataProjectionMap.put(Contacts.NAME_RAW_CONTACT_ID, Contacts.NAME_RAW_CONTACT_ID);
662        sDataProjectionMap.put(GroupMembership.GROUP_SOURCE_ID, GroupMembership.GROUP_SOURCE_ID);
663
664        HashMap<String, String> columns;
665        columns = new HashMap<String, String>();
666        columns.put(RawContacts._ID, RawContacts._ID);
667        columns.put(RawContacts.CONTACT_ID, RawContacts.CONTACT_ID);
668        columns.put(RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_NAME);
669        columns.put(RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_TYPE);
670        columns.put(RawContacts.SOURCE_ID, RawContacts.SOURCE_ID);
671        columns.put(RawContacts.VERSION, RawContacts.VERSION);
672        columns.put(RawContacts.DIRTY, RawContacts.DIRTY);
673        columns.put(RawContacts.DELETED, RawContacts.DELETED);
674        columns.put(RawContacts.IS_RESTRICTED, RawContacts.IS_RESTRICTED);
675        columns.put(RawContacts.SYNC1, RawContacts.SYNC1);
676        columns.put(RawContacts.SYNC2, RawContacts.SYNC2);
677        columns.put(RawContacts.SYNC3, RawContacts.SYNC3);
678        columns.put(RawContacts.SYNC4, RawContacts.SYNC4);
679        columns.put(RawContacts.NAME_VERIFIED, RawContacts.NAME_VERIFIED);
680        columns.put(Data.RES_PACKAGE, Data.RES_PACKAGE);
681        columns.put(Data.MIMETYPE, Data.MIMETYPE);
682        columns.put(Data.DATA1, Data.DATA1);
683        columns.put(Data.DATA2, Data.DATA2);
684        columns.put(Data.DATA3, Data.DATA3);
685        columns.put(Data.DATA4, Data.DATA4);
686        columns.put(Data.DATA5, Data.DATA5);
687        columns.put(Data.DATA6, Data.DATA6);
688        columns.put(Data.DATA7, Data.DATA7);
689        columns.put(Data.DATA8, Data.DATA8);
690        columns.put(Data.DATA9, Data.DATA9);
691        columns.put(Data.DATA10, Data.DATA10);
692        columns.put(Data.DATA11, Data.DATA11);
693        columns.put(Data.DATA12, Data.DATA12);
694        columns.put(Data.DATA13, Data.DATA13);
695        columns.put(Data.DATA14, Data.DATA14);
696        columns.put(Data.DATA15, Data.DATA15);
697        columns.put(Data.SYNC1, Data.SYNC1);
698        columns.put(Data.SYNC2, Data.SYNC2);
699        columns.put(Data.SYNC3, Data.SYNC3);
700        columns.put(Data.SYNC4, Data.SYNC4);
701        columns.put(RawContacts.Entity.DATA_ID, RawContacts.Entity.DATA_ID);
702        columns.put(Data.STARRED, Data.STARRED);
703        columns.put(Data.DATA_VERSION, Data.DATA_VERSION);
704        columns.put(Data.IS_PRIMARY, Data.IS_PRIMARY);
705        columns.put(Data.IS_SUPER_PRIMARY, Data.IS_SUPER_PRIMARY);
706        columns.put(GroupMembership.GROUP_SOURCE_ID, GroupMembership.GROUP_SOURCE_ID);
707        sRawContactsEntityProjectionMap = columns;
708
709        // Handle projections for Contacts-level statuses
710        addProjection(sDataProjectionMap, Contacts.CONTACT_PRESENCE,
711                Tables.AGGREGATED_PRESENCE + "." + StatusUpdates.PRESENCE);
712        addProjection(sDataProjectionMap, Contacts.CONTACT_STATUS,
713                ContactsStatusUpdatesColumns.CONCRETE_STATUS);
714        addProjection(sDataProjectionMap, Contacts.CONTACT_STATUS_TIMESTAMP,
715                ContactsStatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP);
716        addProjection(sDataProjectionMap, Contacts.CONTACT_STATUS_RES_PACKAGE,
717                ContactsStatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE);
718        addProjection(sDataProjectionMap, Contacts.CONTACT_STATUS_LABEL,
719                ContactsStatusUpdatesColumns.CONCRETE_STATUS_LABEL);
720        addProjection(sDataProjectionMap, Contacts.CONTACT_STATUS_ICON,
721                ContactsStatusUpdatesColumns.CONCRETE_STATUS_ICON);
722
723        // Handle projections for Data-level statuses
724        addProjection(sDataProjectionMap, Data.PRESENCE,
725                Tables.PRESENCE + "." + StatusUpdates.PRESENCE);
726        addProjection(sDataProjectionMap, Data.STATUS,
727                StatusUpdatesColumns.CONCRETE_STATUS);
728        addProjection(sDataProjectionMap, Data.STATUS_TIMESTAMP,
729                StatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP);
730        addProjection(sDataProjectionMap, Data.STATUS_RES_PACKAGE,
731                StatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE);
732        addProjection(sDataProjectionMap, Data.STATUS_LABEL,
733                StatusUpdatesColumns.CONCRETE_STATUS_LABEL);
734        addProjection(sDataProjectionMap, Data.STATUS_ICON,
735                StatusUpdatesColumns.CONCRETE_STATUS_ICON);
736
737        // Projection map for data grouped by contact (not raw contact) and some data field(s)
738        sDistinctDataProjectionMap = new HashMap<String, String>();
739        sDistinctDataProjectionMap.put(Data._ID,
740                "MIN(" + Data._ID + ") AS " + Data._ID);
741        sDistinctDataProjectionMap.put(Data.DATA_VERSION, Data.DATA_VERSION);
742        sDistinctDataProjectionMap.put(Data.IS_PRIMARY, Data.IS_PRIMARY);
743        sDistinctDataProjectionMap.put(Data.IS_SUPER_PRIMARY, Data.IS_SUPER_PRIMARY);
744        sDistinctDataProjectionMap.put(Data.RES_PACKAGE, Data.RES_PACKAGE);
745        sDistinctDataProjectionMap.put(Data.MIMETYPE, Data.MIMETYPE);
746        sDistinctDataProjectionMap.put(Data.DATA1, Data.DATA1);
747        sDistinctDataProjectionMap.put(Data.DATA2, Data.DATA2);
748        sDistinctDataProjectionMap.put(Data.DATA3, Data.DATA3);
749        sDistinctDataProjectionMap.put(Data.DATA4, Data.DATA4);
750        sDistinctDataProjectionMap.put(Data.DATA5, Data.DATA5);
751        sDistinctDataProjectionMap.put(Data.DATA6, Data.DATA6);
752        sDistinctDataProjectionMap.put(Data.DATA7, Data.DATA7);
753        sDistinctDataProjectionMap.put(Data.DATA8, Data.DATA8);
754        sDistinctDataProjectionMap.put(Data.DATA9, Data.DATA9);
755        sDistinctDataProjectionMap.put(Data.DATA10, Data.DATA10);
756        sDistinctDataProjectionMap.put(Data.DATA11, Data.DATA11);
757        sDistinctDataProjectionMap.put(Data.DATA12, Data.DATA12);
758        sDistinctDataProjectionMap.put(Data.DATA13, Data.DATA13);
759        sDistinctDataProjectionMap.put(Data.DATA14, Data.DATA14);
760        sDistinctDataProjectionMap.put(Data.DATA15, Data.DATA15);
761        sDistinctDataProjectionMap.put(Data.SYNC1, Data.SYNC1);
762        sDistinctDataProjectionMap.put(Data.SYNC2, Data.SYNC2);
763        sDistinctDataProjectionMap.put(Data.SYNC3, Data.SYNC3);
764        sDistinctDataProjectionMap.put(Data.SYNC4, Data.SYNC4);
765        sDistinctDataProjectionMap.put(RawContacts.CONTACT_ID, RawContacts.CONTACT_ID);
766        sDistinctDataProjectionMap.put(Contacts.LOOKUP_KEY, Contacts.LOOKUP_KEY);
767        sDistinctDataProjectionMap.put(Contacts.DISPLAY_NAME, Contacts.DISPLAY_NAME);
768        sDistinctDataProjectionMap.put(Contacts.DISPLAY_NAME_ALTERNATIVE,
769                Contacts.DISPLAY_NAME_ALTERNATIVE);
770        sDistinctDataProjectionMap.put(Contacts.DISPLAY_NAME_SOURCE, Contacts.DISPLAY_NAME_SOURCE);
771        sDistinctDataProjectionMap.put(Contacts.PHONETIC_NAME, Contacts.PHONETIC_NAME);
772        sDistinctDataProjectionMap.put(Contacts.PHONETIC_NAME_STYLE, Contacts.PHONETIC_NAME_STYLE);
773        sDistinctDataProjectionMap.put(Contacts.SORT_KEY_PRIMARY, Contacts.SORT_KEY_PRIMARY);
774        sDistinctDataProjectionMap.put(Contacts.SORT_KEY_ALTERNATIVE,
775                Contacts.SORT_KEY_ALTERNATIVE);
776        sDistinctDataProjectionMap.put(Contacts.CUSTOM_RINGTONE, Contacts.CUSTOM_RINGTONE);
777        sDistinctDataProjectionMap.put(Contacts.SEND_TO_VOICEMAIL, Contacts.SEND_TO_VOICEMAIL);
778        sDistinctDataProjectionMap.put(Contacts.LAST_TIME_CONTACTED, Contacts.LAST_TIME_CONTACTED);
779        sDistinctDataProjectionMap.put(Contacts.TIMES_CONTACTED, Contacts.TIMES_CONTACTED);
780        sDistinctDataProjectionMap.put(Contacts.STARRED, Contacts.STARRED);
781        sDistinctDataProjectionMap.put(Contacts.PHOTO_ID, Contacts.PHOTO_ID);
782        sDistinctDataProjectionMap.put(Contacts.IN_VISIBLE_GROUP, Contacts.IN_VISIBLE_GROUP);
783        sDistinctDataProjectionMap.put(GroupMembership.GROUP_SOURCE_ID,
784                GroupMembership.GROUP_SOURCE_ID);
785
786        // Handle projections for Contacts-level statuses
787        addProjection(sDistinctDataProjectionMap, Contacts.CONTACT_PRESENCE,
788                Tables.AGGREGATED_PRESENCE + "." + StatusUpdates.PRESENCE);
789        addProjection(sDistinctDataProjectionMap, Contacts.CONTACT_STATUS,
790                ContactsStatusUpdatesColumns.CONCRETE_STATUS);
791        addProjection(sDistinctDataProjectionMap, Contacts.CONTACT_STATUS_TIMESTAMP,
792                ContactsStatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP);
793        addProjection(sDistinctDataProjectionMap, Contacts.CONTACT_STATUS_RES_PACKAGE,
794                ContactsStatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE);
795        addProjection(sDistinctDataProjectionMap, Contacts.CONTACT_STATUS_LABEL,
796                ContactsStatusUpdatesColumns.CONCRETE_STATUS_LABEL);
797        addProjection(sDistinctDataProjectionMap, Contacts.CONTACT_STATUS_ICON,
798                ContactsStatusUpdatesColumns.CONCRETE_STATUS_ICON);
799
800        // Handle projections for Data-level statuses
801        addProjection(sDistinctDataProjectionMap, Data.PRESENCE,
802                Tables.PRESENCE + "." + StatusUpdates.PRESENCE);
803        addProjection(sDistinctDataProjectionMap, Data.STATUS,
804                StatusUpdatesColumns.CONCRETE_STATUS);
805        addProjection(sDistinctDataProjectionMap, Data.STATUS_TIMESTAMP,
806                StatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP);
807        addProjection(sDistinctDataProjectionMap, Data.STATUS_RES_PACKAGE,
808                StatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE);
809        addProjection(sDistinctDataProjectionMap, Data.STATUS_LABEL,
810                StatusUpdatesColumns.CONCRETE_STATUS_LABEL);
811        addProjection(sDistinctDataProjectionMap, Data.STATUS_ICON,
812                StatusUpdatesColumns.CONCRETE_STATUS_ICON);
813
814        sPhoneLookupProjectionMap = new HashMap<String, String>();
815        sPhoneLookupProjectionMap.put(PhoneLookup._ID,
816                "contacts_view." + Contacts._ID
817                        + " AS " + PhoneLookup._ID);
818        sPhoneLookupProjectionMap.put(PhoneLookup.LOOKUP_KEY,
819                "contacts_view." + Contacts.LOOKUP_KEY
820                        + " AS " + PhoneLookup.LOOKUP_KEY);
821        sPhoneLookupProjectionMap.put(PhoneLookup.DISPLAY_NAME,
822                "contacts_view." + Contacts.DISPLAY_NAME
823                        + " AS " + PhoneLookup.DISPLAY_NAME);
824        sPhoneLookupProjectionMap.put(PhoneLookup.LAST_TIME_CONTACTED,
825                "contacts_view." + Contacts.LAST_TIME_CONTACTED
826                        + " AS " + PhoneLookup.LAST_TIME_CONTACTED);
827        sPhoneLookupProjectionMap.put(PhoneLookup.TIMES_CONTACTED,
828                "contacts_view." + Contacts.TIMES_CONTACTED
829                        + " AS " + PhoneLookup.TIMES_CONTACTED);
830        sPhoneLookupProjectionMap.put(PhoneLookup.STARRED,
831                "contacts_view." + Contacts.STARRED
832                        + " AS " + PhoneLookup.STARRED);
833        sPhoneLookupProjectionMap.put(PhoneLookup.IN_VISIBLE_GROUP,
834                "contacts_view." + Contacts.IN_VISIBLE_GROUP
835                        + " AS " + PhoneLookup.IN_VISIBLE_GROUP);
836        sPhoneLookupProjectionMap.put(PhoneLookup.PHOTO_ID,
837                "contacts_view." + Contacts.PHOTO_ID
838                        + " AS " + PhoneLookup.PHOTO_ID);
839        sPhoneLookupProjectionMap.put(PhoneLookup.CUSTOM_RINGTONE,
840                "contacts_view." + Contacts.CUSTOM_RINGTONE
841                        + " AS " + PhoneLookup.CUSTOM_RINGTONE);
842        sPhoneLookupProjectionMap.put(PhoneLookup.HAS_PHONE_NUMBER,
843                "contacts_view." + Contacts.HAS_PHONE_NUMBER
844                        + " AS " + PhoneLookup.HAS_PHONE_NUMBER);
845        sPhoneLookupProjectionMap.put(PhoneLookup.SEND_TO_VOICEMAIL,
846                "contacts_view." + Contacts.SEND_TO_VOICEMAIL
847                        + " AS " + PhoneLookup.SEND_TO_VOICEMAIL);
848        sPhoneLookupProjectionMap.put(PhoneLookup.NUMBER,
849                Phone.NUMBER + " AS " + PhoneLookup.NUMBER);
850        sPhoneLookupProjectionMap.put(PhoneLookup.TYPE,
851                Phone.TYPE + " AS " + PhoneLookup.TYPE);
852        sPhoneLookupProjectionMap.put(PhoneLookup.LABEL,
853                Phone.LABEL + " AS " + PhoneLookup.LABEL);
854
855        // Groups projection map
856        columns = new HashMap<String, String>();
857        columns.put(Groups._ID, Groups._ID);
858        columns.put(Groups.ACCOUNT_NAME, Groups.ACCOUNT_NAME);
859        columns.put(Groups.ACCOUNT_TYPE, Groups.ACCOUNT_TYPE);
860        columns.put(Groups.SOURCE_ID, Groups.SOURCE_ID);
861        columns.put(Groups.DIRTY, Groups.DIRTY);
862        columns.put(Groups.VERSION, Groups.VERSION);
863        columns.put(Groups.RES_PACKAGE, Groups.RES_PACKAGE);
864        columns.put(Groups.TITLE, Groups.TITLE);
865        columns.put(Groups.TITLE_RES, Groups.TITLE_RES);
866        columns.put(Groups.GROUP_VISIBLE, Groups.GROUP_VISIBLE);
867        columns.put(Groups.SYSTEM_ID, Groups.SYSTEM_ID);
868        columns.put(Groups.DELETED, Groups.DELETED);
869        columns.put(Groups.NOTES, Groups.NOTES);
870        columns.put(Groups.SHOULD_SYNC, Groups.SHOULD_SYNC);
871        columns.put(Groups.SYNC1, Groups.SYNC1);
872        columns.put(Groups.SYNC2, Groups.SYNC2);
873        columns.put(Groups.SYNC3, Groups.SYNC3);
874        columns.put(Groups.SYNC4, Groups.SYNC4);
875        sGroupsProjectionMap = columns;
876
877        // RawContacts and groups projection map
878        columns = new HashMap<String, String>();
879        columns.putAll(sGroupsProjectionMap);
880        columns.put(Groups.SUMMARY_COUNT, "(SELECT COUNT(DISTINCT " + ContactsColumns.CONCRETE_ID
881                + ") FROM " + Tables.DATA_JOIN_MIMETYPES_RAW_CONTACTS_CONTACTS + " WHERE "
882                + Clauses.MIMETYPE_IS_GROUP_MEMBERSHIP + " AND " + Clauses.BELONGS_TO_GROUP
883                + ") AS " + Groups.SUMMARY_COUNT);
884        columns.put(Groups.SUMMARY_WITH_PHONES, "(SELECT COUNT(DISTINCT "
885                + ContactsColumns.CONCRETE_ID + ") FROM "
886                + Tables.DATA_JOIN_MIMETYPES_RAW_CONTACTS_CONTACTS + " WHERE "
887                + Clauses.MIMETYPE_IS_GROUP_MEMBERSHIP + " AND " + Clauses.BELONGS_TO_GROUP
888                + " AND " + Contacts.HAS_PHONE_NUMBER + ") AS " + Groups.SUMMARY_WITH_PHONES);
889        sGroupsSummaryProjectionMap = columns;
890
891        // Aggregate exception projection map
892        columns = new HashMap<String, String>();
893        columns.put(AggregationExceptionColumns._ID, Tables.AGGREGATION_EXCEPTIONS + "._id AS _id");
894        columns.put(AggregationExceptions.TYPE, AggregationExceptions.TYPE);
895        columns.put(AggregationExceptions.RAW_CONTACT_ID1, AggregationExceptions.RAW_CONTACT_ID1);
896        columns.put(AggregationExceptions.RAW_CONTACT_ID2, AggregationExceptions.RAW_CONTACT_ID2);
897        sAggregationExceptionsProjectionMap = columns;
898
899        // Settings projection map
900        columns = new HashMap<String, String>();
901        columns.put(Settings.ACCOUNT_NAME, Settings.ACCOUNT_NAME);
902        columns.put(Settings.ACCOUNT_TYPE, Settings.ACCOUNT_TYPE);
903        columns.put(Settings.UNGROUPED_VISIBLE, Settings.UNGROUPED_VISIBLE);
904        columns.put(Settings.SHOULD_SYNC, Settings.SHOULD_SYNC);
905        columns.put(Settings.ANY_UNSYNCED, "(CASE WHEN MIN(" + Settings.SHOULD_SYNC
906                + ",(SELECT (CASE WHEN MIN(" + Groups.SHOULD_SYNC + ") IS NULL THEN 1 ELSE MIN("
907                + Groups.SHOULD_SYNC + ") END) FROM " + Tables.GROUPS + " WHERE "
908                + GroupsColumns.CONCRETE_ACCOUNT_NAME + "=" + SettingsColumns.CONCRETE_ACCOUNT_NAME
909                + " AND " + GroupsColumns.CONCRETE_ACCOUNT_TYPE + "="
910                + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "))=0 THEN 1 ELSE 0 END) AS "
911                + Settings.ANY_UNSYNCED);
912        columns.put(Settings.UNGROUPED_COUNT, "(SELECT COUNT(*) FROM (SELECT 1 FROM "
913                + Tables.SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS + " GROUP BY "
914                + Clauses.GROUP_BY_ACCOUNT_CONTACT_ID + " HAVING " + Clauses.HAVING_NO_GROUPS
915                + ")) AS " + Settings.UNGROUPED_COUNT);
916        columns.put(Settings.UNGROUPED_WITH_PHONES, "(SELECT COUNT(*) FROM (SELECT 1 FROM "
917                + Tables.SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS + " WHERE "
918                + Contacts.HAS_PHONE_NUMBER + " GROUP BY " + Clauses.GROUP_BY_ACCOUNT_CONTACT_ID
919                + " HAVING " + Clauses.HAVING_NO_GROUPS + ")) AS "
920                + Settings.UNGROUPED_WITH_PHONES);
921        sSettingsProjectionMap = columns;
922
923        columns = new HashMap<String, String>();
924        columns.put(PresenceColumns.RAW_CONTACT_ID, PresenceColumns.RAW_CONTACT_ID);
925        columns.put(StatusUpdates.DATA_ID,
926                DataColumns.CONCRETE_ID + " AS " + StatusUpdates.DATA_ID);
927        columns.put(StatusUpdates.IM_ACCOUNT, StatusUpdates.IM_ACCOUNT);
928        columns.put(StatusUpdates.IM_HANDLE, StatusUpdates.IM_HANDLE);
929        columns.put(StatusUpdates.PROTOCOL, StatusUpdates.PROTOCOL);
930        // We cannot allow a null in the custom protocol field, because SQLite3 does not
931        // properly enforce uniqueness of null values
932        columns.put(StatusUpdates.CUSTOM_PROTOCOL, "(CASE WHEN " + StatusUpdates.CUSTOM_PROTOCOL
933                + "='' THEN NULL ELSE " + StatusUpdates.CUSTOM_PROTOCOL + " END) AS "
934                + StatusUpdates.CUSTOM_PROTOCOL);
935        columns.put(StatusUpdates.PRESENCE, StatusUpdates.PRESENCE);
936        columns.put(StatusUpdates.STATUS, StatusUpdates.STATUS);
937        columns.put(StatusUpdates.STATUS_TIMESTAMP, StatusUpdates.STATUS_TIMESTAMP);
938        columns.put(StatusUpdates.STATUS_RES_PACKAGE, StatusUpdates.STATUS_RES_PACKAGE);
939        columns.put(StatusUpdates.STATUS_ICON, StatusUpdates.STATUS_ICON);
940        columns.put(StatusUpdates.STATUS_LABEL, StatusUpdates.STATUS_LABEL);
941        sStatusUpdatesProjectionMap = columns;
942
943        // Live folder projection
944        sLiveFoldersProjectionMap = new HashMap<String, String>();
945        sLiveFoldersProjectionMap.put(LiveFolders._ID,
946                Contacts._ID + " AS " + LiveFolders._ID);
947        sLiveFoldersProjectionMap.put(LiveFolders.NAME,
948                Contacts.DISPLAY_NAME + " AS " + LiveFolders.NAME);
949        // TODO: Put contact photo back when we have a way to display a default icon
950        // for contacts without a photo
951        // sLiveFoldersProjectionMap.put(LiveFolders.ICON_BITMAP,
952        //      Photos.DATA + " AS " + LiveFolders.ICON_BITMAP);
953    }
954
955    private static void addProjection(HashMap<String, String> map, String toField, String fromField) {
956        map.put(toField, fromField + " AS " + toField);
957    }
958
959    /**
960     * Handles inserts and update for a specific Data type.
961     */
962    private abstract class DataRowHandler {
963
964        protected final String mMimetype;
965        protected long mMimetypeId;
966
967        @SuppressWarnings("all")
968        public DataRowHandler(String mimetype) {
969            mMimetype = mimetype;
970
971            // To ensure the data column position. This is dead code if properly configured.
972            if (StructuredName.DISPLAY_NAME != Data.DATA1 || Nickname.NAME != Data.DATA1
973                    || Organization.COMPANY != Data.DATA1 || Phone.NUMBER != Data.DATA1
974                    || Email.DATA != Data.DATA1) {
975                throw new AssertionError("Some of ContactsContract.CommonDataKinds class primary"
976                        + " data is not in DATA1 column");
977            }
978        }
979
980        protected long getMimeTypeId() {
981            if (mMimetypeId == 0) {
982                mMimetypeId = mDbHelper.getMimeTypeId(mMimetype);
983            }
984            return mMimetypeId;
985        }
986
987        /**
988         * Inserts a row into the {@link Data} table.
989         */
990        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
991            final long dataId = db.insert(Tables.DATA, null, values);
992
993            Integer primary = values.getAsInteger(Data.IS_PRIMARY);
994            if (primary != null && primary != 0) {
995                setIsPrimary(rawContactId, dataId, getMimeTypeId());
996            }
997
998            return dataId;
999        }
1000
1001        /**
1002         * Validates data and updates a {@link Data} row using the cursor, which contains
1003         * the current data.
1004         *
1005         * @return true if update changed something
1006         */
1007        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1008                boolean callerIsSyncAdapter) {
1009            long dataId = c.getLong(DataUpdateQuery._ID);
1010            long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1011
1012            if (values.containsKey(Data.IS_SUPER_PRIMARY)) {
1013                long mimeTypeId = getMimeTypeId();
1014                setIsSuperPrimary(rawContactId, dataId, mimeTypeId);
1015                setIsPrimary(rawContactId, dataId, mimeTypeId);
1016
1017                // Now that we've taken care of setting these, remove them from "values".
1018                values.remove(Data.IS_SUPER_PRIMARY);
1019                values.remove(Data.IS_PRIMARY);
1020            } else if (values.containsKey(Data.IS_PRIMARY)) {
1021                setIsPrimary(rawContactId, dataId, getMimeTypeId());
1022
1023                // Now that we've taken care of setting this, remove it from "values".
1024                values.remove(Data.IS_PRIMARY);
1025            }
1026
1027            if (values.size() > 0) {
1028                mSelectionArgs1[0] = String.valueOf(dataId);
1029                mDb.update(Tables.DATA, values, Data._ID + " =?", mSelectionArgs1);
1030            }
1031
1032            if (!callerIsSyncAdapter) {
1033                setRawContactDirty(rawContactId);
1034            }
1035
1036            return true;
1037        }
1038
1039        public int delete(SQLiteDatabase db, Cursor c) {
1040            long dataId = c.getLong(DataDeleteQuery._ID);
1041            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1042            boolean primary = c.getInt(DataDeleteQuery.IS_PRIMARY) != 0;
1043            mSelectionArgs1[0] = String.valueOf(dataId);
1044            int count = db.delete(Tables.DATA, Data._ID + "=?", mSelectionArgs1);
1045            mSelectionArgs1[0] = String.valueOf(rawContactId);
1046            db.delete(Tables.PRESENCE, PresenceColumns.RAW_CONTACT_ID + "=?", mSelectionArgs1);
1047            if (count != 0 && primary) {
1048                fixPrimary(db, rawContactId);
1049            }
1050            return count;
1051        }
1052
1053        private void fixPrimary(SQLiteDatabase db, long rawContactId) {
1054            long mimeTypeId = getMimeTypeId();
1055            long primaryId = -1;
1056            int primaryType = -1;
1057            mSelectionArgs1[0] = String.valueOf(rawContactId);
1058            Cursor c = db.query(DataDeleteQuery.TABLE,
1059                    DataDeleteQuery.CONCRETE_COLUMNS,
1060                    Data.RAW_CONTACT_ID + "=?" +
1061                        " AND " + DataColumns.MIMETYPE_ID + "=" + mimeTypeId,
1062                    mSelectionArgs1, null, null, null);
1063            try {
1064                while (c.moveToNext()) {
1065                    long dataId = c.getLong(DataDeleteQuery._ID);
1066                    int type = c.getInt(DataDeleteQuery.DATA1);
1067                    if (primaryType == -1 || getTypeRank(type) < getTypeRank(primaryType)) {
1068                        primaryId = dataId;
1069                        primaryType = type;
1070                    }
1071                }
1072            } finally {
1073                c.close();
1074            }
1075            if (primaryId != -1) {
1076                setIsPrimary(rawContactId, primaryId, mimeTypeId);
1077            }
1078        }
1079
1080        /**
1081         * Returns the rank of a specific record type to be used in determining the primary
1082         * row. Lower number represents higher priority.
1083         */
1084        protected int getTypeRank(int type) {
1085            return 0;
1086        }
1087
1088        protected void fixRawContactDisplayName(SQLiteDatabase db, long rawContactId) {
1089            if (!isNewRawContact(rawContactId)) {
1090                updateRawContactDisplayName(db, rawContactId);
1091                mContactAggregator.updateDisplayNameForRawContact(db, rawContactId);
1092            }
1093        }
1094
1095        /**
1096         * Return set of values, using current values at given {@link Data#_ID}
1097         * as baseline, but augmented with any updates.  Returns null if there is
1098         * no change.
1099         */
1100        public ContentValues getAugmentedValues(SQLiteDatabase db, long dataId,
1101                ContentValues update) {
1102            boolean changing = false;
1103            final ContentValues values = new ContentValues();
1104            mSelectionArgs1[0] = String.valueOf(dataId);
1105            final Cursor cursor = db.query(Tables.DATA, null, Data._ID + "=?",
1106                    mSelectionArgs1, null, null, null);
1107            try {
1108                if (cursor.moveToFirst()) {
1109                    for (int i = 0; i < cursor.getColumnCount(); i++) {
1110                        final String key = cursor.getColumnName(i);
1111                        final String value = cursor.getString(i);
1112                        if (!changing && update.containsKey(key)) {
1113                            Object newValue = update.get(key);
1114                            String newString = newValue == null ? null : newValue.toString();
1115                            changing |= !TextUtils.equals(newString, value);
1116                        }
1117                        values.put(key, value);
1118                    }
1119                }
1120            } finally {
1121                cursor.close();
1122            }
1123            if (!changing) {
1124                return null;
1125            }
1126
1127            values.putAll(update);
1128            return values;
1129        }
1130    }
1131
1132    public class CustomDataRowHandler extends DataRowHandler {
1133
1134        public CustomDataRowHandler(String mimetype) {
1135            super(mimetype);
1136        }
1137    }
1138
1139    public class StructuredNameRowHandler extends DataRowHandler {
1140        private final NameSplitter mSplitter;
1141
1142        public StructuredNameRowHandler(NameSplitter splitter) {
1143            super(StructuredName.CONTENT_ITEM_TYPE);
1144            mSplitter = splitter;
1145        }
1146
1147        @Override
1148        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1149            fixStructuredNameComponents(values, values);
1150
1151            long dataId = super.insert(db, rawContactId, values);
1152
1153            String name = values.getAsString(StructuredName.DISPLAY_NAME);
1154            Integer fullNameStyle = values.getAsInteger(StructuredName.FULL_NAME_STYLE);
1155            insertNameLookupForStructuredName(rawContactId, dataId, name,
1156                    fullNameStyle != null
1157                            ? mNameSplitter.getAdjustedFullNameStyle(fullNameStyle)
1158                            : FullNameStyle.UNDEFINED);
1159            insertNameLookupForPhoneticName(rawContactId, dataId, values);
1160            fixRawContactDisplayName(db, rawContactId);
1161            triggerAggregation(rawContactId);
1162            return dataId;
1163        }
1164
1165        @Override
1166        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1167                boolean callerIsSyncAdapter) {
1168            final long dataId = c.getLong(DataUpdateQuery._ID);
1169            final long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1170
1171            final ContentValues augmented = getAugmentedValues(db, dataId, values);
1172            if (augmented == null) {  // No change
1173                return false;
1174            }
1175
1176            fixStructuredNameComponents(augmented, values);
1177
1178            super.update(db, values, c, callerIsSyncAdapter);
1179            if (values.containsKey(StructuredName.DISPLAY_NAME) ||
1180                    values.containsKey(StructuredName.PHONETIC_FAMILY_NAME) ||
1181                    values.containsKey(StructuredName.PHONETIC_MIDDLE_NAME) ||
1182                    values.containsKey(StructuredName.PHONETIC_GIVEN_NAME)) {
1183                augmented.putAll(values);
1184                String name = augmented.getAsString(StructuredName.DISPLAY_NAME);
1185                deleteNameLookup(dataId);
1186                Integer fullNameStyle = augmented.getAsInteger(StructuredName.FULL_NAME_STYLE);
1187                insertNameLookupForStructuredName(rawContactId, dataId, name,
1188                        fullNameStyle != null
1189                                ? mNameSplitter.getAdjustedFullNameStyle(fullNameStyle)
1190                                : FullNameStyle.UNDEFINED);
1191                insertNameLookupForPhoneticName(rawContactId, dataId, augmented);
1192            }
1193            fixRawContactDisplayName(db, rawContactId);
1194            triggerAggregation(rawContactId);
1195            return true;
1196        }
1197
1198        @Override
1199        public int delete(SQLiteDatabase db, Cursor c) {
1200            long dataId = c.getLong(DataDeleteQuery._ID);
1201            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1202
1203            int count = super.delete(db, c);
1204
1205            deleteNameLookup(dataId);
1206            fixRawContactDisplayName(db, rawContactId);
1207            triggerAggregation(rawContactId);
1208            return count;
1209        }
1210
1211        /**
1212         * Specific list of structured fields.
1213         */
1214        private final String[] STRUCTURED_FIELDS = new String[] {
1215                StructuredName.PREFIX, StructuredName.GIVEN_NAME, StructuredName.MIDDLE_NAME,
1216                StructuredName.FAMILY_NAME, StructuredName.SUFFIX
1217        };
1218
1219        /**
1220         * Parses the supplied display name, but only if the incoming values do
1221         * not already contain structured name parts. Also, if the display name
1222         * is not provided, generate one by concatenating first name and last
1223         * name.
1224         */
1225        private void fixStructuredNameComponents(ContentValues augmented, ContentValues update) {
1226            final String unstruct = update.getAsString(StructuredName.DISPLAY_NAME);
1227
1228            final boolean touchedUnstruct = !TextUtils.isEmpty(unstruct);
1229            final boolean touchedStruct = !areAllEmpty(update, STRUCTURED_FIELDS);
1230
1231            if (touchedUnstruct && !touchedStruct) {
1232                NameSplitter.Name name = new NameSplitter.Name();
1233                mSplitter.split(name, unstruct);
1234                name.toValues(update);
1235            } else if (!touchedUnstruct
1236                    && (touchedStruct || areAnySpecified(update, STRUCTURED_FIELDS))) {
1237                // We need to update the display name when any structured components
1238                // are specified, even when they are null, which is why we are checking
1239                // areAnySpecified.  The touchedStruct in the condition is an optimization:
1240                // if there are non-null values, we know for a fact that some values are present.
1241                NameSplitter.Name name = new NameSplitter.Name();
1242                name.fromValues(augmented);
1243                // As the name could be changed, let's guess the name style again.
1244                name.fullNameStyle = FullNameStyle.UNDEFINED;
1245                mSplitter.guessNameStyle(name);
1246                int unadjustedFullNameStyle = name.fullNameStyle;
1247                name.fullNameStyle = mSplitter.getAdjustedFullNameStyle(name.fullNameStyle);
1248                final String joined = mSplitter.join(name, true);
1249                update.put(StructuredName.DISPLAY_NAME, joined);
1250
1251                update.put(StructuredName.FULL_NAME_STYLE, unadjustedFullNameStyle);
1252                update.put(StructuredName.PHONETIC_NAME_STYLE, name.phoneticNameStyle);
1253            } else if (touchedUnstruct && touchedStruct){
1254                if (!update.containsKey(StructuredName.FULL_NAME_STYLE)) {
1255                    update.put(StructuredName.FULL_NAME_STYLE,
1256                            mSplitter.guessFullNameStyle(unstruct));
1257                }
1258                if (!update.containsKey(StructuredName.PHONETIC_NAME_STYLE)) {
1259                    update.put(StructuredName.PHONETIC_NAME_STYLE,
1260                            mSplitter.guessPhoneticNameStyle(unstruct));
1261                }
1262            }
1263        }
1264    }
1265
1266    public class StructuredPostalRowHandler extends DataRowHandler {
1267        private PostalSplitter mSplitter;
1268
1269        public StructuredPostalRowHandler(PostalSplitter splitter) {
1270            super(StructuredPostal.CONTENT_ITEM_TYPE);
1271            mSplitter = splitter;
1272        }
1273
1274        @Override
1275        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1276            fixStructuredPostalComponents(values, values);
1277            return super.insert(db, rawContactId, values);
1278        }
1279
1280        @Override
1281        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1282                boolean callerIsSyncAdapter) {
1283            final long dataId = c.getLong(DataUpdateQuery._ID);
1284            final ContentValues augmented = getAugmentedValues(db, dataId, values);
1285            if (augmented == null) {    // No change
1286                return false;
1287            }
1288
1289            fixStructuredPostalComponents(augmented, values);
1290            super.update(db, values, c, callerIsSyncAdapter);
1291            return true;
1292        }
1293
1294        /**
1295         * Specific list of structured fields.
1296         */
1297        private final String[] STRUCTURED_FIELDS = new String[] {
1298                StructuredPostal.STREET, StructuredPostal.POBOX, StructuredPostal.NEIGHBORHOOD,
1299                StructuredPostal.CITY, StructuredPostal.REGION, StructuredPostal.POSTCODE,
1300                StructuredPostal.COUNTRY,
1301        };
1302
1303        /**
1304         * Prepares the given {@link StructuredPostal} row, building
1305         * {@link StructuredPostal#FORMATTED_ADDRESS} to match the structured
1306         * values when missing. When structured components are missing, the
1307         * unstructured value is assigned to {@link StructuredPostal#STREET}.
1308         */
1309        private void fixStructuredPostalComponents(ContentValues augmented, ContentValues update) {
1310            final String unstruct = update.getAsString(StructuredPostal.FORMATTED_ADDRESS);
1311
1312            final boolean touchedUnstruct = !TextUtils.isEmpty(unstruct);
1313            final boolean touchedStruct = !areAllEmpty(update, STRUCTURED_FIELDS);
1314
1315            final PostalSplitter.Postal postal = new PostalSplitter.Postal();
1316
1317            if (touchedUnstruct && !touchedStruct) {
1318                mSplitter.split(postal, unstruct);
1319                postal.toValues(update);
1320            } else if (!touchedUnstruct
1321                    && (touchedStruct || areAnySpecified(update, STRUCTURED_FIELDS))) {
1322                // See comment in
1323                postal.fromValues(augmented);
1324                final String joined = mSplitter.join(postal);
1325                update.put(StructuredPostal.FORMATTED_ADDRESS, joined);
1326            }
1327        }
1328    }
1329
1330    public class CommonDataRowHandler extends DataRowHandler {
1331
1332        private final String mTypeColumn;
1333        private final String mLabelColumn;
1334
1335        public CommonDataRowHandler(String mimetype, String typeColumn, String labelColumn) {
1336            super(mimetype);
1337            mTypeColumn = typeColumn;
1338            mLabelColumn = labelColumn;
1339        }
1340
1341        @Override
1342        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1343            enforceTypeAndLabel(values, values);
1344            return super.insert(db, rawContactId, values);
1345        }
1346
1347        @Override
1348        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1349                boolean callerIsSyncAdapter) {
1350            final long dataId = c.getLong(DataUpdateQuery._ID);
1351            final ContentValues augmented = getAugmentedValues(db, dataId, values);
1352            if (augmented == null) {        // No change
1353                return false;
1354            }
1355            enforceTypeAndLabel(augmented, values);
1356            return super.update(db, values, c, callerIsSyncAdapter);
1357        }
1358
1359        /**
1360         * If the given {@link ContentValues} defines {@link #mTypeColumn},
1361         * enforce that {@link #mLabelColumn} only appears when type is
1362         * {@link BaseTypes#TYPE_CUSTOM}. Exception is thrown otherwise.
1363         */
1364        private void enforceTypeAndLabel(ContentValues augmented, ContentValues update) {
1365            final boolean hasType = !TextUtils.isEmpty(augmented.getAsString(mTypeColumn));
1366            final boolean hasLabel = !TextUtils.isEmpty(augmented.getAsString(mLabelColumn));
1367
1368            if (hasLabel && !hasType) {
1369                // When label exists, assert that some type is defined
1370                throw new IllegalArgumentException(mTypeColumn + " must be specified when "
1371                        + mLabelColumn + " is defined.");
1372            }
1373        }
1374    }
1375
1376    public class OrganizationDataRowHandler extends CommonDataRowHandler {
1377
1378        public OrganizationDataRowHandler() {
1379            super(Organization.CONTENT_ITEM_TYPE, Organization.TYPE, Organization.LABEL);
1380        }
1381
1382        @Override
1383        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1384            String company = values.getAsString(Organization.COMPANY);
1385            String title = values.getAsString(Organization.TITLE);
1386
1387            long dataId = super.insert(db, rawContactId, values);
1388
1389            fixRawContactDisplayName(db, rawContactId);
1390            insertNameLookupForOrganization(rawContactId, dataId, company, title);
1391            return dataId;
1392        }
1393
1394        @Override
1395        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1396                boolean callerIsSyncAdapter) {
1397            if (!super.update(db, values, c, callerIsSyncAdapter)) {
1398                return false;
1399            }
1400
1401            boolean containsCompany = values.containsKey(Organization.COMPANY);
1402            boolean containsTitle = values.containsKey(Organization.TITLE);
1403            if (containsCompany || containsTitle) {
1404                long dataId = c.getLong(DataUpdateQuery._ID);
1405                long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1406
1407                String company;
1408
1409                if (containsCompany) {
1410                    company = values.getAsString(Organization.COMPANY);
1411                } else {
1412                    mSelectionArgs1[0] = String.valueOf(dataId);
1413                    company = DatabaseUtils.stringForQuery(db,
1414                            "SELECT " + Organization.COMPANY +
1415                            " FROM " + Tables.DATA +
1416                            " WHERE " + Data._ID + "=?", mSelectionArgs1);
1417                }
1418
1419                String title;
1420                if (containsTitle) {
1421                    title = values.getAsString(Organization.TITLE);
1422                } else {
1423                    mSelectionArgs1[0] = String.valueOf(dataId);
1424                    title = DatabaseUtils.stringForQuery(db,
1425                            "SELECT " + Organization.TITLE +
1426                            " FROM " + Tables.DATA +
1427                            " WHERE " + Data._ID + "=?", mSelectionArgs1);
1428                }
1429
1430                deleteNameLookup(dataId);
1431                insertNameLookupForOrganization(rawContactId, dataId, company, title);
1432
1433                fixRawContactDisplayName(db, rawContactId);
1434            }
1435            return true;
1436        }
1437
1438        @Override
1439        public int delete(SQLiteDatabase db, Cursor c) {
1440            long dataId = c.getLong(DataUpdateQuery._ID);
1441            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1442
1443            int count = super.delete(db, c);
1444            fixRawContactDisplayName(db, rawContactId);
1445            deleteNameLookup(dataId);
1446            return count;
1447        }
1448
1449        @Override
1450        protected int getTypeRank(int type) {
1451            switch (type) {
1452                case Organization.TYPE_WORK: return 0;
1453                case Organization.TYPE_CUSTOM: return 1;
1454                case Organization.TYPE_OTHER: return 2;
1455                default: return 1000;
1456            }
1457        }
1458    }
1459
1460    public class EmailDataRowHandler extends CommonDataRowHandler {
1461
1462        public EmailDataRowHandler() {
1463            super(Email.CONTENT_ITEM_TYPE, Email.TYPE, Email.LABEL);
1464        }
1465
1466        @Override
1467        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1468            String email = values.getAsString(Email.DATA);
1469
1470            long dataId = super.insert(db, rawContactId, values);
1471
1472            fixRawContactDisplayName(db, rawContactId);
1473            String address = insertNameLookupForEmail(rawContactId, dataId, email);
1474            if (address != null) {
1475                triggerAggregation(rawContactId);
1476            }
1477            return dataId;
1478        }
1479
1480        @Override
1481        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1482                boolean callerIsSyncAdapter) {
1483            if (!super.update(db, values, c, callerIsSyncAdapter)) {
1484                return false;
1485            }
1486
1487            if (values.containsKey(Email.DATA)) {
1488                long dataId = c.getLong(DataUpdateQuery._ID);
1489                long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1490
1491                String address = values.getAsString(Email.DATA);
1492                deleteNameLookup(dataId);
1493                insertNameLookupForEmail(rawContactId, dataId, address);
1494                fixRawContactDisplayName(db, rawContactId);
1495                triggerAggregation(rawContactId);
1496            }
1497
1498            return true;
1499        }
1500
1501        @Override
1502        public int delete(SQLiteDatabase db, Cursor c) {
1503            long dataId = c.getLong(DataDeleteQuery._ID);
1504            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1505
1506            int count = super.delete(db, c);
1507
1508            deleteNameLookup(dataId);
1509            fixRawContactDisplayName(db, rawContactId);
1510            triggerAggregation(rawContactId);
1511            return count;
1512        }
1513
1514        @Override
1515        protected int getTypeRank(int type) {
1516            switch (type) {
1517                case Email.TYPE_HOME: return 0;
1518                case Email.TYPE_WORK: return 1;
1519                case Email.TYPE_CUSTOM: return 2;
1520                case Email.TYPE_OTHER: return 3;
1521                default: return 1000;
1522            }
1523        }
1524    }
1525
1526    public class NicknameDataRowHandler extends CommonDataRowHandler {
1527
1528        public NicknameDataRowHandler() {
1529            super(Nickname.CONTENT_ITEM_TYPE, Nickname.TYPE, Nickname.LABEL);
1530        }
1531
1532        @Override
1533        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1534            String nickname = values.getAsString(Nickname.NAME);
1535
1536            long dataId = super.insert(db, rawContactId, values);
1537
1538            if (!TextUtils.isEmpty(nickname)) {
1539                fixRawContactDisplayName(db, rawContactId);
1540                insertNameLookupForNickname(rawContactId, dataId, nickname);
1541                triggerAggregation(rawContactId);
1542            }
1543            return dataId;
1544        }
1545
1546        @Override
1547        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1548                boolean callerIsSyncAdapter) {
1549            long dataId = c.getLong(DataUpdateQuery._ID);
1550            long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1551
1552            if (!super.update(db, values, c, callerIsSyncAdapter)) {
1553                return false;
1554            }
1555
1556            if (values.containsKey(Nickname.NAME)) {
1557                String nickname = values.getAsString(Nickname.NAME);
1558                deleteNameLookup(dataId);
1559                insertNameLookupForNickname(rawContactId, dataId, nickname);
1560                fixRawContactDisplayName(db, rawContactId);
1561                triggerAggregation(rawContactId);
1562            }
1563
1564            return true;
1565        }
1566
1567        @Override
1568        public int delete(SQLiteDatabase db, Cursor c) {
1569            long dataId = c.getLong(DataDeleteQuery._ID);
1570            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1571
1572            int count = super.delete(db, c);
1573
1574            deleteNameLookup(dataId);
1575            fixRawContactDisplayName(db, rawContactId);
1576            triggerAggregation(rawContactId);
1577            return count;
1578        }
1579    }
1580
1581    public class PhoneDataRowHandler extends CommonDataRowHandler {
1582
1583        public PhoneDataRowHandler() {
1584            super(Phone.CONTENT_ITEM_TYPE, Phone.TYPE, Phone.LABEL);
1585        }
1586
1587        @Override
1588        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1589            long dataId;
1590            if (values.containsKey(Phone.NUMBER)) {
1591                String number = values.getAsString(Phone.NUMBER);
1592                String normalizedNumber = computeNormalizedNumber(number);
1593                values.put(PhoneColumns.NORMALIZED_NUMBER, normalizedNumber);
1594                dataId = super.insert(db, rawContactId, values);
1595
1596                updatePhoneLookup(db, rawContactId, dataId, number, normalizedNumber);
1597                mContactAggregator.updateHasPhoneNumber(db, rawContactId);
1598                fixRawContactDisplayName(db, rawContactId);
1599                if (normalizedNumber != null) {
1600                    triggerAggregation(rawContactId);
1601                }
1602            } else {
1603                dataId = super.insert(db, rawContactId, values);
1604            }
1605            return dataId;
1606        }
1607
1608        @Override
1609        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1610                boolean callerIsSyncAdapter) {
1611            String number = null;
1612            String normalizedNumber = null;
1613            if (values.containsKey(Phone.NUMBER)) {
1614                number = values.getAsString(Phone.NUMBER);
1615                normalizedNumber = computeNormalizedNumber(number);
1616                values.put(PhoneColumns.NORMALIZED_NUMBER, normalizedNumber);
1617            }
1618
1619            if (!super.update(db, values, c, callerIsSyncAdapter)) {
1620                return false;
1621            }
1622
1623            if (values.containsKey(Phone.NUMBER)) {
1624                long dataId = c.getLong(DataUpdateQuery._ID);
1625                long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1626                updatePhoneLookup(db, rawContactId, dataId, number, normalizedNumber);
1627                mContactAggregator.updateHasPhoneNumber(db, rawContactId);
1628                fixRawContactDisplayName(db, rawContactId);
1629                triggerAggregation(rawContactId);
1630            }
1631            return true;
1632        }
1633
1634        @Override
1635        public int delete(SQLiteDatabase db, Cursor c) {
1636            long dataId = c.getLong(DataDeleteQuery._ID);
1637            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1638
1639            int count = super.delete(db, c);
1640
1641            updatePhoneLookup(db, rawContactId, dataId, null, null);
1642            mContactAggregator.updateHasPhoneNumber(db, rawContactId);
1643            fixRawContactDisplayName(db, rawContactId);
1644            triggerAggregation(rawContactId);
1645            return count;
1646        }
1647
1648        private String computeNormalizedNumber(String number) {
1649            String normalizedNumber = null;
1650            if (number != null) {
1651                normalizedNumber = PhoneNumberUtils.getStrippedReversed(number);
1652            }
1653            return normalizedNumber;
1654        }
1655
1656        private void updatePhoneLookup(SQLiteDatabase db, long rawContactId, long dataId,
1657                String number, String normalizedNumber) {
1658            if (number != null) {
1659                ContentValues phoneValues = new ContentValues();
1660                phoneValues.put(PhoneLookupColumns.RAW_CONTACT_ID, rawContactId);
1661                phoneValues.put(PhoneLookupColumns.DATA_ID, dataId);
1662                phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, normalizedNumber);
1663                phoneValues.put(PhoneLookupColumns.MIN_MATCH,
1664                        PhoneNumberUtils.toCallerIDMinMatch(number));
1665
1666                db.replace(Tables.PHONE_LOOKUP, null, phoneValues);
1667            } else {
1668                mSelectionArgs1[0] = String.valueOf(dataId);
1669                db.delete(Tables.PHONE_LOOKUP, PhoneLookupColumns.DATA_ID + "=?", mSelectionArgs1);
1670            }
1671        }
1672
1673        @Override
1674        protected int getTypeRank(int type) {
1675            switch (type) {
1676                case Phone.TYPE_MOBILE: return 0;
1677                case Phone.TYPE_WORK: return 1;
1678                case Phone.TYPE_HOME: return 2;
1679                case Phone.TYPE_PAGER: return 3;
1680                case Phone.TYPE_CUSTOM: return 4;
1681                case Phone.TYPE_OTHER: return 5;
1682                case Phone.TYPE_FAX_WORK: return 6;
1683                case Phone.TYPE_FAX_HOME: return 7;
1684                default: return 1000;
1685            }
1686        }
1687    }
1688
1689    public class GroupMembershipRowHandler extends DataRowHandler {
1690
1691        public GroupMembershipRowHandler() {
1692            super(GroupMembership.CONTENT_ITEM_TYPE);
1693        }
1694
1695        @Override
1696        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1697            resolveGroupSourceIdInValues(rawContactId, db, values, true);
1698            long dataId = super.insert(db, rawContactId, values);
1699            updateVisibility(rawContactId);
1700            return dataId;
1701        }
1702
1703        @Override
1704        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1705                boolean callerIsSyncAdapter) {
1706            long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1707            resolveGroupSourceIdInValues(rawContactId, db, values, false);
1708            if (!super.update(db, values, c, callerIsSyncAdapter)) {
1709                return false;
1710            }
1711            updateVisibility(rawContactId);
1712            return true;
1713        }
1714
1715        @Override
1716        public int delete(SQLiteDatabase db, Cursor c) {
1717            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1718            int count = super.delete(db, c);
1719            updateVisibility(rawContactId);
1720            return count;
1721        }
1722
1723        private void updateVisibility(long rawContactId) {
1724            long contactId = mDbHelper.getContactId(rawContactId);
1725            if (contactId != 0) {
1726                mDbHelper.updateContactVisible(contactId);
1727            }
1728        }
1729
1730        private void resolveGroupSourceIdInValues(long rawContactId, SQLiteDatabase db,
1731                ContentValues values, boolean isInsert) {
1732            boolean containsGroupSourceId = values.containsKey(GroupMembership.GROUP_SOURCE_ID);
1733            boolean containsGroupId = values.containsKey(GroupMembership.GROUP_ROW_ID);
1734            if (containsGroupSourceId && containsGroupId) {
1735                throw new IllegalArgumentException(
1736                        "you are not allowed to set both the GroupMembership.GROUP_SOURCE_ID "
1737                                + "and GroupMembership.GROUP_ROW_ID");
1738            }
1739
1740            if (!containsGroupSourceId && !containsGroupId) {
1741                if (isInsert) {
1742                    throw new IllegalArgumentException(
1743                            "you must set exactly one of GroupMembership.GROUP_SOURCE_ID "
1744                                    + "and GroupMembership.GROUP_ROW_ID");
1745                } else {
1746                    return;
1747                }
1748            }
1749
1750            if (containsGroupSourceId) {
1751                final String sourceId = values.getAsString(GroupMembership.GROUP_SOURCE_ID);
1752                final long groupId = getOrMakeGroup(db, rawContactId, sourceId,
1753                        mInsertedRawContacts.get(rawContactId));
1754                values.remove(GroupMembership.GROUP_SOURCE_ID);
1755                values.put(GroupMembership.GROUP_ROW_ID, groupId);
1756            }
1757        }
1758    }
1759
1760    public class PhotoDataRowHandler extends DataRowHandler {
1761
1762        public PhotoDataRowHandler() {
1763            super(Photo.CONTENT_ITEM_TYPE);
1764        }
1765
1766        @Override
1767        public long insert(SQLiteDatabase db, long rawContactId, ContentValues values) {
1768            long dataId = super.insert(db, rawContactId, values);
1769            if (!isNewRawContact(rawContactId)) {
1770                mContactAggregator.updatePhotoId(db, rawContactId);
1771            }
1772            return dataId;
1773        }
1774
1775        @Override
1776        public boolean update(SQLiteDatabase db, ContentValues values, Cursor c,
1777                boolean callerIsSyncAdapter) {
1778            long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID);
1779            if (!super.update(db, values, c, callerIsSyncAdapter)) {
1780                return false;
1781            }
1782
1783            mContactAggregator.updatePhotoId(db, rawContactId);
1784            return true;
1785        }
1786
1787        @Override
1788        public int delete(SQLiteDatabase db, Cursor c) {
1789            long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
1790            int count = super.delete(db, c);
1791            mContactAggregator.updatePhotoId(db, rawContactId);
1792            return count;
1793        }
1794    }
1795
1796    /**
1797     * An entry in group id cache. It maps the combination of (account type, account name
1798     * and source id) to group row id.
1799     */
1800    public class GroupIdCacheEntry {
1801        String accountType;
1802        String accountName;
1803        String sourceId;
1804        long groupId;
1805    }
1806
1807    private HashMap<String, DataRowHandler> mDataRowHandlers;
1808    private ContactsDatabaseHelper mDbHelper;
1809
1810    private NameSplitter mNameSplitter;
1811    private NameLookupBuilder mNameLookupBuilder;
1812
1813    private PostalSplitter mPostalSplitter;
1814
1815    // We don't need a soft cache for groups - the assumption is that there will only
1816    // be a small number of contact groups. The cache is keyed off source id.  The value
1817    // is a list of groups with this group id.
1818    private HashMap<String, ArrayList<GroupIdCacheEntry>> mGroupIdCache = Maps.newHashMap();
1819
1820    private ContactAggregator mContactAggregator;
1821    private LegacyApiSupport mLegacyApiSupport;
1822    private GlobalSearchSupport mGlobalSearchSupport;
1823    private CommonNicknameCache mCommonNicknameCache;
1824
1825    private ContentValues mValues = new ContentValues();
1826    private CharArrayBuffer mCharArrayBuffer = new CharArrayBuffer(128);
1827    private NameSplitter.Name mName = new NameSplitter.Name();
1828    private HashMap<String, Boolean> mAccountWritability = Maps.newHashMap();
1829
1830    private int mProviderStatus = ProviderStatus.STATUS_NORMAL;
1831    private long mEstimatedStorageRequirement = 0;
1832    private volatile CountDownLatch mAccessLatch;
1833
1834    private HashMap<Long, Account> mInsertedRawContacts = Maps.newHashMap();
1835    private HashSet<Long> mUpdatedRawContacts = Sets.newHashSet();
1836    private HashSet<Long> mDirtyRawContacts = Sets.newHashSet();
1837    private HashMap<Long, Object> mUpdatedSyncStates = Maps.newHashMap();
1838
1839    private boolean mVisibleTouched = false;
1840
1841    private boolean mSyncToNetwork;
1842
1843    private Locale mCurrentLocale;
1844
1845
1846    @Override
1847    public boolean onCreate() {
1848        super.onCreate();
1849        try {
1850            return initialize();
1851        } catch (RuntimeException e) {
1852            Log.e(TAG, "Cannot start provider", e);
1853            return false;
1854        }
1855    }
1856
1857    private boolean initialize() {
1858        final Context context = getContext();
1859        mDbHelper = (ContactsDatabaseHelper)getDatabaseHelper();
1860        mGlobalSearchSupport = new GlobalSearchSupport(this);
1861        mLegacyApiSupport = new LegacyApiSupport(context, mDbHelper, this, mGlobalSearchSupport);
1862        mContactAggregator = new ContactAggregator(this, mDbHelper,
1863                createPhotoPriorityResolver(context));
1864        mContactAggregator.setEnabled(SystemProperties.getBoolean(AGGREGATE_CONTACTS, true));
1865
1866        mDb = mDbHelper.getWritableDatabase();
1867
1868        initForDefaultLocale();
1869
1870        mSetPrimaryStatement = mDb.compileStatement(
1871                "UPDATE " + Tables.DATA +
1872                " SET " + Data.IS_PRIMARY + "=(_id=?)" +
1873                " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
1874                "   AND " + Data.RAW_CONTACT_ID + "=?");
1875
1876        mSetSuperPrimaryStatement = mDb.compileStatement(
1877                "UPDATE " + Tables.DATA +
1878                " SET " + Data.IS_SUPER_PRIMARY + "=(" + Data._ID + "=?)" +
1879                " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
1880                "   AND " + Data.RAW_CONTACT_ID + " IN (" +
1881                        "SELECT " + RawContacts._ID +
1882                        " FROM " + Tables.RAW_CONTACTS +
1883                        " WHERE " + RawContacts.CONTACT_ID + " =(" +
1884                                "SELECT " + RawContacts.CONTACT_ID +
1885                                " FROM " + Tables.RAW_CONTACTS +
1886                                " WHERE " + RawContacts._ID + "=?))");
1887
1888        mRawContactDisplayNameUpdate = mDb.compileStatement(
1889                "UPDATE " + Tables.RAW_CONTACTS +
1890                " SET " +
1891                        RawContacts.DISPLAY_NAME_SOURCE + "=?," +
1892                        RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
1893                        RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
1894                        RawContacts.PHONETIC_NAME + "=?," +
1895                        RawContacts.PHONETIC_NAME_STYLE + "=?," +
1896                        RawContacts.SORT_KEY_PRIMARY + "=?," +
1897                        RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
1898                " WHERE " + RawContacts._ID + "=?");
1899
1900        mLastStatusUpdate = mDb.compileStatement(
1901                "UPDATE " + Tables.CONTACTS +
1902                " SET " + ContactsColumns.LAST_STATUS_UPDATE_ID + "=" +
1903                        "(SELECT " + DataColumns.CONCRETE_ID +
1904                        " FROM " + Tables.STATUS_UPDATES +
1905                        " JOIN " + Tables.DATA +
1906                        "   ON (" + StatusUpdatesColumns.DATA_ID + "="
1907                                + DataColumns.CONCRETE_ID + ")" +
1908                        " JOIN " + Tables.RAW_CONTACTS +
1909                        "   ON (" + DataColumns.CONCRETE_RAW_CONTACT_ID + "="
1910                                + RawContactsColumns.CONCRETE_ID + ")" +
1911                        " WHERE " + RawContacts.CONTACT_ID + "=?" +
1912                        " ORDER BY " + StatusUpdates.STATUS_TIMESTAMP + " DESC,"
1913                                + StatusUpdates.STATUS +
1914                        " LIMIT 1)" +
1915                " WHERE " + ContactsColumns.CONCRETE_ID + "=?");
1916
1917        mNameLookupInsert = mDb.compileStatement("INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
1918                + NameLookupColumns.RAW_CONTACT_ID + "," + NameLookupColumns.DATA_ID + ","
1919                + NameLookupColumns.NAME_TYPE + "," + NameLookupColumns.NORMALIZED_NAME
1920                + ") VALUES (?,?,?,?)");
1921        mNameLookupDelete = mDb.compileStatement("DELETE FROM " + Tables.NAME_LOOKUP + " WHERE "
1922                + NameLookupColumns.DATA_ID + "=?");
1923
1924        mStatusUpdateInsert = mDb.compileStatement(
1925                "INSERT INTO " + Tables.STATUS_UPDATES + "("
1926                        + StatusUpdatesColumns.DATA_ID + ", "
1927                        + StatusUpdates.STATUS + ","
1928                        + StatusUpdates.STATUS_RES_PACKAGE + ","
1929                        + StatusUpdates.STATUS_ICON + ","
1930                        + StatusUpdates.STATUS_LABEL + ")" +
1931                " VALUES (?,?,?,?,?)");
1932
1933        mStatusUpdateReplace = mDb.compileStatement(
1934                "INSERT OR REPLACE INTO " + Tables.STATUS_UPDATES + "("
1935                        + StatusUpdatesColumns.DATA_ID + ", "
1936                        + StatusUpdates.STATUS_TIMESTAMP + ","
1937                        + StatusUpdates.STATUS + ","
1938                        + StatusUpdates.STATUS_RES_PACKAGE + ","
1939                        + StatusUpdates.STATUS_ICON + ","
1940                        + StatusUpdates.STATUS_LABEL + ")" +
1941                " VALUES (?,?,?,?,?,?)");
1942
1943        mStatusUpdateAutoTimestamp = mDb.compileStatement(
1944                "UPDATE " + Tables.STATUS_UPDATES +
1945                " SET " + StatusUpdates.STATUS_TIMESTAMP + "=?,"
1946                        + StatusUpdates.STATUS + "=?" +
1947                " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"
1948                        + " AND " + StatusUpdates.STATUS + "!=?");
1949
1950        mStatusAttributionUpdate = mDb.compileStatement(
1951                "UPDATE " + Tables.STATUS_UPDATES +
1952                " SET " + StatusUpdates.STATUS_RES_PACKAGE + "=?,"
1953                        + StatusUpdates.STATUS_ICON + "=?,"
1954                        + StatusUpdates.STATUS_LABEL + "=?" +
1955                " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
1956
1957        mStatusUpdateDelete = mDb.compileStatement(
1958                "DELETE FROM " + Tables.STATUS_UPDATES +
1959                " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
1960
1961        // When setting NAME_VERIFIED to 1 on a raw contact, reset it to 0
1962        // on all other raw contacts in the same aggregate
1963        mResetNameVerifiedForOtherRawContacts = mDb.compileStatement(
1964                "UPDATE " + Tables.RAW_CONTACTS +
1965                " SET " + RawContacts.NAME_VERIFIED + "=0" +
1966                " WHERE " + RawContacts.CONTACT_ID + "=(" +
1967                        "SELECT " + RawContacts.CONTACT_ID +
1968                        " FROM " + Tables.RAW_CONTACTS +
1969                        " WHERE " + RawContacts._ID + "=?)" +
1970                " AND " + RawContacts._ID + "!=?");
1971
1972        mMimeTypeIdEmail = mDbHelper.getMimeTypeId(Email.CONTENT_ITEM_TYPE);
1973        mMimeTypeIdIm = mDbHelper.getMimeTypeId(Im.CONTENT_ITEM_TYPE);
1974        mMimeTypeIdStructuredName = mDbHelper.getMimeTypeId(StructuredName.CONTENT_ITEM_TYPE);
1975        mMimeTypeIdOrganization = mDbHelper.getMimeTypeId(Organization.CONTENT_ITEM_TYPE);
1976        mMimeTypeIdNickname = mDbHelper.getMimeTypeId(Nickname.CONTENT_ITEM_TYPE);
1977        mMimeTypeIdPhone = mDbHelper.getMimeTypeId(Phone.CONTENT_ITEM_TYPE);
1978
1979        verifyAccounts();
1980
1981        if (isLegacyContactImportNeeded()) {
1982            importLegacyContactsAsync();
1983        } else {
1984            verifyLocale();
1985        }
1986
1987        return (mDb != null);
1988    }
1989
1990    private void initDataRowHandlers() {
1991      mDataRowHandlers = new HashMap<String, DataRowHandler>();
1992
1993      mDataRowHandlers.put(Email.CONTENT_ITEM_TYPE, new EmailDataRowHandler());
1994      mDataRowHandlers.put(Im.CONTENT_ITEM_TYPE,
1995              new CommonDataRowHandler(Im.CONTENT_ITEM_TYPE, Im.TYPE, Im.LABEL));
1996      mDataRowHandlers.put(Nickname.CONTENT_ITEM_TYPE, new CommonDataRowHandler(
1997              StructuredPostal.CONTENT_ITEM_TYPE, StructuredPostal.TYPE, StructuredPostal.LABEL));
1998      mDataRowHandlers.put(Organization.CONTENT_ITEM_TYPE, new OrganizationDataRowHandler());
1999      mDataRowHandlers.put(Phone.CONTENT_ITEM_TYPE, new PhoneDataRowHandler());
2000      mDataRowHandlers.put(Nickname.CONTENT_ITEM_TYPE, new NicknameDataRowHandler());
2001      mDataRowHandlers.put(StructuredName.CONTENT_ITEM_TYPE,
2002              new StructuredNameRowHandler(mNameSplitter));
2003      mDataRowHandlers.put(StructuredPostal.CONTENT_ITEM_TYPE,
2004              new StructuredPostalRowHandler(mPostalSplitter));
2005      mDataRowHandlers.put(GroupMembership.CONTENT_ITEM_TYPE, new GroupMembershipRowHandler());
2006      mDataRowHandlers.put(Photo.CONTENT_ITEM_TYPE, new PhotoDataRowHandler());
2007    }
2008    /**
2009     * Visible for testing.
2010     */
2011    /* package */ PhotoPriorityResolver createPhotoPriorityResolver(Context context) {
2012        return new PhotoPriorityResolver(context);
2013    }
2014
2015    /**
2016     * (Re)allocates all locale-sensitive structures.
2017     */
2018    private void initForDefaultLocale() {
2019        mCurrentLocale = getLocale();
2020        mNameSplitter = mDbHelper.createNameSplitter();
2021        mNameLookupBuilder = new StructuredNameLookupBuilder(mNameSplitter);
2022        mPostalSplitter = new PostalSplitter(mCurrentLocale);
2023        mCommonNicknameCache = new CommonNicknameCache(mDbHelper.getReadableDatabase());
2024        ContactLocaleUtils.getIntance().setLocale(mCurrentLocale);
2025        initDataRowHandlers();
2026    }
2027
2028    @Override
2029    public void onConfigurationChanged(Configuration newConfig) {
2030        initForDefaultLocale();
2031        verifyLocale();
2032    }
2033
2034    protected void verifyAccounts() {
2035        AccountManager.get(getContext()).addOnAccountsUpdatedListener(this, null, false);
2036        onAccountsUpdated(AccountManager.get(getContext()).getAccounts());
2037    }
2038
2039    /**
2040     * Verifies that the contacts database is properly configured for the current locale.
2041     * If not, changes the database locale to the current locale using an asynchronous task.
2042     * This needs to be done asynchronously because the process involves rebuilding
2043     * large data structures (name lookup, sort keys), which can take minutes on
2044     * a large set of contacts.
2045     */
2046    protected void verifyLocale() {
2047
2048        // The process is already running - postpone the change
2049        if (mProviderStatus == ProviderStatus.STATUS_CHANGING_LOCALE) {
2050            return;
2051        }
2052
2053        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
2054        final String providerLocale = prefs.getString(PREF_LOCALE, null);
2055        final Locale currentLocale = mCurrentLocale;
2056        if (currentLocale.toString().equals(providerLocale)) {
2057            return;
2058        }
2059
2060        int providerStatus = mProviderStatus;
2061        setProviderStatus(ProviderStatus.STATUS_CHANGING_LOCALE);
2062
2063        AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
2064
2065            int savedProviderStatus;
2066
2067            @Override
2068            protected Void doInBackground(Integer... params) {
2069                savedProviderStatus = params[0];
2070                mDbHelper.setLocale(ContactsProvider2.this, currentLocale);
2071                return null;
2072            }
2073
2074            @Override
2075            protected void onPostExecute(Void result) {
2076                prefs.edit().putString(PREF_LOCALE, currentLocale.toString()).commit();
2077                setProviderStatus(savedProviderStatus);
2078
2079                // Recursive invocation, needed to cover the case where locale
2080                // changes once and then changes again before the db upgrade is completed.
2081                verifyLocale();
2082            }
2083        };
2084
2085        task.execute(providerStatus);
2086    }
2087
2088    /* Visible for testing */
2089    @Override
2090    protected ContactsDatabaseHelper getDatabaseHelper(final Context context) {
2091        return ContactsDatabaseHelper.getInstance(context);
2092    }
2093
2094    /* package */ NameSplitter getNameSplitter() {
2095        return mNameSplitter;
2096    }
2097
2098    /* Visible for testing */
2099    protected Locale getLocale() {
2100        return Locale.getDefault();
2101    }
2102
2103    protected boolean isLegacyContactImportNeeded() {
2104        int version = Integer.parseInt(mDbHelper.getProperty(PROPERTY_CONTACTS_IMPORTED, "0"));
2105        return version < PROPERTY_CONTACTS_IMPORT_VERSION;
2106    }
2107
2108    protected LegacyContactImporter getLegacyContactImporter() {
2109        return new LegacyContactImporter(getContext(), this);
2110    }
2111
2112    /**
2113     * Imports legacy contacts in a separate thread.  As long as the import process is running
2114     * all other access to the contacts is blocked.
2115     */
2116    private void importLegacyContactsAsync() {
2117        Log.v(TAG, "Importing legacy contacts");
2118        setProviderStatus(ProviderStatus.STATUS_UPGRADING);
2119        if (mAccessLatch == null) {
2120            mAccessLatch = new CountDownLatch(1);
2121        }
2122
2123        Thread importThread = new Thread("LegacyContactImport") {
2124            @Override
2125            public void run() {
2126                final SharedPreferences prefs =
2127                    PreferenceManager.getDefaultSharedPreferences(getContext());
2128                mDbHelper.setLocale(ContactsProvider2.this, mCurrentLocale);
2129                prefs.edit().putString(PREF_LOCALE, mCurrentLocale.toString()).commit();
2130
2131                LegacyContactImporter importer = getLegacyContactImporter();
2132                if (importLegacyContacts(importer)) {
2133                    onLegacyContactImportSuccess();
2134                } else {
2135                    onLegacyContactImportFailure();
2136                }
2137            }
2138        };
2139
2140        importThread.start();
2141    }
2142
2143    /**
2144     * Unlocks the provider and declares that the import process is complete.
2145     */
2146    private void onLegacyContactImportSuccess() {
2147        NotificationManager nm =
2148            (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE);
2149        nm.cancel(LEGACY_IMPORT_FAILED_NOTIFICATION);
2150
2151        // Store a property in the database indicating that the conversion process succeeded
2152        mDbHelper.setProperty(PROPERTY_CONTACTS_IMPORTED,
2153                String.valueOf(PROPERTY_CONTACTS_IMPORT_VERSION));
2154        setProviderStatus(ProviderStatus.STATUS_NORMAL);
2155        mAccessLatch.countDown();
2156        mAccessLatch = null;
2157        Log.v(TAG, "Completed import of legacy contacts");
2158    }
2159
2160    /**
2161     * Announces the provider status and keeps the provider locked.
2162     */
2163    private void onLegacyContactImportFailure() {
2164        Context context = getContext();
2165        NotificationManager nm =
2166            (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
2167
2168        // Show a notification
2169        Notification n = new Notification(android.R.drawable.stat_notify_error,
2170                context.getString(R.string.upgrade_out_of_memory_notification_ticker),
2171                System.currentTimeMillis());
2172        n.setLatestEventInfo(context,
2173                context.getString(R.string.upgrade_out_of_memory_notification_title),
2174                context.getString(R.string.upgrade_out_of_memory_notification_text),
2175                PendingIntent.getActivity(context, 0, new Intent(Intents.UI.LIST_DEFAULT), 0));
2176        n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
2177
2178        nm.notify(LEGACY_IMPORT_FAILED_NOTIFICATION, n);
2179
2180        setProviderStatus(ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY);
2181        Log.v(TAG, "Failed to import legacy contacts");
2182    }
2183
2184    /* Visible for testing */
2185    /* package */ boolean importLegacyContacts(LegacyContactImporter importer) {
2186        boolean aggregatorEnabled = mContactAggregator.isEnabled();
2187        mContactAggregator.setEnabled(false);
2188        try {
2189            if (importer.importContacts()) {
2190
2191                // TODO aggregate all newly added raw contacts
2192                mContactAggregator.setEnabled(aggregatorEnabled);
2193                return true;
2194            }
2195        } catch (Throwable e) {
2196           Log.e(TAG, "Legacy contact import failed", e);
2197        }
2198        mEstimatedStorageRequirement = importer.getEstimatedStorageRequirement();
2199        return false;
2200    }
2201
2202    /**
2203     * Wipes all data from the contacts database.
2204     */
2205    /* package */ void wipeData() {
2206        mDbHelper.wipeData();
2207    }
2208
2209    /**
2210     * While importing and aggregating contacts, this content provider will
2211     * block all attempts to change contacts data. In particular, it will hold
2212     * up all contact syncs. As soon as the import process is complete, all
2213     * processes waiting to write to the provider are unblocked and can proceed
2214     * to compete for the database transaction monitor.
2215     */
2216    private void waitForAccess() {
2217        CountDownLatch latch = mAccessLatch;
2218        if (latch != null) {
2219            while (true) {
2220                try {
2221                    latch.await();
2222                    mAccessLatch = null;
2223                    return;
2224                } catch (InterruptedException e) {
2225                    Thread.currentThread().interrupt();
2226                }
2227            }
2228        }
2229    }
2230
2231    @Override
2232    public Uri insert(Uri uri, ContentValues values) {
2233        waitForAccess();
2234        return super.insert(uri, values);
2235    }
2236
2237    @Override
2238    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
2239        if (mAccessLatch != null) {
2240            // We are stuck trying to upgrade contacts db.  The only update request
2241            // allowed in this case is an update of provider status, which will trigger
2242            // an attempt to upgrade contacts again.
2243            int match = sUriMatcher.match(uri);
2244            if (match == PROVIDER_STATUS && isLegacyContactImportNeeded()) {
2245                Integer newStatus = values.getAsInteger(ProviderStatus.STATUS);
2246                if (newStatus != null && newStatus == ProviderStatus.STATUS_UPGRADING) {
2247                    importLegacyContactsAsync();
2248                    return 1;
2249                } else {
2250                    return 0;
2251                }
2252            }
2253        }
2254        waitForAccess();
2255        return super.update(uri, values, selection, selectionArgs);
2256    }
2257
2258    @Override
2259    public int delete(Uri uri, String selection, String[] selectionArgs) {
2260        waitForAccess();
2261        return super.delete(uri, selection, selectionArgs);
2262    }
2263
2264    @Override
2265    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
2266            throws OperationApplicationException {
2267        waitForAccess();
2268        return super.applyBatch(operations);
2269    }
2270
2271    @Override
2272    protected void onBeginTransaction() {
2273        if (VERBOSE_LOGGING) {
2274            Log.v(TAG, "onBeginTransaction");
2275        }
2276        super.onBeginTransaction();
2277        mContactAggregator.clearPendingAggregations();
2278        clearTransactionalChanges();
2279    }
2280
2281    private void clearTransactionalChanges() {
2282        mInsertedRawContacts.clear();
2283        mUpdatedRawContacts.clear();
2284        mUpdatedSyncStates.clear();
2285        mDirtyRawContacts.clear();
2286    }
2287
2288    @Override
2289    protected void beforeTransactionCommit() {
2290
2291        if (VERBOSE_LOGGING) {
2292            Log.v(TAG, "beforeTransactionCommit");
2293        }
2294        super.beforeTransactionCommit();
2295        flushTransactionalChanges();
2296        mContactAggregator.aggregateInTransaction(mDb);
2297        if (mVisibleTouched) {
2298            mVisibleTouched = false;
2299            mDbHelper.updateAllVisible();
2300        }
2301    }
2302
2303    private void flushTransactionalChanges() {
2304        if (VERBOSE_LOGGING) {
2305            Log.v(TAG, "flushTransactionChanges");
2306        }
2307
2308        for (long rawContactId : mInsertedRawContacts.keySet()) {
2309            updateRawContactDisplayName(mDb, rawContactId);
2310            mContactAggregator.onRawContactInsert(mDb, rawContactId);
2311        }
2312
2313        if (!mDirtyRawContacts.isEmpty()) {
2314            mSb.setLength(0);
2315            mSb.append(UPDATE_RAW_CONTACT_SET_DIRTY_SQL);
2316            appendIds(mSb, mDirtyRawContacts);
2317            mSb.append(")");
2318            mDb.execSQL(mSb.toString());
2319        }
2320
2321        if (!mUpdatedRawContacts.isEmpty()) {
2322            mSb.setLength(0);
2323            mSb.append(UPDATE_RAW_CONTACT_SET_VERSION_SQL);
2324            appendIds(mSb, mUpdatedRawContacts);
2325            mSb.append(")");
2326            mDb.execSQL(mSb.toString());
2327        }
2328
2329        for (Map.Entry<Long, Object> entry : mUpdatedSyncStates.entrySet()) {
2330            long id = entry.getKey();
2331            if (mDbHelper.getSyncState().update(mDb, id, entry.getValue()) <= 0) {
2332                throw new IllegalStateException(
2333                        "unable to update sync state, does it still exist?");
2334            }
2335        }
2336
2337        clearTransactionalChanges();
2338    }
2339
2340    /**
2341     * Appends comma separated ids.
2342     * @param ids Should not be empty
2343     */
2344    private void appendIds(StringBuilder sb, HashSet<Long> ids) {
2345        for (long id : ids) {
2346            sb.append(id).append(',');
2347        }
2348
2349        sb.setLength(sb.length() - 1); // Yank the last comma
2350    }
2351
2352    @Override
2353    protected void notifyChange() {
2354        notifyChange(mSyncToNetwork);
2355        mSyncToNetwork = false;
2356    }
2357
2358    protected void notifyChange(boolean syncToNetwork) {
2359        getContext().getContentResolver().notifyChange(ContactsContract.AUTHORITY_URI, null,
2360                syncToNetwork);
2361    }
2362
2363    protected void setProviderStatus(int status) {
2364        mProviderStatus = status;
2365        getContext().getContentResolver().notifyChange(ContactsContract.ProviderStatus.CONTENT_URI,
2366                null, false);
2367    }
2368
2369    private boolean isNewRawContact(long rawContactId) {
2370        return mInsertedRawContacts.containsKey(rawContactId);
2371    }
2372
2373    private DataRowHandler getDataRowHandler(final String mimeType) {
2374        DataRowHandler handler = mDataRowHandlers.get(mimeType);
2375        if (handler == null) {
2376            handler = new CustomDataRowHandler(mimeType);
2377            mDataRowHandlers.put(mimeType, handler);
2378        }
2379        return handler;
2380    }
2381
2382    @Override
2383    protected Uri insertInTransaction(Uri uri, ContentValues values) {
2384        if (VERBOSE_LOGGING) {
2385            Log.v(TAG, "insertInTransaction: " + uri + " " + values);
2386        }
2387
2388        final boolean callerIsSyncAdapter =
2389                readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false);
2390
2391        final int match = sUriMatcher.match(uri);
2392        long id = 0;
2393
2394        switch (match) {
2395            case SYNCSTATE:
2396                id = mDbHelper.getSyncState().insert(mDb, values);
2397                break;
2398
2399            case CONTACTS: {
2400                insertContact(values);
2401                break;
2402            }
2403
2404            case RAW_CONTACTS: {
2405                id = insertRawContact(uri, values);
2406                mSyncToNetwork |= !callerIsSyncAdapter;
2407                break;
2408            }
2409
2410            case RAW_CONTACTS_DATA: {
2411                values.put(Data.RAW_CONTACT_ID, uri.getPathSegments().get(1));
2412                id = insertData(values, callerIsSyncAdapter);
2413                mSyncToNetwork |= !callerIsSyncAdapter;
2414                break;
2415            }
2416
2417            case DATA: {
2418                id = insertData(values, callerIsSyncAdapter);
2419                mSyncToNetwork |= !callerIsSyncAdapter;
2420                break;
2421            }
2422
2423            case GROUPS: {
2424                id = insertGroup(uri, values, callerIsSyncAdapter);
2425                mSyncToNetwork |= !callerIsSyncAdapter;
2426                break;
2427            }
2428
2429            case SETTINGS: {
2430                id = insertSettings(uri, values);
2431                mSyncToNetwork |= !callerIsSyncAdapter;
2432                break;
2433            }
2434
2435            case STATUS_UPDATES: {
2436                id = insertStatusUpdate(values);
2437                break;
2438            }
2439
2440            default:
2441                mSyncToNetwork = true;
2442                return mLegacyApiSupport.insert(uri, values);
2443        }
2444
2445        if (id < 0) {
2446            return null;
2447        }
2448
2449        return ContentUris.withAppendedId(uri, id);
2450    }
2451
2452    /**
2453     * If account is non-null then store it in the values. If the account is
2454     * already specified in the values then it must be consistent with the
2455     * account, if it is non-null.
2456     *
2457     * @param uri Current {@link Uri} being operated on.
2458     * @param values {@link ContentValues} to read and possibly update.
2459     * @throws IllegalArgumentException when only one of
2460     *             {@link RawContacts#ACCOUNT_NAME} or
2461     *             {@link RawContacts#ACCOUNT_TYPE} is specified, leaving the
2462     *             other undefined.
2463     * @throws IllegalArgumentException when {@link RawContacts#ACCOUNT_NAME}
2464     *             and {@link RawContacts#ACCOUNT_TYPE} are inconsistent between
2465     *             the given {@link Uri} and {@link ContentValues}.
2466     */
2467    private Account resolveAccount(Uri uri, ContentValues values) throws IllegalArgumentException {
2468        String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME);
2469        String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE);
2470        final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType);
2471
2472        String valueAccountName = values.getAsString(RawContacts.ACCOUNT_NAME);
2473        String valueAccountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
2474        final boolean partialValues = TextUtils.isEmpty(valueAccountName)
2475                ^ TextUtils.isEmpty(valueAccountType);
2476
2477        if (partialUri || partialValues) {
2478            // Throw when either account is incomplete
2479            throw new IllegalArgumentException(mDbHelper.exceptionMessage(
2480                    "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri));
2481        }
2482
2483        // Accounts are valid by only checking one parameter, since we've
2484        // already ruled out partial accounts.
2485        final boolean validUri = !TextUtils.isEmpty(accountName);
2486        final boolean validValues = !TextUtils.isEmpty(valueAccountName);
2487
2488        if (validValues && validUri) {
2489            // Check that accounts match when both present
2490            final boolean accountMatch = TextUtils.equals(accountName, valueAccountName)
2491                    && TextUtils.equals(accountType, valueAccountType);
2492            if (!accountMatch) {
2493                throw new IllegalArgumentException(mDbHelper.exceptionMessage(
2494                        "When both specified, ACCOUNT_NAME and ACCOUNT_TYPE must match", uri));
2495            }
2496        } else if (validUri) {
2497            // Fill values from Uri when not present
2498            values.put(RawContacts.ACCOUNT_NAME, accountName);
2499            values.put(RawContacts.ACCOUNT_TYPE, accountType);
2500        } else if (validValues) {
2501            accountName = valueAccountName;
2502            accountType = valueAccountType;
2503        } else {
2504            return null;
2505        }
2506
2507        // Use cached Account object when matches, otherwise create
2508        if (mAccount == null
2509                || !mAccount.name.equals(accountName)
2510                || !mAccount.type.equals(accountType)) {
2511            mAccount = new Account(accountName, accountType);
2512        }
2513
2514        return mAccount;
2515    }
2516
2517    /**
2518     * Inserts an item in the contacts table
2519     *
2520     * @param values the values for the new row
2521     * @return the row ID of the newly created row
2522     */
2523    private long insertContact(ContentValues values) {
2524        throw new UnsupportedOperationException("Aggregate contacts are created automatically");
2525    }
2526
2527    /**
2528     * Inserts an item in the contacts table
2529     *
2530     * @param uri the values for the new row
2531     * @param values the account this contact should be associated with. may be null.
2532     * @return the row ID of the newly created row
2533     */
2534    private long insertRawContact(Uri uri, ContentValues values) {
2535        mValues.clear();
2536        mValues.putAll(values);
2537        mValues.putNull(RawContacts.CONTACT_ID);
2538
2539        final Account account = resolveAccount(uri, mValues);
2540
2541        if (values.containsKey(RawContacts.DELETED)
2542                && values.getAsInteger(RawContacts.DELETED) != 0) {
2543            mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED);
2544        }
2545
2546        long rawContactId = mDb.insert(Tables.RAW_CONTACTS, RawContacts.CONTACT_ID, mValues);
2547        int aggregationMode = RawContacts.AGGREGATION_MODE_DEFAULT;
2548        if (mValues.containsKey(RawContacts.AGGREGATION_MODE)) {
2549            aggregationMode = mValues.getAsInteger(RawContacts.AGGREGATION_MODE);
2550        }
2551        mContactAggregator.markNewForAggregation(rawContactId, aggregationMode);
2552
2553        // Trigger creation of a Contact based on this RawContact at the end of transaction
2554        mInsertedRawContacts.put(rawContactId, account);
2555
2556        return rawContactId;
2557    }
2558
2559    /**
2560     * Inserts an item in the data table
2561     *
2562     * @param values the values for the new row
2563     * @return the row ID of the newly created row
2564     */
2565    private long insertData(ContentValues values, boolean callerIsSyncAdapter) {
2566        long id = 0;
2567        mValues.clear();
2568        mValues.putAll(values);
2569
2570        long rawContactId = mValues.getAsLong(Data.RAW_CONTACT_ID);
2571
2572        // Replace package with internal mapping
2573        final String packageName = mValues.getAsString(Data.RES_PACKAGE);
2574        if (packageName != null) {
2575            mValues.put(DataColumns.PACKAGE_ID, mDbHelper.getPackageId(packageName));
2576        }
2577        mValues.remove(Data.RES_PACKAGE);
2578
2579        // Replace mimetype with internal mapping
2580        final String mimeType = mValues.getAsString(Data.MIMETYPE);
2581        if (TextUtils.isEmpty(mimeType)) {
2582            throw new IllegalArgumentException(Data.MIMETYPE + " is required");
2583        }
2584
2585        mValues.put(DataColumns.MIMETYPE_ID, mDbHelper.getMimeTypeId(mimeType));
2586        mValues.remove(Data.MIMETYPE);
2587
2588        DataRowHandler rowHandler = getDataRowHandler(mimeType);
2589        id = rowHandler.insert(mDb, rawContactId, mValues);
2590        if (!callerIsSyncAdapter) {
2591            setRawContactDirty(rawContactId);
2592        }
2593        mUpdatedRawContacts.add(rawContactId);
2594        return id;
2595    }
2596
2597    private void triggerAggregation(long rawContactId) {
2598        if (!mContactAggregator.isEnabled()) {
2599            return;
2600        }
2601
2602        int aggregationMode = mDbHelper.getAggregationMode(rawContactId);
2603        switch (aggregationMode) {
2604            case RawContacts.AGGREGATION_MODE_DISABLED:
2605                break;
2606
2607            case RawContacts.AGGREGATION_MODE_DEFAULT: {
2608                mContactAggregator.markForAggregation(rawContactId, aggregationMode, false);
2609                break;
2610            }
2611
2612            case RawContacts.AGGREGATION_MODE_SUSPENDED: {
2613                long contactId = mDbHelper.getContactId(rawContactId);
2614
2615                if (contactId != 0) {
2616                    mContactAggregator.updateAggregateData(contactId);
2617                }
2618                break;
2619            }
2620
2621            case RawContacts.AGGREGATION_MODE_IMMEDIATE: {
2622                long contactId = mDbHelper.getContactId(rawContactId);
2623                mContactAggregator.aggregateContact(mDb, rawContactId, contactId);
2624                break;
2625            }
2626        }
2627    }
2628
2629    /**
2630     * Returns the group id of the group with sourceId and the same account as rawContactId.
2631     * If the group doesn't already exist then it is first created,
2632     * @param db SQLiteDatabase to use for this operation
2633     * @param rawContactId the contact this group is associated with
2634     * @param sourceId the sourceIf of the group to query or create
2635     * @return the group id of the existing or created group
2636     * @throws IllegalArgumentException if the contact is not associated with an account
2637     * @throws IllegalStateException if a group needs to be created but the creation failed
2638     */
2639    private long getOrMakeGroup(SQLiteDatabase db, long rawContactId, String sourceId,
2640            Account account) {
2641
2642        if (account == null) {
2643            mSelectionArgs1[0] = String.valueOf(rawContactId);
2644            Cursor c = db.query(RawContactsQuery.TABLE, RawContactsQuery.COLUMNS,
2645                    RawContacts._ID + "=?", mSelectionArgs1, null, null, null);
2646            try {
2647                if (c.moveToFirst()) {
2648                    String accountName = c.getString(RawContactsQuery.ACCOUNT_NAME);
2649                    String accountType = c.getString(RawContactsQuery.ACCOUNT_TYPE);
2650                    if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2651                        account = new Account(accountName, accountType);
2652                    }
2653                }
2654            } finally {
2655                c.close();
2656            }
2657        }
2658
2659        if (account == null) {
2660            throw new IllegalArgumentException("if the groupmembership only "
2661                    + "has a sourceid the the contact must be associated with "
2662                    + "an account");
2663        }
2664
2665        ArrayList<GroupIdCacheEntry> entries = mGroupIdCache.get(sourceId);
2666        if (entries == null) {
2667            entries = new ArrayList<GroupIdCacheEntry>(1);
2668            mGroupIdCache.put(sourceId, entries);
2669        }
2670
2671        int count = entries.size();
2672        for (int i = 0; i < count; i++) {
2673            GroupIdCacheEntry entry = entries.get(i);
2674            if (entry.accountName.equals(account.name) && entry.accountType.equals(account.type)) {
2675                return entry.groupId;
2676            }
2677        }
2678
2679        GroupIdCacheEntry entry = new GroupIdCacheEntry();
2680        entry.accountName = account.name;
2681        entry.accountType = account.type;
2682        entry.sourceId = sourceId;
2683        entries.add(0, entry);
2684
2685        // look up the group that contains this sourceId and has the same account name and type
2686        // as the contact refered to by rawContactId
2687        Cursor c = db.query(Tables.GROUPS, new String[]{RawContacts._ID},
2688                Clauses.GROUP_HAS_ACCOUNT_AND_SOURCE_ID,
2689                new String[]{sourceId, account.name, account.type}, null, null, null);
2690        try {
2691            if (c.moveToFirst()) {
2692                entry.groupId = c.getLong(0);
2693            } else {
2694                ContentValues groupValues = new ContentValues();
2695                groupValues.put(Groups.ACCOUNT_NAME, account.name);
2696                groupValues.put(Groups.ACCOUNT_TYPE, account.type);
2697                groupValues.put(Groups.SOURCE_ID, sourceId);
2698                long groupId = db.insert(Tables.GROUPS, Groups.ACCOUNT_NAME, groupValues);
2699                if (groupId < 0) {
2700                    throw new IllegalStateException("unable to create a new group with "
2701                            + "this sourceid: " + groupValues);
2702                }
2703                entry.groupId = groupId;
2704            }
2705        } finally {
2706            c.close();
2707        }
2708
2709        return entry.groupId;
2710    }
2711
2712    private interface DisplayNameQuery {
2713        public static final String RAW_SQL =
2714                "SELECT "
2715                        + DataColumns.MIMETYPE_ID + ","
2716                        + Data.IS_PRIMARY + ","
2717                        + Data.DATA1 + ","
2718                        + Data.DATA2 + ","
2719                        + Data.DATA3 + ","
2720                        + Data.DATA4 + ","
2721                        + Data.DATA5 + ","
2722                        + Data.DATA6 + ","
2723                        + Data.DATA7 + ","
2724                        + Data.DATA8 + ","
2725                        + Data.DATA9 + ","
2726                        + Data.DATA10 + ","
2727                        + Data.DATA11 +
2728                " FROM " + Tables.DATA +
2729                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
2730                        " AND (" + Data.DATA1 + " NOT NULL OR " +
2731                                Organization.TITLE + " NOT NULL)";
2732
2733        public static final int MIMETYPE = 0;
2734        public static final int IS_PRIMARY = 1;
2735        public static final int DATA1 = 2;
2736        public static final int GIVEN_NAME = 3;                         // data2
2737        public static final int FAMILY_NAME = 4;                        // data3
2738        public static final int PREFIX = 5;                             // data4
2739        public static final int TITLE = 5;                              // data4
2740        public static final int MIDDLE_NAME = 6;                        // data5
2741        public static final int SUFFIX = 7;                             // data6
2742        public static final int PHONETIC_GIVEN_NAME = 8;                // data7
2743        public static final int PHONETIC_MIDDLE_NAME = 9;               // data8
2744        public static final int ORGANIZATION_PHONETIC_NAME = 9;         // data8
2745        public static final int PHONETIC_FAMILY_NAME = 10;              // data9
2746        public static final int FULL_NAME_STYLE = 11;                   // data10
2747        public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11;  // data10
2748        public static final int PHONETIC_NAME_STYLE = 12;               // data11
2749    }
2750
2751    /**
2752     * Updates a raw contact display name based on data rows, e.g. structured name,
2753     * organization, email etc.
2754     */
2755    public void updateRawContactDisplayName(SQLiteDatabase db, long rawContactId) {
2756        int bestDisplayNameSource = DisplayNameSources.UNDEFINED;
2757        NameSplitter.Name bestName = null;
2758        String bestDisplayName = null;
2759        String bestPhoneticName = null;
2760        int bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
2761
2762        mSelectionArgs1[0] = String.valueOf(rawContactId);
2763        Cursor c = db.rawQuery(DisplayNameQuery.RAW_SQL, mSelectionArgs1);
2764        try {
2765            while (c.moveToNext()) {
2766                int mimeType = c.getInt(DisplayNameQuery.MIMETYPE);
2767                int source = getDisplayNameSource(mimeType);
2768                if (source < bestDisplayNameSource || source == DisplayNameSources.UNDEFINED) {
2769                    continue;
2770                }
2771
2772                if (source == bestDisplayNameSource && c.getInt(DisplayNameQuery.IS_PRIMARY) == 0) {
2773                    continue;
2774                }
2775
2776                if (mimeType == mMimeTypeIdStructuredName) {
2777                    NameSplitter.Name name;
2778                    if (bestName != null) {
2779                        name = new NameSplitter.Name();
2780                    } else {
2781                        name = mName;
2782                        name.clear();
2783                    }
2784                    name.prefix = c.getString(DisplayNameQuery.PREFIX);
2785                    name.givenNames = c.getString(DisplayNameQuery.GIVEN_NAME);
2786                    name.middleName = c.getString(DisplayNameQuery.MIDDLE_NAME);
2787                    name.familyName = c.getString(DisplayNameQuery.FAMILY_NAME);
2788                    name.suffix = c.getString(DisplayNameQuery.SUFFIX);
2789                    name.fullNameStyle = c.isNull(DisplayNameQuery.FULL_NAME_STYLE)
2790                            ? FullNameStyle.UNDEFINED
2791                            : c.getInt(DisplayNameQuery.FULL_NAME_STYLE);
2792                    name.phoneticFamilyName = c.getString(DisplayNameQuery.PHONETIC_FAMILY_NAME);
2793                    name.phoneticMiddleName = c.getString(DisplayNameQuery.PHONETIC_MIDDLE_NAME);
2794                    name.phoneticGivenName = c.getString(DisplayNameQuery.PHONETIC_GIVEN_NAME);
2795                    name.phoneticNameStyle = c.isNull(DisplayNameQuery.PHONETIC_NAME_STYLE)
2796                            ? PhoneticNameStyle.UNDEFINED
2797                            : c.getInt(DisplayNameQuery.PHONETIC_NAME_STYLE);
2798                    if (!name.isEmpty()) {
2799                        bestDisplayNameSource = source;
2800                        bestName = name;
2801                    }
2802                } else if (mimeType == mMimeTypeIdOrganization) {
2803                    mCharArrayBuffer.sizeCopied = 0;
2804                    c.copyStringToBuffer(DisplayNameQuery.DATA1, mCharArrayBuffer);
2805                    if (mCharArrayBuffer.sizeCopied != 0) {
2806                        bestDisplayNameSource = source;
2807                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
2808                                mCharArrayBuffer.sizeCopied);
2809                        bestPhoneticName = c.getString(DisplayNameQuery.ORGANIZATION_PHONETIC_NAME);
2810                        bestPhoneticNameStyle =
2811                                c.isNull(DisplayNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE)
2812                                    ? PhoneticNameStyle.UNDEFINED
2813                                    : c.getInt(DisplayNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE);
2814                    } else {
2815                        c.copyStringToBuffer(DisplayNameQuery.TITLE, mCharArrayBuffer);
2816                        if (mCharArrayBuffer.sizeCopied != 0) {
2817                            bestDisplayNameSource = source;
2818                            bestDisplayName = new String(mCharArrayBuffer.data, 0,
2819                                    mCharArrayBuffer.sizeCopied);
2820                            bestPhoneticName = null;
2821                            bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
2822                        }
2823                    }
2824                } else {
2825                    // Display name is at DATA1 in all other types.
2826                    // This is ensured in the constructor.
2827
2828                    mCharArrayBuffer.sizeCopied = 0;
2829                    c.copyStringToBuffer(DisplayNameQuery.DATA1, mCharArrayBuffer);
2830                    if (mCharArrayBuffer.sizeCopied != 0) {
2831                        bestDisplayNameSource = source;
2832                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
2833                                mCharArrayBuffer.sizeCopied);
2834                        bestPhoneticName = null;
2835                        bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
2836                    }
2837                }
2838            }
2839
2840        } finally {
2841            c.close();
2842        }
2843
2844        String displayNamePrimary;
2845        String displayNameAlternative;
2846        String sortKeyPrimary = null;
2847        String sortKeyAlternative = null;
2848        int displayNameStyle = FullNameStyle.UNDEFINED;
2849
2850        if (bestDisplayNameSource == DisplayNameSources.STRUCTURED_NAME) {
2851            displayNameStyle = bestName.fullNameStyle;
2852            if (displayNameStyle == FullNameStyle.CJK
2853                    || displayNameStyle == FullNameStyle.UNDEFINED) {
2854                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
2855                bestName.fullNameStyle = displayNameStyle;
2856            }
2857
2858            displayNamePrimary = mNameSplitter.join(bestName, true);
2859            displayNameAlternative = mNameSplitter.join(bestName, false);
2860
2861            bestPhoneticName = mNameSplitter.joinPhoneticName(bestName);
2862            bestPhoneticNameStyle = bestName.phoneticNameStyle;
2863        } else {
2864            displayNamePrimary = displayNameAlternative = bestDisplayName;
2865        }
2866
2867        if (bestPhoneticName != null) {
2868            sortKeyPrimary = sortKeyAlternative = bestPhoneticName;
2869            if (bestPhoneticNameStyle == PhoneticNameStyle.UNDEFINED) {
2870                bestPhoneticNameStyle = mNameSplitter.guessPhoneticNameStyle(bestPhoneticName);
2871            }
2872        } else {
2873            if (displayNameStyle == FullNameStyle.UNDEFINED) {
2874                displayNameStyle = mNameSplitter.guessFullNameStyle(bestDisplayName);
2875                if (displayNameStyle == FullNameStyle.UNDEFINED
2876                        || displayNameStyle == FullNameStyle.CJK) {
2877                    displayNameStyle = mNameSplitter.getAdjustedNameStyleBasedOnPhoneticNameStyle(
2878                            displayNameStyle, bestPhoneticNameStyle);
2879                }
2880                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
2881            }
2882            if (displayNameStyle == FullNameStyle.CHINESE ||
2883                    displayNameStyle == FullNameStyle.CJK) {
2884                sortKeyPrimary = sortKeyAlternative =
2885                        ContactLocaleUtils.getIntance().getSortKey(
2886                                displayNamePrimary, displayNameStyle);
2887            }
2888        }
2889
2890        if (sortKeyPrimary == null) {
2891            sortKeyPrimary = displayNamePrimary;
2892            sortKeyAlternative = displayNameAlternative;
2893        }
2894
2895        setDisplayName(rawContactId, bestDisplayNameSource, displayNamePrimary,
2896                displayNameAlternative, bestPhoneticName, bestPhoneticNameStyle,
2897                sortKeyPrimary, sortKeyAlternative);
2898    }
2899
2900    private int getDisplayNameSource(int mimeTypeId) {
2901        if (mimeTypeId == mMimeTypeIdStructuredName) {
2902            return DisplayNameSources.STRUCTURED_NAME;
2903        } else if (mimeTypeId == mMimeTypeIdEmail) {
2904            return DisplayNameSources.EMAIL;
2905        } else if (mimeTypeId == mMimeTypeIdPhone) {
2906            return DisplayNameSources.PHONE;
2907        } else if (mimeTypeId == mMimeTypeIdOrganization) {
2908            return DisplayNameSources.ORGANIZATION;
2909        } else if (mimeTypeId == mMimeTypeIdNickname) {
2910            return DisplayNameSources.NICKNAME;
2911        } else {
2912            return DisplayNameSources.UNDEFINED;
2913        }
2914    }
2915
2916    /**
2917     * Delete data row by row so that fixing of primaries etc work correctly.
2918     */
2919    private int deleteData(String selection, String[] selectionArgs, boolean callerIsSyncAdapter) {
2920        int count = 0;
2921
2922        // Note that the query will return data according to the access restrictions,
2923        // so we don't need to worry about deleting data we don't have permission to read.
2924        Cursor c = query(Data.CONTENT_URI, DataDeleteQuery.COLUMNS, selection, selectionArgs, null);
2925        try {
2926            while(c.moveToNext()) {
2927                long rawContactId = c.getLong(DataDeleteQuery.RAW_CONTACT_ID);
2928                String mimeType = c.getString(DataDeleteQuery.MIMETYPE);
2929                DataRowHandler rowHandler = getDataRowHandler(mimeType);
2930                count += rowHandler.delete(mDb, c);
2931                if (!callerIsSyncAdapter) {
2932                    setRawContactDirty(rawContactId);
2933                }
2934            }
2935        } finally {
2936            c.close();
2937        }
2938
2939        return count;
2940    }
2941
2942    /**
2943     * Delete a data row provided that it is one of the allowed mime types.
2944     */
2945    public int deleteData(long dataId, String[] allowedMimeTypes) {
2946
2947        // Note that the query will return data according to the access restrictions,
2948        // so we don't need to worry about deleting data we don't have permission to read.
2949        mSelectionArgs1[0] = String.valueOf(dataId);
2950        Cursor c = query(Data.CONTENT_URI, DataDeleteQuery.COLUMNS, Data._ID + "=?",
2951                mSelectionArgs1, null);
2952
2953        try {
2954            if (!c.moveToFirst()) {
2955                return 0;
2956            }
2957
2958            String mimeType = c.getString(DataDeleteQuery.MIMETYPE);
2959            boolean valid = false;
2960            for (int i = 0; i < allowedMimeTypes.length; i++) {
2961                if (TextUtils.equals(mimeType, allowedMimeTypes[i])) {
2962                    valid = true;
2963                    break;
2964                }
2965            }
2966
2967            if (!valid) {
2968                throw new IllegalArgumentException("Data type mismatch: expected "
2969                        + Lists.newArrayList(allowedMimeTypes));
2970            }
2971
2972            DataRowHandler rowHandler = getDataRowHandler(mimeType);
2973            return rowHandler.delete(mDb, c);
2974        } finally {
2975            c.close();
2976        }
2977    }
2978
2979    /**
2980     * Inserts an item in the groups table
2981     */
2982    private long insertGroup(Uri uri, ContentValues values, boolean callerIsSyncAdapter) {
2983        mValues.clear();
2984        mValues.putAll(values);
2985
2986        final Account account = resolveAccount(uri, mValues);
2987
2988        // Replace package with internal mapping
2989        final String packageName = mValues.getAsString(Groups.RES_PACKAGE);
2990        if (packageName != null) {
2991            mValues.put(GroupsColumns.PACKAGE_ID, mDbHelper.getPackageId(packageName));
2992        }
2993        mValues.remove(Groups.RES_PACKAGE);
2994
2995        if (!callerIsSyncAdapter) {
2996            mValues.put(Groups.DIRTY, 1);
2997        }
2998
2999        long result = mDb.insert(Tables.GROUPS, Groups.TITLE, mValues);
3000
3001        if (mValues.containsKey(Groups.GROUP_VISIBLE)) {
3002            mVisibleTouched = true;
3003        }
3004
3005        return result;
3006    }
3007
3008    private long insertSettings(Uri uri, ContentValues values) {
3009        final long id = mDb.insert(Tables.SETTINGS, null, values);
3010
3011        if (values.containsKey(Settings.UNGROUPED_VISIBLE)) {
3012            mVisibleTouched = true;
3013        }
3014
3015        return id;
3016    }
3017
3018    /**
3019     * Inserts a status update.
3020     */
3021    public long insertStatusUpdate(ContentValues values) {
3022        final String handle = values.getAsString(StatusUpdates.IM_HANDLE);
3023        final Integer protocol = values.getAsInteger(StatusUpdates.PROTOCOL);
3024        String customProtocol = null;
3025
3026        if (protocol != null && protocol == Im.PROTOCOL_CUSTOM) {
3027            customProtocol = values.getAsString(StatusUpdates.CUSTOM_PROTOCOL);
3028            if (TextUtils.isEmpty(customProtocol)) {
3029                throw new IllegalArgumentException(
3030                        "CUSTOM_PROTOCOL is required when PROTOCOL=PROTOCOL_CUSTOM");
3031            }
3032        }
3033
3034        long rawContactId = -1;
3035        long contactId = -1;
3036        Long dataId = values.getAsLong(StatusUpdates.DATA_ID);
3037        mSb.setLength(0);
3038        mSelectionArgs.clear();
3039        if (dataId != null) {
3040            // Lookup the contact info for the given data row.
3041
3042            mSb.append(Tables.DATA + "." + Data._ID + "=?");
3043            mSelectionArgs.add(String.valueOf(dataId));
3044        } else {
3045            // Lookup the data row to attach this presence update to
3046
3047            if (TextUtils.isEmpty(handle) || protocol == null) {
3048                throw new IllegalArgumentException("PROTOCOL and IM_HANDLE are required");
3049            }
3050
3051            // TODO: generalize to allow other providers to match against email
3052            boolean matchEmail = Im.PROTOCOL_GOOGLE_TALK == protocol;
3053
3054            String mimeTypeIdIm = String.valueOf(mMimeTypeIdIm);
3055            if (matchEmail) {
3056                String mimeTypeIdEmail = String.valueOf(mMimeTypeIdEmail);
3057
3058                // The following hack forces SQLite to use the (mimetype_id,data1) index, otherwise
3059                // the "OR" conjunction confuses it and it switches to a full scan of
3060                // the raw_contacts table.
3061
3062                // This code relies on the fact that Im.DATA and Email.DATA are in fact the same
3063                // column - Data.DATA1
3064                mSb.append(DataColumns.MIMETYPE_ID + " IN (?,?)" +
3065                        " AND " + Data.DATA1 + "=?" +
3066                        " AND ((" + DataColumns.MIMETYPE_ID + "=? AND " + Im.PROTOCOL + "=?");
3067                mSelectionArgs.add(mimeTypeIdEmail);
3068                mSelectionArgs.add(mimeTypeIdIm);
3069                mSelectionArgs.add(handle);
3070                mSelectionArgs.add(mimeTypeIdIm);
3071                mSelectionArgs.add(String.valueOf(protocol));
3072                if (customProtocol != null) {
3073                    mSb.append(" AND " + Im.CUSTOM_PROTOCOL + "=?");
3074                    mSelectionArgs.add(customProtocol);
3075                }
3076                mSb.append(") OR (" + DataColumns.MIMETYPE_ID + "=?))");
3077                mSelectionArgs.add(mimeTypeIdEmail);
3078            } else {
3079                mSb.append(DataColumns.MIMETYPE_ID + "=?" +
3080                        " AND " + Im.PROTOCOL + "=?" +
3081                        " AND " + Im.DATA + "=?");
3082                mSelectionArgs.add(mimeTypeIdIm);
3083                mSelectionArgs.add(String.valueOf(protocol));
3084                mSelectionArgs.add(handle);
3085                if (customProtocol != null) {
3086                    mSb.append(" AND " + Im.CUSTOM_PROTOCOL + "=?");
3087                    mSelectionArgs.add(customProtocol);
3088                }
3089            }
3090
3091            if (values.containsKey(StatusUpdates.DATA_ID)) {
3092                mSb.append(" AND " + DataColumns.CONCRETE_ID + "=?");
3093                mSelectionArgs.add(values.getAsString(StatusUpdates.DATA_ID));
3094            }
3095        }
3096        mSb.append(" AND ").append(getContactsRestrictions());
3097
3098        Cursor cursor = null;
3099        try {
3100            cursor = mDb.query(DataContactsQuery.TABLE, DataContactsQuery.PROJECTION,
3101                    mSb.toString(), mSelectionArgs.toArray(EMPTY_STRING_ARRAY), null, null,
3102                    Contacts.IN_VISIBLE_GROUP + " DESC, " + Data.RAW_CONTACT_ID);
3103            if (cursor.moveToFirst()) {
3104                dataId = cursor.getLong(DataContactsQuery.DATA_ID);
3105                rawContactId = cursor.getLong(DataContactsQuery.RAW_CONTACT_ID);
3106                contactId = cursor.getLong(DataContactsQuery.CONTACT_ID);
3107            } else {
3108                // No contact found, return a null URI
3109                return -1;
3110            }
3111        } finally {
3112            if (cursor != null) {
3113                cursor.close();
3114            }
3115        }
3116
3117        if (values.containsKey(StatusUpdates.PRESENCE)) {
3118            if (customProtocol == null) {
3119                // We cannot allow a null in the custom protocol field, because SQLite3 does not
3120                // properly enforce uniqueness of null values
3121                customProtocol = "";
3122            }
3123
3124            mValues.clear();
3125            mValues.put(StatusUpdates.DATA_ID, dataId);
3126            mValues.put(PresenceColumns.RAW_CONTACT_ID, rawContactId);
3127            mValues.put(PresenceColumns.CONTACT_ID, contactId);
3128            mValues.put(StatusUpdates.PROTOCOL, protocol);
3129            mValues.put(StatusUpdates.CUSTOM_PROTOCOL, customProtocol);
3130            mValues.put(StatusUpdates.IM_HANDLE, handle);
3131            if (values.containsKey(StatusUpdates.IM_ACCOUNT)) {
3132                mValues.put(StatusUpdates.IM_ACCOUNT, values.getAsString(StatusUpdates.IM_ACCOUNT));
3133            }
3134            mValues.put(StatusUpdates.PRESENCE,
3135                    values.getAsString(StatusUpdates.PRESENCE));
3136
3137            // Insert the presence update
3138            mDb.replace(Tables.PRESENCE, null, mValues);
3139        }
3140
3141
3142        if (values.containsKey(StatusUpdates.STATUS)) {
3143            String status = values.getAsString(StatusUpdates.STATUS);
3144            String resPackage = values.getAsString(StatusUpdates.STATUS_RES_PACKAGE);
3145            Integer labelResource = values.getAsInteger(StatusUpdates.STATUS_LABEL);
3146
3147            if (TextUtils.isEmpty(resPackage)
3148                    && (labelResource == null || labelResource == 0)
3149                    && protocol != null) {
3150                labelResource = Im.getProtocolLabelResource(protocol);
3151            }
3152
3153            Long iconResource = values.getAsLong(StatusUpdates.STATUS_ICON);
3154            // TODO compute the default icon based on the protocol
3155
3156            if (TextUtils.isEmpty(status)) {
3157                mStatusUpdateDelete.bindLong(1, dataId);
3158                mStatusUpdateDelete.execute();
3159            } else if (values.containsKey(StatusUpdates.STATUS_TIMESTAMP)) {
3160                long timestamp = values.getAsLong(StatusUpdates.STATUS_TIMESTAMP);
3161                mStatusUpdateReplace.bindLong(1, dataId);
3162                mStatusUpdateReplace.bindLong(2, timestamp);
3163                bindString(mStatusUpdateReplace, 3, status);
3164                bindString(mStatusUpdateReplace, 4, resPackage);
3165                bindLong(mStatusUpdateReplace, 5, iconResource);
3166                bindLong(mStatusUpdateReplace, 6, labelResource);
3167                mStatusUpdateReplace.execute();
3168            } else {
3169
3170                try {
3171                    mStatusUpdateInsert.bindLong(1, dataId);
3172                    bindString(mStatusUpdateInsert, 2, status);
3173                    bindString(mStatusUpdateInsert, 3, resPackage);
3174                    bindLong(mStatusUpdateInsert, 4, iconResource);
3175                    bindLong(mStatusUpdateInsert, 5, labelResource);
3176                    mStatusUpdateInsert.executeInsert();
3177                } catch (SQLiteConstraintException e) {
3178                    // The row already exists - update it
3179                    long timestamp = System.currentTimeMillis();
3180                    mStatusUpdateAutoTimestamp.bindLong(1, timestamp);
3181                    bindString(mStatusUpdateAutoTimestamp, 2, status);
3182                    mStatusUpdateAutoTimestamp.bindLong(3, dataId);
3183                    bindString(mStatusUpdateAutoTimestamp, 4, status);
3184                    mStatusUpdateAutoTimestamp.execute();
3185
3186                    bindString(mStatusAttributionUpdate, 1, resPackage);
3187                    bindLong(mStatusAttributionUpdate, 2, iconResource);
3188                    bindLong(mStatusAttributionUpdate, 3, labelResource);
3189                    mStatusAttributionUpdate.bindLong(4, dataId);
3190                    mStatusAttributionUpdate.execute();
3191                }
3192            }
3193        }
3194
3195        if (contactId != -1) {
3196            mLastStatusUpdate.bindLong(1, contactId);
3197            mLastStatusUpdate.bindLong(2, contactId);
3198            mLastStatusUpdate.execute();
3199        }
3200
3201        return dataId;
3202    }
3203
3204    @Override
3205    protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) {
3206        if (VERBOSE_LOGGING) {
3207            Log.v(TAG, "deleteInTransaction: " + uri);
3208        }
3209        flushTransactionalChanges();
3210        final boolean callerIsSyncAdapter =
3211                readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false);
3212        final int match = sUriMatcher.match(uri);
3213        switch (match) {
3214            case SYNCSTATE:
3215                return mDbHelper.getSyncState().delete(mDb, selection, selectionArgs);
3216
3217            case SYNCSTATE_ID:
3218                String selectionWithId =
3219                        (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
3220                        + (selection == null ? "" : " AND (" + selection + ")");
3221                return mDbHelper.getSyncState().delete(mDb, selectionWithId, selectionArgs);
3222
3223            case CONTACTS: {
3224                // TODO
3225                return 0;
3226            }
3227
3228            case CONTACTS_ID: {
3229                long contactId = ContentUris.parseId(uri);
3230                return deleteContact(contactId);
3231            }
3232
3233            case CONTACTS_LOOKUP: {
3234                final List<String> pathSegments = uri.getPathSegments();
3235                final int segmentCount = pathSegments.size();
3236                if (segmentCount < 3) {
3237                    throw new IllegalArgumentException(mDbHelper.exceptionMessage(
3238                            "Missing a lookup key", uri));
3239                }
3240                final String lookupKey = pathSegments.get(2);
3241                final long contactId = lookupContactIdByLookupKey(mDb, lookupKey);
3242                return deleteContact(contactId);
3243            }
3244
3245            case CONTACTS_LOOKUP_ID: {
3246                // lookup contact by id and lookup key to see if they still match the actual record
3247                long contactId = ContentUris.parseId(uri);
3248                final List<String> pathSegments = uri.getPathSegments();
3249                final String lookupKey = pathSegments.get(2);
3250                SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
3251                setTablesAndProjectionMapForContacts(lookupQb, uri, null);
3252                String[] args;
3253                if (selectionArgs == null) {
3254                    args = new String[2];
3255                } else {
3256                    args = new String[selectionArgs.length + 2];
3257                    System.arraycopy(selectionArgs, 0, args, 2, selectionArgs.length);
3258                }
3259                args[0] = String.valueOf(contactId);
3260                args[1] = Uri.encode(lookupKey);
3261                lookupQb.appendWhere(Contacts._ID + "=? AND " + Contacts.LOOKUP_KEY + "=?");
3262                final SQLiteDatabase db = mDbHelper.getReadableDatabase();
3263                Cursor c = query(db, lookupQb, null, selection, args, null, null, null);
3264                try {
3265                    if (c.getCount() == 1) {
3266                        // contact was unmodified so go ahead and delete it
3267                        return deleteContact(contactId);
3268                    } else {
3269                        // row was changed (e.g. the merging might have changed), we got multiple
3270                        // rows or the supplied selection filtered the record out
3271                        return 0;
3272                    }
3273                } finally {
3274                    c.close();
3275                }
3276            }
3277
3278            case RAW_CONTACTS: {
3279                int numDeletes = 0;
3280                Cursor c = mDb.query(Tables.RAW_CONTACTS,
3281                        new String[]{RawContacts._ID, RawContacts.CONTACT_ID},
3282                        appendAccountToSelection(uri, selection), selectionArgs, null, null, null);
3283                try {
3284                    while (c.moveToNext()) {
3285                        final long rawContactId = c.getLong(0);
3286                        long contactId = c.getLong(1);
3287                        numDeletes += deleteRawContact(rawContactId, contactId,
3288                                callerIsSyncAdapter);
3289                    }
3290                } finally {
3291                    c.close();
3292                }
3293                return numDeletes;
3294            }
3295
3296            case RAW_CONTACTS_ID: {
3297                final long rawContactId = ContentUris.parseId(uri);
3298                return deleteRawContact(rawContactId, mDbHelper.getContactId(rawContactId),
3299                        callerIsSyncAdapter);
3300            }
3301
3302            case DATA: {
3303                mSyncToNetwork |= !callerIsSyncAdapter;
3304                return deleteData(appendAccountToSelection(uri, selection), selectionArgs,
3305                        callerIsSyncAdapter);
3306            }
3307
3308            case DATA_ID:
3309            case PHONES_ID:
3310            case EMAILS_ID:
3311            case POSTALS_ID: {
3312                long dataId = ContentUris.parseId(uri);
3313                mSyncToNetwork |= !callerIsSyncAdapter;
3314                mSelectionArgs1[0] = String.valueOf(dataId);
3315                return deleteData(Data._ID + "=?", mSelectionArgs1, callerIsSyncAdapter);
3316            }
3317
3318            case GROUPS_ID: {
3319                mSyncToNetwork |= !callerIsSyncAdapter;
3320                return deleteGroup(uri, ContentUris.parseId(uri), callerIsSyncAdapter);
3321            }
3322
3323            case GROUPS: {
3324                int numDeletes = 0;
3325                Cursor c = mDb.query(Tables.GROUPS, new String[]{Groups._ID},
3326                        appendAccountToSelection(uri, selection), selectionArgs, null, null, null);
3327                try {
3328                    while (c.moveToNext()) {
3329                        numDeletes += deleteGroup(uri, c.getLong(0), callerIsSyncAdapter);
3330                    }
3331                } finally {
3332                    c.close();
3333                }
3334                if (numDeletes > 0) {
3335                    mSyncToNetwork |= !callerIsSyncAdapter;
3336                }
3337                return numDeletes;
3338            }
3339
3340            case SETTINGS: {
3341                mSyncToNetwork |= !callerIsSyncAdapter;
3342                return deleteSettings(uri, appendAccountToSelection(uri, selection), selectionArgs);
3343            }
3344
3345            case STATUS_UPDATES: {
3346                return deleteStatusUpdates(selection, selectionArgs);
3347            }
3348
3349            default: {
3350                mSyncToNetwork = true;
3351                return mLegacyApiSupport.delete(uri, selection, selectionArgs);
3352            }
3353        }
3354    }
3355
3356    public int deleteGroup(Uri uri, long groupId, boolean callerIsSyncAdapter) {
3357        mGroupIdCache.clear();
3358        final long groupMembershipMimetypeId = mDbHelper
3359                .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3360        mDb.delete(Tables.DATA, DataColumns.MIMETYPE_ID + "="
3361                + groupMembershipMimetypeId + " AND " + GroupMembership.GROUP_ROW_ID + "="
3362                + groupId, null);
3363
3364        try {
3365            if (callerIsSyncAdapter) {
3366                return mDb.delete(Tables.GROUPS, Groups._ID + "=" + groupId, null);
3367            } else {
3368                mValues.clear();
3369                mValues.put(Groups.DELETED, 1);
3370                mValues.put(Groups.DIRTY, 1);
3371                return mDb.update(Tables.GROUPS, mValues, Groups._ID + "=" + groupId, null);
3372            }
3373        } finally {
3374            mVisibleTouched = true;
3375        }
3376    }
3377
3378    private int deleteSettings(Uri uri, String selection, String[] selectionArgs) {
3379        final int count = mDb.delete(Tables.SETTINGS, selection, selectionArgs);
3380        mVisibleTouched = true;
3381        return count;
3382    }
3383
3384    private int deleteContact(long contactId) {
3385        mSelectionArgs1[0] = Long.toString(contactId);
3386        Cursor c = mDb.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID},
3387                RawContacts.CONTACT_ID + "=?", mSelectionArgs1,
3388                null, null, null);
3389        try {
3390            while (c.moveToNext()) {
3391                long rawContactId = c.getLong(0);
3392                markRawContactAsDeleted(rawContactId);
3393            }
3394        } finally {
3395            c.close();
3396        }
3397
3398        return mDb.delete(Tables.CONTACTS, Contacts._ID + "=" + contactId, null);
3399    }
3400
3401    public int deleteRawContact(long rawContactId, long contactId, boolean callerIsSyncAdapter) {
3402        mContactAggregator.invalidateAggregationExceptionCache();
3403        if (callerIsSyncAdapter) {
3404            mDb.delete(Tables.PRESENCE, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null);
3405            int count = mDb.delete(Tables.RAW_CONTACTS, RawContacts._ID + "=" + rawContactId, null);
3406            mContactAggregator.updateDisplayNameForContact(mDb, contactId);
3407            return count;
3408        } else {
3409            mDbHelper.removeContactIfSingleton(rawContactId);
3410            return markRawContactAsDeleted(rawContactId);
3411        }
3412    }
3413
3414    private int deleteStatusUpdates(String selection, String[] selectionArgs) {
3415      // delete from both tables: presence and status_updates
3416      // TODO should account type/name be appended to the where clause?
3417      if (VERBOSE_LOGGING) {
3418          Log.v(TAG, "deleting data from status_updates for " + selection);
3419      }
3420      mDb.delete(Tables.STATUS_UPDATES, getWhereClauseForStatusUpdatesTable(selection),
3421          selectionArgs);
3422      return mDb.delete(Tables.PRESENCE, selection, selectionArgs);
3423    }
3424
3425    private int markRawContactAsDeleted(long rawContactId) {
3426        mSyncToNetwork = true;
3427
3428        mValues.clear();
3429        mValues.put(RawContacts.DELETED, 1);
3430        mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED);
3431        mValues.put(RawContactsColumns.AGGREGATION_NEEDED, 1);
3432        mValues.putNull(RawContacts.CONTACT_ID);
3433        mValues.put(RawContacts.DIRTY, 1);
3434        return updateRawContact(rawContactId, mValues);
3435    }
3436
3437    @Override
3438    protected int updateInTransaction(Uri uri, ContentValues values, String selection,
3439            String[] selectionArgs) {
3440        if (VERBOSE_LOGGING) {
3441            Log.v(TAG, "updateInTransaction: " + uri);
3442        }
3443
3444        int count = 0;
3445
3446        final int match = sUriMatcher.match(uri);
3447        if (match == SYNCSTATE_ID && selection == null) {
3448            long rowId = ContentUris.parseId(uri);
3449            Object data = values.get(ContactsContract.SyncState.DATA);
3450            mUpdatedSyncStates.put(rowId, data);
3451            return 1;
3452        }
3453        flushTransactionalChanges();
3454        final boolean callerIsSyncAdapter =
3455                readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false);
3456        switch(match) {
3457            case SYNCSTATE:
3458                return mDbHelper.getSyncState().update(mDb, values,
3459                        appendAccountToSelection(uri, selection), selectionArgs);
3460
3461            case SYNCSTATE_ID: {
3462                selection = appendAccountToSelection(uri, selection);
3463                String selectionWithId =
3464                        (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
3465                        + (selection == null ? "" : " AND (" + selection + ")");
3466                return mDbHelper.getSyncState().update(mDb, values,
3467                        selectionWithId, selectionArgs);
3468            }
3469
3470            case CONTACTS: {
3471                count = updateContactOptions(values, selection, selectionArgs);
3472                break;
3473            }
3474
3475            case CONTACTS_ID: {
3476                count = updateContactOptions(ContentUris.parseId(uri), values);
3477                break;
3478            }
3479
3480            case CONTACTS_LOOKUP:
3481            case CONTACTS_LOOKUP_ID: {
3482                final List<String> pathSegments = uri.getPathSegments();
3483                final int segmentCount = pathSegments.size();
3484                if (segmentCount < 3) {
3485                    throw new IllegalArgumentException(mDbHelper.exceptionMessage(
3486                            "Missing a lookup key", uri));
3487                }
3488                final String lookupKey = pathSegments.get(2);
3489                final long contactId = lookupContactIdByLookupKey(mDb, lookupKey);
3490                count = updateContactOptions(contactId, values);
3491                break;
3492            }
3493
3494            case RAW_CONTACTS_DATA: {
3495                final String rawContactId = uri.getPathSegments().get(1);
3496                String selectionWithId = (Data.RAW_CONTACT_ID + "=" + rawContactId + " ")
3497                    + (selection == null ? "" : " AND " + selection);
3498
3499                count = updateData(uri, values, selectionWithId, selectionArgs, callerIsSyncAdapter);
3500
3501                break;
3502            }
3503
3504            case DATA: {
3505                count = updateData(uri, values, appendAccountToSelection(uri, selection),
3506                        selectionArgs, callerIsSyncAdapter);
3507                if (count > 0) {
3508                    mSyncToNetwork |= !callerIsSyncAdapter;
3509                }
3510                break;
3511            }
3512
3513            case DATA_ID:
3514            case PHONES_ID:
3515            case EMAILS_ID:
3516            case POSTALS_ID: {
3517                count = updateData(uri, values, selection, selectionArgs, callerIsSyncAdapter);
3518                if (count > 0) {
3519                    mSyncToNetwork |= !callerIsSyncAdapter;
3520                }
3521                break;
3522            }
3523
3524            case RAW_CONTACTS: {
3525                selection = appendAccountToSelection(uri, selection);
3526                count = updateRawContacts(values, selection, selectionArgs);
3527                break;
3528            }
3529
3530            case RAW_CONTACTS_ID: {
3531                long rawContactId = ContentUris.parseId(uri);
3532                if (selection != null) {
3533                    selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
3534                    count = updateRawContacts(values, RawContacts._ID + "=?"
3535                                    + " AND(" + selection + ")", selectionArgs);
3536                } else {
3537                    mSelectionArgs1[0] = String.valueOf(rawContactId);
3538                    count = updateRawContacts(values, RawContacts._ID + "=?", mSelectionArgs1);
3539                }
3540                break;
3541            }
3542
3543            case GROUPS: {
3544                count = updateGroups(uri, values, appendAccountToSelection(uri, selection),
3545                        selectionArgs, callerIsSyncAdapter);
3546                if (count > 0) {
3547                    mSyncToNetwork |= !callerIsSyncAdapter;
3548                }
3549                break;
3550            }
3551
3552            case GROUPS_ID: {
3553                long groupId = ContentUris.parseId(uri);
3554                selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(groupId));
3555                String selectionWithId = Groups._ID + "=? "
3556                        + (selection == null ? "" : " AND " + selection);
3557                count = updateGroups(uri, values, selectionWithId, selectionArgs,
3558                        callerIsSyncAdapter);
3559                if (count > 0) {
3560                    mSyncToNetwork |= !callerIsSyncAdapter;
3561                }
3562                break;
3563            }
3564
3565            case AGGREGATION_EXCEPTIONS: {
3566                count = updateAggregationException(mDb, values);
3567                break;
3568            }
3569
3570            case SETTINGS: {
3571                count = updateSettings(uri, values, appendAccountToSelection(uri, selection),
3572                        selectionArgs);
3573                mSyncToNetwork |= !callerIsSyncAdapter;
3574                break;
3575            }
3576
3577            case STATUS_UPDATES: {
3578                count = updateStatusUpdate(uri, values, selection, selectionArgs);
3579                break;
3580            }
3581
3582            default: {
3583                mSyncToNetwork = true;
3584                return mLegacyApiSupport.update(uri, values, selection, selectionArgs);
3585            }
3586        }
3587
3588        return count;
3589    }
3590
3591    private int updateStatusUpdate(Uri uri, ContentValues values, String selection,
3592        String[] selectionArgs) {
3593        // update status_updates table, if status is provided
3594        // TODO should account type/name be appended to the where clause?
3595        int updateCount = 0;
3596        ContentValues settableValues = getSettableColumnsForStatusUpdatesTable(values);
3597        if (settableValues.size() > 0) {
3598          updateCount = mDb.update(Tables.STATUS_UPDATES,
3599                    settableValues,
3600                    getWhereClauseForStatusUpdatesTable(selection),
3601                    selectionArgs);
3602        }
3603
3604        // now update the Presence table
3605        settableValues = getSettableColumnsForPresenceTable(values);
3606        if (settableValues.size() > 0) {
3607          updateCount = mDb.update(Tables.PRESENCE, settableValues,
3608                    selection, selectionArgs);
3609        }
3610        // TODO updateCount is not entirely a valid count of updated rows because 2 tables could
3611        // potentially get updated in this method.
3612        return updateCount;
3613    }
3614
3615    /**
3616     * Build a where clause to select the rows to be updated in status_updates table.
3617     */
3618    private String getWhereClauseForStatusUpdatesTable(String selection) {
3619        mSb.setLength(0);
3620        mSb.append(WHERE_CLAUSE_FOR_STATUS_UPDATES_TABLE);
3621        mSb.append(selection);
3622        mSb.append(")");
3623        return mSb.toString();
3624    }
3625
3626    private ContentValues getSettableColumnsForStatusUpdatesTable(ContentValues values) {
3627        mValues.clear();
3628        ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS, values,
3629            StatusUpdates.STATUS);
3630        ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_TIMESTAMP, values,
3631            StatusUpdates.STATUS_TIMESTAMP);
3632        ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_RES_PACKAGE, values,
3633            StatusUpdates.STATUS_RES_PACKAGE);
3634        ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_LABEL, values,
3635            StatusUpdates.STATUS_LABEL);
3636        ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_ICON, values,
3637            StatusUpdates.STATUS_ICON);
3638        return mValues;
3639    }
3640
3641    private ContentValues getSettableColumnsForPresenceTable(ContentValues values) {
3642        mValues.clear();
3643        ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.PRESENCE, values,
3644            StatusUpdates.PRESENCE);
3645        return mValues;
3646    }
3647
3648    private int updateGroups(Uri uri, ContentValues values, String selectionWithId,
3649            String[] selectionArgs, boolean callerIsSyncAdapter) {
3650
3651        mGroupIdCache.clear();
3652
3653        ContentValues updatedValues;
3654        if (!callerIsSyncAdapter && !values.containsKey(Groups.DIRTY)) {
3655            updatedValues = mValues;
3656            updatedValues.clear();
3657            updatedValues.putAll(values);
3658            updatedValues.put(Groups.DIRTY, 1);
3659        } else {
3660            updatedValues = values;
3661        }
3662
3663        int count = mDb.update(Tables.GROUPS, updatedValues, selectionWithId, selectionArgs);
3664        if (updatedValues.containsKey(Groups.GROUP_VISIBLE)) {
3665            mVisibleTouched = true;
3666        }
3667        if (updatedValues.containsKey(Groups.SHOULD_SYNC)
3668                && updatedValues.getAsInteger(Groups.SHOULD_SYNC) != 0) {
3669            Cursor c = mDb.query(Tables.GROUPS, new String[]{Groups.ACCOUNT_NAME,
3670                    Groups.ACCOUNT_TYPE}, selectionWithId, selectionArgs, null,
3671                    null, null);
3672            String accountName;
3673            String accountType;
3674            try {
3675                while (c.moveToNext()) {
3676                    accountName = c.getString(0);
3677                    accountType = c.getString(1);
3678                    if(!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3679                        Account account = new Account(accountName, accountType);
3680                        ContentResolver.requestSync(account, ContactsContract.AUTHORITY,
3681                                new Bundle());
3682                        break;
3683                    }
3684                }
3685            } finally {
3686                c.close();
3687            }
3688        }
3689        return count;
3690    }
3691
3692    private int updateSettings(Uri uri, ContentValues values, String selection,
3693            String[] selectionArgs) {
3694        final int count = mDb.update(Tables.SETTINGS, values, selection, selectionArgs);
3695        if (values.containsKey(Settings.UNGROUPED_VISIBLE)) {
3696            mVisibleTouched = true;
3697        }
3698        return count;
3699    }
3700
3701    private int updateRawContacts(ContentValues values, String selection, String[] selectionArgs) {
3702        if (values.containsKey(RawContacts.CONTACT_ID)) {
3703            throw new IllegalArgumentException(RawContacts.CONTACT_ID + " should not be included " +
3704                    "in content values. Contact IDs are assigned automatically");
3705        }
3706
3707        int count = 0;
3708        Cursor cursor = mDb.query(mDbHelper.getRawContactView(),
3709                new String[] { RawContacts._ID }, selection,
3710                selectionArgs, null, null, null);
3711        try {
3712            while (cursor.moveToNext()) {
3713                long rawContactId = cursor.getLong(0);
3714                updateRawContact(rawContactId, values);
3715                count++;
3716            }
3717        } finally {
3718            cursor.close();
3719        }
3720
3721        return count;
3722    }
3723
3724    private int updateRawContact(long rawContactId, ContentValues values) {
3725        final String selection = RawContacts._ID + " = ?";
3726        mSelectionArgs1[0] = Long.toString(rawContactId);
3727        final boolean requestUndoDelete = (values.containsKey(RawContacts.DELETED)
3728                && values.getAsInteger(RawContacts.DELETED) == 0);
3729        int previousDeleted = 0;
3730        String accountType = null;
3731        String accountName = null;
3732        if (requestUndoDelete) {
3733            Cursor cursor = mDb.query(RawContactsQuery.TABLE, RawContactsQuery.COLUMNS, selection,
3734                    mSelectionArgs1, null, null, null);
3735            try {
3736                if (cursor.moveToFirst()) {
3737                    previousDeleted = cursor.getInt(RawContactsQuery.DELETED);
3738                    accountType = cursor.getString(RawContactsQuery.ACCOUNT_TYPE);
3739                    accountName = cursor.getString(RawContactsQuery.ACCOUNT_NAME);
3740                }
3741            } finally {
3742                cursor.close();
3743            }
3744            values.put(ContactsContract.RawContacts.AGGREGATION_MODE,
3745                    ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT);
3746        }
3747
3748        int count = mDb.update(Tables.RAW_CONTACTS, values, selection, mSelectionArgs1);
3749        if (count != 0) {
3750            if (values.containsKey(RawContacts.AGGREGATION_MODE)) {
3751                int aggregationMode = values.getAsInteger(RawContacts.AGGREGATION_MODE);
3752
3753                // As per ContactsContract documentation, changing aggregation mode
3754                // to DEFAULT should not trigger aggregation
3755                if (aggregationMode != RawContacts.AGGREGATION_MODE_DEFAULT) {
3756                    mContactAggregator.markForAggregation(rawContactId, aggregationMode, false);
3757                }
3758            }
3759            if (values.containsKey(RawContacts.STARRED)) {
3760                mContactAggregator.updateStarred(rawContactId);
3761            }
3762            if (values.containsKey(RawContacts.SOURCE_ID)) {
3763                mContactAggregator.updateLookupKeyForRawContact(mDb, rawContactId);
3764            }
3765            if (values.containsKey(RawContacts.NAME_VERIFIED)) {
3766
3767                // If setting NAME_VERIFIED for this raw contact, reset it for all
3768                // other raw contacts in the same aggregate
3769                if (values.getAsInteger(RawContacts.NAME_VERIFIED) != 0) {
3770                    mResetNameVerifiedForOtherRawContacts.bindLong(1, rawContactId);
3771                    mResetNameVerifiedForOtherRawContacts.bindLong(2, rawContactId);
3772                    mResetNameVerifiedForOtherRawContacts.execute();
3773                }
3774                mContactAggregator.updateDisplayNameForRawContact(mDb, rawContactId);
3775            }
3776            if (requestUndoDelete && previousDeleted == 1) {
3777                // undo delete, needs aggregation again.
3778                mInsertedRawContacts.put(rawContactId, new Account(accountName, accountType));
3779            }
3780        }
3781        return count;
3782    }
3783
3784    private int updateData(Uri uri, ContentValues values, String selection,
3785            String[] selectionArgs, boolean callerIsSyncAdapter) {
3786        mValues.clear();
3787        mValues.putAll(values);
3788        mValues.remove(Data._ID);
3789        mValues.remove(Data.RAW_CONTACT_ID);
3790        mValues.remove(Data.MIMETYPE);
3791
3792        String packageName = values.getAsString(Data.RES_PACKAGE);
3793        if (packageName != null) {
3794            mValues.remove(Data.RES_PACKAGE);
3795            mValues.put(DataColumns.PACKAGE_ID, mDbHelper.getPackageId(packageName));
3796        }
3797
3798        boolean containsIsSuperPrimary = mValues.containsKey(Data.IS_SUPER_PRIMARY);
3799        boolean containsIsPrimary = mValues.containsKey(Data.IS_PRIMARY);
3800
3801        // Remove primary or super primary values being set to 0. This is disallowed by the
3802        // content provider.
3803        if (containsIsSuperPrimary && mValues.getAsInteger(Data.IS_SUPER_PRIMARY) == 0) {
3804            containsIsSuperPrimary = false;
3805            mValues.remove(Data.IS_SUPER_PRIMARY);
3806        }
3807        if (containsIsPrimary && mValues.getAsInteger(Data.IS_PRIMARY) == 0) {
3808            containsIsPrimary = false;
3809            mValues.remove(Data.IS_PRIMARY);
3810        }
3811
3812        int count = 0;
3813
3814        // Note that the query will return data according to the access restrictions,
3815        // so we don't need to worry about updating data we don't have permission to read.
3816        Cursor c = query(uri, DataUpdateQuery.COLUMNS, selection, selectionArgs, null);
3817        try {
3818            while(c.moveToNext()) {
3819                count += updateData(mValues, c, callerIsSyncAdapter);
3820            }
3821        } finally {
3822            c.close();
3823        }
3824
3825        return count;
3826    }
3827
3828    private int updateData(ContentValues values, Cursor c, boolean callerIsSyncAdapter) {
3829        if (values.size() == 0) {
3830            return 0;
3831        }
3832
3833        final String mimeType = c.getString(DataUpdateQuery.MIMETYPE);
3834        DataRowHandler rowHandler = getDataRowHandler(mimeType);
3835        if (rowHandler.update(mDb, values, c, callerIsSyncAdapter)) {
3836            return 1;
3837        } else {
3838            return 0;
3839        }
3840    }
3841
3842    private int updateContactOptions(ContentValues values, String selection,
3843            String[] selectionArgs) {
3844        int count = 0;
3845        Cursor cursor = mDb.query(mDbHelper.getContactView(),
3846                new String[] { Contacts._ID }, selection,
3847                selectionArgs, null, null, null);
3848        try {
3849            while (cursor.moveToNext()) {
3850                long contactId = cursor.getLong(0);
3851                updateContactOptions(contactId, values);
3852                count++;
3853            }
3854        } finally {
3855            cursor.close();
3856        }
3857
3858        return count;
3859    }
3860
3861    private int updateContactOptions(long contactId, ContentValues values) {
3862
3863        mValues.clear();
3864        ContactsDatabaseHelper.copyStringValue(mValues, RawContacts.CUSTOM_RINGTONE,
3865                values, Contacts.CUSTOM_RINGTONE);
3866        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.SEND_TO_VOICEMAIL,
3867                values, Contacts.SEND_TO_VOICEMAIL);
3868        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.LAST_TIME_CONTACTED,
3869                values, Contacts.LAST_TIME_CONTACTED);
3870        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.TIMES_CONTACTED,
3871                values, Contacts.TIMES_CONTACTED);
3872        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.STARRED,
3873                values, Contacts.STARRED);
3874
3875        // Nothing to update - just return
3876        if (mValues.size() == 0) {
3877            return 0;
3878        }
3879
3880        if (mValues.containsKey(RawContacts.STARRED)) {
3881            // Mark dirty when changing starred to trigger sync
3882            mValues.put(RawContacts.DIRTY, 1);
3883        }
3884
3885        mSelectionArgs1[0] = String.valueOf(contactId);
3886        mDb.update(Tables.RAW_CONTACTS, mValues, RawContacts.CONTACT_ID + "=?", mSelectionArgs1);
3887
3888        // Copy changeable values to prevent automatically managed fields from
3889        // being explicitly updated by clients.
3890        mValues.clear();
3891        ContactsDatabaseHelper.copyStringValue(mValues, RawContacts.CUSTOM_RINGTONE,
3892                values, Contacts.CUSTOM_RINGTONE);
3893        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.SEND_TO_VOICEMAIL,
3894                values, Contacts.SEND_TO_VOICEMAIL);
3895        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.LAST_TIME_CONTACTED,
3896                values, Contacts.LAST_TIME_CONTACTED);
3897        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.TIMES_CONTACTED,
3898                values, Contacts.TIMES_CONTACTED);
3899        ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.STARRED,
3900                values, Contacts.STARRED);
3901
3902        int rslt = mDb.update(Tables.CONTACTS, mValues, Contacts._ID + "=?", mSelectionArgs1);
3903
3904        if (values.containsKey(Contacts.LAST_TIME_CONTACTED) &&
3905                !values.containsKey(Contacts.TIMES_CONTACTED)) {
3906            mDb.execSQL(UPDATE_TIMES_CONTACTED_CONTACTS_TABLE, mSelectionArgs1);
3907            mDb.execSQL(UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE, mSelectionArgs1);
3908        }
3909        return rslt;
3910    }
3911
3912    private int updateAggregationException(SQLiteDatabase db, ContentValues values) {
3913        int exceptionType = values.getAsInteger(AggregationExceptions.TYPE);
3914        long rcId1 = values.getAsInteger(AggregationExceptions.RAW_CONTACT_ID1);
3915        long rcId2 = values.getAsInteger(AggregationExceptions.RAW_CONTACT_ID2);
3916
3917        long rawContactId1, rawContactId2;
3918        if (rcId1 < rcId2) {
3919            rawContactId1 = rcId1;
3920            rawContactId2 = rcId2;
3921        } else {
3922            rawContactId2 = rcId1;
3923            rawContactId1 = rcId2;
3924        }
3925
3926        if (exceptionType == AggregationExceptions.TYPE_AUTOMATIC) {
3927            mSelectionArgs2[0] = String.valueOf(rawContactId1);
3928            mSelectionArgs2[1] = String.valueOf(rawContactId2);
3929            db.delete(Tables.AGGREGATION_EXCEPTIONS,
3930                    AggregationExceptions.RAW_CONTACT_ID1 + "=? AND "
3931                    + AggregationExceptions.RAW_CONTACT_ID2 + "=?", mSelectionArgs2);
3932        } else {
3933            ContentValues exceptionValues = new ContentValues(3);
3934            exceptionValues.put(AggregationExceptions.TYPE, exceptionType);
3935            exceptionValues.put(AggregationExceptions.RAW_CONTACT_ID1, rawContactId1);
3936            exceptionValues.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId2);
3937            db.replace(Tables.AGGREGATION_EXCEPTIONS, AggregationExceptions._ID,
3938                    exceptionValues);
3939        }
3940
3941        mContactAggregator.invalidateAggregationExceptionCache();
3942        mContactAggregator.markForAggregation(rawContactId1,
3943                RawContacts.AGGREGATION_MODE_DEFAULT, true);
3944        mContactAggregator.markForAggregation(rawContactId2,
3945                RawContacts.AGGREGATION_MODE_DEFAULT, true);
3946
3947        long contactId1 = mDbHelper.getContactId(rawContactId1);
3948        mContactAggregator.aggregateContact(db, rawContactId1, contactId1);
3949
3950        long contactId2 = mDbHelper.getContactId(rawContactId2);
3951        mContactAggregator.aggregateContact(db, rawContactId2, contactId2);
3952
3953        // The return value is fake - we just confirm that we made a change, not count actual
3954        // rows changed.
3955        return 1;
3956    }
3957
3958    /**
3959     * Check whether GOOGLE_MY_CONTACTS_GROUP exists, otherwise create it.
3960     *
3961     * @return the group id
3962     */
3963    private long getOrCreateMyContactsGroupInTransaction(String accountName, String accountType) {
3964        Cursor cursor = mDb.query(Tables.GROUPS, new String[] {"_id"},
3965                Groups.ACCOUNT_NAME + " =? AND " + Groups.ACCOUNT_TYPE + " =? AND "
3966                    + Groups.TITLE + " =?",
3967                new String[] {accountName, accountType, GOOGLE_MY_CONTACTS_GROUP_TITLE},
3968                null, null, null);
3969        try {
3970            if(cursor.moveToNext()) {
3971                return cursor.getLong(0);
3972            }
3973        } finally {
3974            cursor.close();
3975        }
3976
3977        ContentValues values = new ContentValues();
3978        values.put(Groups.TITLE, GOOGLE_MY_CONTACTS_GROUP_TITLE);
3979        values.put(Groups.ACCOUNT_NAME, accountName);
3980        values.put(Groups.ACCOUNT_TYPE, accountType);
3981        values.put(Groups.GROUP_VISIBLE, "1");
3982        return mDb.insert(Tables.GROUPS, null, values);
3983    }
3984
3985    public void onAccountsUpdated(Account[] accounts) {
3986        // TODO : Check the unit test.
3987        HashSet<Account> existingAccounts = new HashSet<Account>();
3988        boolean hasUnassignedContacts[] = new boolean[]{false};
3989        mDb.beginTransaction();
3990        try {
3991            findValidAccounts(existingAccounts, hasUnassignedContacts);
3992
3993            // Add a row to the ACCOUNTS table for each new account
3994            for (Account account : accounts) {
3995                if (!existingAccounts.contains(account)) {
3996                    mDb.execSQL("INSERT INTO " + Tables.ACCOUNTS + " (" + RawContacts.ACCOUNT_NAME
3997                            + ", " + RawContacts.ACCOUNT_TYPE + ") VALUES (?, ?)",
3998                            new String[] {account.name, account.type});
3999                }
4000            }
4001
4002            // Remove all valid accounts from the existing account set. What is left
4003            // in the accountsToDelete set will be extra accounts whose data must be deleted.
4004            HashSet<Account> accountsToDelete = new HashSet<Account>(existingAccounts);
4005            for (Account account : accounts) {
4006                accountsToDelete.remove(account);
4007            }
4008
4009            for (Account account : accountsToDelete) {
4010                Log.d(TAG, "removing data for removed account " + account);
4011                String[] params = new String[] {account.name, account.type};
4012                mDb.execSQL(
4013                        "DELETE FROM " + Tables.GROUPS +
4014                        " WHERE " + Groups.ACCOUNT_NAME + " = ?" +
4015                                " AND " + Groups.ACCOUNT_TYPE + " = ?", params);
4016                mDb.execSQL(
4017                        "DELETE FROM " + Tables.PRESENCE +
4018                        " WHERE " + PresenceColumns.RAW_CONTACT_ID + " IN (" +
4019                                "SELECT " + RawContacts._ID +
4020                                " FROM " + Tables.RAW_CONTACTS +
4021                                " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" +
4022                                " AND " + RawContacts.ACCOUNT_TYPE + " = ?)", params);
4023                mDb.execSQL(
4024                        "DELETE FROM " + Tables.RAW_CONTACTS +
4025                        " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" +
4026                        " AND " + RawContacts.ACCOUNT_TYPE + " = ?", params);
4027                mDb.execSQL(
4028                        "DELETE FROM " + Tables.SETTINGS +
4029                        " WHERE " + Settings.ACCOUNT_NAME + " = ?" +
4030                        " AND " + Settings.ACCOUNT_TYPE + " = ?", params);
4031                mDb.execSQL(
4032                        "DELETE FROM " + Tables.ACCOUNTS +
4033                        " WHERE " + RawContacts.ACCOUNT_NAME + "=?" +
4034                        " AND " + RawContacts.ACCOUNT_TYPE + "=?", params);
4035            }
4036
4037            if (!accountsToDelete.isEmpty()) {
4038                // Find all aggregated contacts that used to contain the raw contacts
4039                // we have just deleted and see if they are still referencing the deleted
4040                // names of photos.  If so, fix up those contacts.
4041                HashSet<Long> orphanContactIds = Sets.newHashSet();
4042                Cursor cursor = mDb.rawQuery("SELECT " + Contacts._ID +
4043                        " FROM " + Tables.CONTACTS +
4044                        " WHERE (" + Contacts.NAME_RAW_CONTACT_ID + " NOT NULL AND " +
4045                                Contacts.NAME_RAW_CONTACT_ID + " NOT IN " +
4046                                        "(SELECT " + RawContacts._ID +
4047                                        " FROM " + Tables.RAW_CONTACTS + "))" +
4048                        " OR (" + Contacts.PHOTO_ID + " NOT NULL AND " +
4049                                Contacts.PHOTO_ID + " NOT IN " +
4050                                        "(SELECT " + Data._ID +
4051                                        " FROM " + Tables.DATA + "))", null);
4052                try {
4053                    while (cursor.moveToNext()) {
4054                        orphanContactIds.add(cursor.getLong(0));
4055                    }
4056                } finally {
4057                    cursor.close();
4058                }
4059
4060                for (Long contactId : orphanContactIds) {
4061                    mContactAggregator.updateAggregateData(contactId);
4062                }
4063            }
4064
4065            if (hasUnassignedContacts[0]) {
4066
4067                Account primaryAccount = null;
4068                for (Account account : accounts) {
4069                    if (isWritableAccount(account.type)) {
4070                        primaryAccount = account;
4071                        break;
4072                    }
4073                }
4074
4075                if (primaryAccount != null) {
4076                    String[] params = new String[] {primaryAccount.name, primaryAccount.type};
4077                    if (primaryAccount.type.equals(DEFAULT_ACCOUNT_TYPE)) {
4078                        long groupId = getOrCreateMyContactsGroupInTransaction(
4079                                primaryAccount.name, primaryAccount.type);
4080                        if (groupId != -1) {
4081                            long mimeTypeId = mDbHelper.getMimeTypeId(
4082                                    GroupMembership.CONTENT_ITEM_TYPE);
4083                            mDb.execSQL(
4084                                    "INSERT INTO " + Tables.DATA + "(" + DataColumns.MIMETYPE_ID +
4085                                        ", " + Data.RAW_CONTACT_ID + ", "
4086                                        + GroupMembership.GROUP_ROW_ID + ") " +
4087                                    "SELECT " + mimeTypeId + ", "
4088                                            + RawContacts._ID + ", " + groupId +
4089                                    " FROM " + Tables.RAW_CONTACTS +
4090                                    " WHERE " + RawContacts.ACCOUNT_NAME + " IS NULL" +
4091                                    " AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"
4092                            );
4093                        }
4094                    }
4095                    mDb.execSQL(
4096                            "UPDATE " + Tables.RAW_CONTACTS +
4097                            " SET " + RawContacts.ACCOUNT_NAME + "=?,"
4098                                    + RawContacts.ACCOUNT_TYPE + "=?" +
4099                            " WHERE " + RawContacts.ACCOUNT_NAME + " IS NULL" +
4100                            " AND " + RawContacts.ACCOUNT_TYPE + " IS NULL", params);
4101
4102                    // We don't currently support groups for unsynced accounts, so this is for
4103                    // the future
4104                    mDb.execSQL(
4105                            "UPDATE " + Tables.GROUPS +
4106                            " SET " + Groups.ACCOUNT_NAME + "=?,"
4107                                    + Groups.ACCOUNT_TYPE + "=?" +
4108                            " WHERE " + Groups.ACCOUNT_NAME + " IS NULL" +
4109                            " AND " + Groups.ACCOUNT_TYPE + " IS NULL", params);
4110
4111                    mDb.execSQL(
4112                            "DELETE FROM " + Tables.ACCOUNTS +
4113                            " WHERE " + RawContacts.ACCOUNT_NAME + " IS NULL" +
4114                            " AND " + RawContacts.ACCOUNT_TYPE + " IS NULL");
4115                }
4116            }
4117
4118            mDbHelper.updateAllVisible();
4119
4120            mDbHelper.getSyncState().onAccountsChanged(mDb, accounts);
4121            mDb.setTransactionSuccessful();
4122        } finally {
4123            mDb.endTransaction();
4124        }
4125        mAccountWritability.clear();
4126    }
4127
4128    /**
4129     * Finds all distinct accounts present in the specified table.
4130     */
4131    private void findValidAccounts(Set<Account> validAccounts, boolean[] hasUnassignedContacts) {
4132        Cursor c = mDb.rawQuery(
4133                "SELECT " + RawContacts.ACCOUNT_NAME + "," + RawContacts.ACCOUNT_TYPE +
4134                " FROM " + Tables.ACCOUNTS, null);
4135        try {
4136            while (c.moveToNext()) {
4137                if (c.isNull(0) && c.isNull(1)) {
4138                    hasUnassignedContacts[0] = true;
4139                } else {
4140                    validAccounts.add(new Account(c.getString(0), c.getString(1)));
4141                }
4142            }
4143        } finally {
4144            c.close();
4145        }
4146    }
4147
4148    /**
4149     * Test all against {@link TextUtils#isEmpty(CharSequence)}.
4150     */
4151    private static boolean areAllEmpty(ContentValues values, String[] keys) {
4152        for (String key : keys) {
4153            if (!TextUtils.isEmpty(values.getAsString(key))) {
4154                return false;
4155            }
4156        }
4157        return true;
4158    }
4159
4160    /**
4161     * Returns true if a value (possibly null) is specified for at least one of the supplied keys.
4162     */
4163    private static boolean areAnySpecified(ContentValues values, String[] keys) {
4164        for (String key : keys) {
4165            if (values.containsKey(key)) {
4166                return true;
4167            }
4168        }
4169        return false;
4170    }
4171
4172    @Override
4173    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
4174            String sortOrder) {
4175        if (VERBOSE_LOGGING) {
4176            Log.v(TAG, "query: " + uri);
4177        }
4178
4179        final SQLiteDatabase db = mDbHelper.getReadableDatabase();
4180
4181        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
4182        String groupBy = null;
4183        String limit = getLimit(uri);
4184
4185        // TODO: Consider writing a test case for RestrictionExceptions when you
4186        // write a new query() block to make sure it protects restricted data.
4187        final int match = sUriMatcher.match(uri);
4188        switch (match) {
4189            case SYNCSTATE:
4190                return mDbHelper.getSyncState().query(db, projection, selection,  selectionArgs,
4191                        sortOrder);
4192
4193            case CONTACTS: {
4194                setTablesAndProjectionMapForContacts(qb, uri, projection);
4195                break;
4196            }
4197
4198            case CONTACTS_ID: {
4199                long contactId = ContentUris.parseId(uri);
4200                setTablesAndProjectionMapForContacts(qb, uri, projection);
4201                selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
4202                qb.appendWhere(Contacts._ID + "=?");
4203                break;
4204            }
4205
4206            case CONTACTS_LOOKUP:
4207            case CONTACTS_LOOKUP_ID: {
4208                List<String> pathSegments = uri.getPathSegments();
4209                int segmentCount = pathSegments.size();
4210                if (segmentCount < 3) {
4211                    throw new IllegalArgumentException(mDbHelper.exceptionMessage(
4212                            "Missing a lookup key", uri));
4213                }
4214                String lookupKey = pathSegments.get(2);
4215                if (segmentCount == 4) {
4216                    // TODO: pull this out into a method and generalize to not require contactId
4217                    long contactId = Long.parseLong(pathSegments.get(3));
4218                    SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder();
4219                    setTablesAndProjectionMapForContacts(lookupQb, uri, projection);
4220                    String[] args;
4221                    if (selectionArgs == null) {
4222                        args = new String[2];
4223                    } else {
4224                        args = new String[selectionArgs.length + 2];
4225                        System.arraycopy(selectionArgs, 0, args, 2, selectionArgs.length);
4226                    }
4227                    args[0] = String.valueOf(contactId);
4228                    args[1] = Uri.encode(lookupKey);
4229                    lookupQb.appendWhere(Contacts._ID + "=? AND " + Contacts.LOOKUP_KEY + "=?");
4230                    Cursor c = query(db, lookupQb, projection, selection, args, sortOrder,
4231                            groupBy, limit);
4232                    if (c.getCount() != 0) {
4233                        return c;
4234                    }
4235
4236                    c.close();
4237                }
4238
4239                setTablesAndProjectionMapForContacts(qb, uri, projection);
4240                selectionArgs = insertSelectionArg(selectionArgs,
4241                        String.valueOf(lookupContactIdByLookupKey(db, lookupKey)));
4242                qb.appendWhere(Contacts._ID + "=?");
4243                break;
4244            }
4245
4246            case CONTACTS_AS_VCARD: {
4247                // When reading as vCard always use restricted view
4248                final String lookupKey = Uri.encode(uri.getPathSegments().get(2));
4249                qb.setTables(mDbHelper.getContactView(true /* require restricted */));
4250                qb.setProjectionMap(sContactsVCardProjectionMap);
4251                selectionArgs = insertSelectionArg(selectionArgs,
4252                        String.valueOf(lookupContactIdByLookupKey(db, lookupKey)));
4253                qb.appendWhere(Contacts._ID + "=?");
4254                break;
4255            }
4256
4257            case CONTACTS_AS_MULTI_VCARD: {
4258                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
4259                String currentDateString = dateFormat.format(new Date()).toString();
4260                return db.rawQuery(
4261                    "SELECT" +
4262                    " 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," +
4263                    " NULL AS " + OpenableColumns.SIZE,
4264                    new String[] { currentDateString });
4265            }
4266
4267            case CONTACTS_FILTER: {
4268                String filterParam = "";
4269                if (uri.getPathSegments().size() > 2) {
4270                    filterParam = uri.getLastPathSegment();
4271                }
4272                setTablesAndProjectionMapForContactsWithSnippet(qb, uri, projection, filterParam);
4273                break;
4274            }
4275
4276            case CONTACTS_STREQUENT_FILTER:
4277            case CONTACTS_STREQUENT: {
4278                String filterSql = null;
4279                if (match == CONTACTS_STREQUENT_FILTER
4280                        && uri.getPathSegments().size() > 3) {
4281                    String filterParam = uri.getLastPathSegment();
4282                    StringBuilder sb = new StringBuilder();
4283                    sb.append(Contacts._ID + " IN ");
4284                    appendContactFilterAsNestedQuery(sb, filterParam);
4285                    filterSql = sb.toString();
4286                }
4287
4288                setTablesAndProjectionMapForContacts(qb, uri, projection);
4289
4290                String[] starredProjection = null;
4291                String[] frequentProjection = null;
4292                if (projection != null) {
4293                    starredProjection = appendProjectionArg(projection, TIMES_CONTACED_SORT_COLUMN);
4294                    frequentProjection = appendProjectionArg(projection, TIMES_CONTACED_SORT_COLUMN);
4295                }
4296
4297                // Build the first query for starred
4298                if (filterSql != null) {
4299                    qb.appendWhere(filterSql);
4300                }
4301                qb.setProjectionMap(sStrequentStarredProjectionMap);
4302                final String starredQuery = qb.buildQuery(starredProjection, Contacts.STARRED + "=1",
4303                        null, Contacts._ID, null, null, null);
4304
4305                // Build the second query for frequent
4306                qb = new SQLiteQueryBuilder();
4307                setTablesAndProjectionMapForContacts(qb, uri, projection);
4308                if (filterSql != null) {
4309                    qb.appendWhere(filterSql);
4310                }
4311                qb.setProjectionMap(sStrequentFrequentProjectionMap);
4312                final String frequentQuery = qb.buildQuery(frequentProjection,
4313                        Contacts.TIMES_CONTACTED + " > 0 AND (" + Contacts.STARRED
4314                        + " = 0 OR " + Contacts.STARRED + " IS NULL)",
4315                        null, Contacts._ID, null, null, null);
4316
4317                // Put them together
4318                final String query = qb.buildUnionQuery(new String[] {starredQuery, frequentQuery},
4319                        STREQUENT_ORDER_BY, STREQUENT_LIMIT);
4320                Cursor c = db.rawQuery(query, null);
4321                if (c != null) {
4322                    c.setNotificationUri(getContext().getContentResolver(),
4323                            ContactsContract.AUTHORITY_URI);
4324                }
4325                return c;
4326            }
4327
4328            case CONTACTS_GROUP: {
4329                setTablesAndProjectionMapForContacts(qb, uri, projection);
4330                if (uri.getPathSegments().size() > 2) {
4331                    qb.appendWhere(CONTACTS_IN_GROUP_SELECT);
4332                    selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4333                }
4334                break;
4335            }
4336
4337            case CONTACTS_DATA: {
4338                long contactId = Long.parseLong(uri.getPathSegments().get(1));
4339                setTablesAndProjectionMapForData(qb, uri, projection, false);
4340                selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
4341                qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
4342                break;
4343            }
4344
4345            case CONTACTS_PHOTO: {
4346                long contactId = Long.parseLong(uri.getPathSegments().get(1));
4347                setTablesAndProjectionMapForData(qb, uri, projection, false);
4348                selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId));
4349                qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?");
4350                qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID);
4351                break;
4352            }
4353
4354            case PHONES: {
4355                setTablesAndProjectionMapForData(qb, uri, projection, false);
4356                qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'");
4357                break;
4358            }
4359
4360            case PHONES_ID: {
4361                setTablesAndProjectionMapForData(qb, uri, projection, false);
4362                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4363                qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'");
4364                qb.appendWhere(" AND " + Data._ID + "=?");
4365                break;
4366            }
4367
4368            case PHONES_FILTER: {
4369                setTablesAndProjectionMapForData(qb, uri, projection, true);
4370                qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'");
4371                if (uri.getPathSegments().size() > 2) {
4372                    String filterParam = uri.getLastPathSegment();
4373                    StringBuilder sb = new StringBuilder();
4374                    sb.append(" AND (");
4375
4376                    boolean hasCondition = false;
4377                    boolean orNeeded = false;
4378                    String normalizedName = NameNormalizer.normalize(filterParam);
4379                    if (normalizedName.length() > 0) {
4380                        sb.append(Data.RAW_CONTACT_ID + " IN ");
4381                        appendRawContactsByNormalizedNameFilter(sb, normalizedName, false);
4382                        orNeeded = true;
4383                        hasCondition = true;
4384                    }
4385
4386                    if (isPhoneNumber(filterParam)) {
4387                        if (orNeeded) {
4388                            sb.append(" OR ");
4389                        }
4390                        String number = PhoneNumberUtils.convertKeypadLettersToDigits(filterParam);
4391                        String reversed = PhoneNumberUtils.getStrippedReversed(number);
4392                        sb.append(Data._ID +
4393                                " IN (SELECT " + PhoneLookupColumns.DATA_ID
4394                                  + " FROM " + Tables.PHONE_LOOKUP
4395                                  + " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '%");
4396                        sb.append(reversed);
4397                        sb.append("')");
4398                        hasCondition = true;
4399                    }
4400
4401                    if (!hasCondition) {
4402                        // If it is neither a phone number nor a name, the query should return
4403                        // an empty cursor.  Let's ensure that.
4404                        sb.append("0");
4405                    }
4406                    sb.append(")");
4407                    qb.appendWhere(sb);
4408                }
4409                groupBy = PhoneColumns.NORMALIZED_NUMBER + "," + RawContacts.CONTACT_ID;
4410                if (sortOrder == null) {
4411                    sortOrder = Contacts.IN_VISIBLE_GROUP + " DESC, " + RawContacts.CONTACT_ID;
4412                }
4413                break;
4414            }
4415
4416            case EMAILS: {
4417                setTablesAndProjectionMapForData(qb, uri, projection, false);
4418                qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'");
4419                break;
4420            }
4421
4422            case EMAILS_ID: {
4423                setTablesAndProjectionMapForData(qb, uri, projection, false);
4424                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4425                qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'"
4426                        + " AND " + Data._ID + "=?");
4427                break;
4428            }
4429
4430            case EMAILS_LOOKUP: {
4431                setTablesAndProjectionMapForData(qb, uri, projection, false);
4432                qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'");
4433                if (uri.getPathSegments().size() > 2) {
4434                    String email = uri.getLastPathSegment();
4435                    String address = mDbHelper.extractAddressFromEmailAddress(email);
4436                    selectionArgs = insertSelectionArg(selectionArgs, address);
4437                    qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)");
4438                }
4439                break;
4440            }
4441
4442            case EMAILS_FILTER: {
4443                setTablesAndProjectionMapForData(qb, uri, projection, true);
4444                String filterParam = null;
4445                if (uri.getPathSegments().size() > 3) {
4446                    filterParam = uri.getLastPathSegment();
4447                    if (TextUtils.isEmpty(filterParam)) {
4448                        filterParam = null;
4449                    }
4450                }
4451
4452                if (filterParam == null) {
4453                    // If the filter is unspecified, return nothing
4454                    qb.appendWhere(" AND 0");
4455                } else {
4456                    StringBuilder sb = new StringBuilder();
4457                    sb.append(" AND " + Data._ID + " IN (");
4458                    sb.append(
4459                            "SELECT " + Data._ID +
4460                            " FROM " + Tables.DATA +
4461                            " WHERE " + DataColumns.MIMETYPE_ID + "=" + mMimeTypeIdEmail +
4462                            " AND " + Data.DATA1 + " LIKE ");
4463                    DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%');
4464                    if (!filterParam.contains("@")) {
4465                        String normalizedName = NameNormalizer.normalize(filterParam);
4466                        if (normalizedName.length() > 0) {
4467
4468                            /*
4469                             * Using a UNION instead of an "OR" to make SQLite use the right
4470                             * indexes. We need it to use the (mimetype,data1) index for the
4471                             * email lookup (see above), but not for the name lookup.
4472                             * SQLite is not smart enough to use the index on one side of an OR
4473                             * but not on the other. Using two separate nested queries
4474                             * and a UNION between them does the job.
4475                             */
4476                            sb.append(
4477                                    " UNION SELECT " + Data._ID +
4478                                    " FROM " + Tables.DATA +
4479                                    " WHERE +" + DataColumns.MIMETYPE_ID + "=" + mMimeTypeIdEmail +
4480                                    " AND " + Data.RAW_CONTACT_ID + " IN ");
4481                            appendRawContactsByNormalizedNameFilter(sb, normalizedName, false);
4482                        }
4483                    }
4484                    sb.append(")");
4485                    qb.appendWhere(sb);
4486                }
4487                groupBy = Email.DATA + "," + RawContacts.CONTACT_ID;
4488                if (sortOrder == null) {
4489                    sortOrder = Contacts.IN_VISIBLE_GROUP + " DESC, " + RawContacts.CONTACT_ID;
4490                }
4491                break;
4492            }
4493
4494            case POSTALS: {
4495                setTablesAndProjectionMapForData(qb, uri, projection, false);
4496                qb.appendWhere(" AND " + Data.MIMETYPE + " = '"
4497                        + StructuredPostal.CONTENT_ITEM_TYPE + "'");
4498                break;
4499            }
4500
4501            case POSTALS_ID: {
4502                setTablesAndProjectionMapForData(qb, uri, projection, false);
4503                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4504                qb.appendWhere(" AND " + Data.MIMETYPE + " = '"
4505                        + StructuredPostal.CONTENT_ITEM_TYPE + "'");
4506                qb.appendWhere(" AND " + Data._ID + "=?");
4507                break;
4508            }
4509
4510            case RAW_CONTACTS: {
4511                setTablesAndProjectionMapForRawContacts(qb, uri);
4512                break;
4513            }
4514
4515            case RAW_CONTACTS_ID: {
4516                long rawContactId = ContentUris.parseId(uri);
4517                setTablesAndProjectionMapForRawContacts(qb, uri);
4518                selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
4519                qb.appendWhere(" AND " + RawContacts._ID + "=?");
4520                break;
4521            }
4522
4523            case RAW_CONTACTS_DATA: {
4524                long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
4525                setTablesAndProjectionMapForData(qb, uri, projection, false);
4526                selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
4527                qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?");
4528                break;
4529            }
4530
4531            case DATA: {
4532                setTablesAndProjectionMapForData(qb, uri, projection, false);
4533                break;
4534            }
4535
4536            case DATA_ID: {
4537                setTablesAndProjectionMapForData(qb, uri, projection, false);
4538                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4539                qb.appendWhere(" AND " + Data._ID + "=?");
4540                break;
4541            }
4542
4543            case PHONE_LOOKUP: {
4544
4545                if (TextUtils.isEmpty(sortOrder)) {
4546                    // Default the sort order to something reasonable so we get consistent
4547                    // results when callers don't request an ordering
4548                    sortOrder = RawContactsColumns.CONCRETE_ID;
4549                }
4550
4551                String number = uri.getPathSegments().size() > 1 ? uri.getLastPathSegment() : "";
4552                mDbHelper.buildPhoneLookupAndContactQuery(qb, number);
4553                qb.setProjectionMap(sPhoneLookupProjectionMap);
4554
4555                // Phone lookup cannot be combined with a selection
4556                selection = null;
4557                selectionArgs = null;
4558                break;
4559            }
4560
4561            case GROUPS: {
4562                qb.setTables(mDbHelper.getGroupView());
4563                qb.setProjectionMap(sGroupsProjectionMap);
4564                appendAccountFromParameter(qb, uri);
4565                break;
4566            }
4567
4568            case GROUPS_ID: {
4569                qb.setTables(mDbHelper.getGroupView());
4570                qb.setProjectionMap(sGroupsProjectionMap);
4571                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4572                qb.appendWhere(Groups._ID + "=?");
4573                break;
4574            }
4575
4576            case GROUPS_SUMMARY: {
4577                qb.setTables(mDbHelper.getGroupView() + " AS groups");
4578                qb.setProjectionMap(sGroupsSummaryProjectionMap);
4579                appendAccountFromParameter(qb, uri);
4580                groupBy = Groups._ID;
4581                break;
4582            }
4583
4584            case AGGREGATION_EXCEPTIONS: {
4585                qb.setTables(Tables.AGGREGATION_EXCEPTIONS);
4586                qb.setProjectionMap(sAggregationExceptionsProjectionMap);
4587                break;
4588            }
4589
4590            case AGGREGATION_SUGGESTIONS: {
4591                long contactId = Long.parseLong(uri.getPathSegments().get(1));
4592                String filter = null;
4593                if (uri.getPathSegments().size() > 3) {
4594                    filter = uri.getPathSegments().get(3);
4595                }
4596                final int maxSuggestions;
4597                if (limit != null) {
4598                    maxSuggestions = Integer.parseInt(limit);
4599                } else {
4600                    maxSuggestions = DEFAULT_MAX_SUGGESTIONS;
4601                }
4602
4603                setTablesAndProjectionMapForContacts(qb, uri, projection);
4604
4605                return mContactAggregator.queryAggregationSuggestions(qb, projection, contactId,
4606                        maxSuggestions, filter);
4607            }
4608
4609            case SETTINGS: {
4610                qb.setTables(Tables.SETTINGS);
4611                qb.setProjectionMap(sSettingsProjectionMap);
4612                appendAccountFromParameter(qb, uri);
4613
4614                // When requesting specific columns, this query requires
4615                // late-binding of the GroupMembership MIME-type.
4616                final String groupMembershipMimetypeId = Long.toString(mDbHelper
4617                        .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE));
4618                if (projection != null && projection.length != 0 &&
4619                        mDbHelper.isInProjection(projection, Settings.UNGROUPED_COUNT)) {
4620                    selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId);
4621                }
4622                if (projection != null && projection.length != 0 &&
4623                        mDbHelper.isInProjection(projection, Settings.UNGROUPED_WITH_PHONES)) {
4624                    selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId);
4625                }
4626
4627                break;
4628            }
4629
4630            case STATUS_UPDATES: {
4631                setTableAndProjectionMapForStatusUpdates(qb, projection);
4632                break;
4633            }
4634
4635            case STATUS_UPDATES_ID: {
4636                setTableAndProjectionMapForStatusUpdates(qb, projection);
4637                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4638                qb.appendWhere(DataColumns.CONCRETE_ID + "=?");
4639                break;
4640            }
4641
4642            case SEARCH_SUGGESTIONS: {
4643                return mGlobalSearchSupport.handleSearchSuggestionsQuery(db, uri, limit);
4644            }
4645
4646            case SEARCH_SHORTCUT: {
4647                String lookupKey = uri.getLastPathSegment();
4648                return mGlobalSearchSupport.handleSearchShortcutRefresh(db, lookupKey, projection);
4649            }
4650
4651            case LIVE_FOLDERS_CONTACTS:
4652                qb.setTables(mDbHelper.getContactView());
4653                qb.setProjectionMap(sLiveFoldersProjectionMap);
4654                break;
4655
4656            case LIVE_FOLDERS_CONTACTS_WITH_PHONES:
4657                qb.setTables(mDbHelper.getContactView());
4658                qb.setProjectionMap(sLiveFoldersProjectionMap);
4659                qb.appendWhere(Contacts.HAS_PHONE_NUMBER + "=1");
4660                break;
4661
4662            case LIVE_FOLDERS_CONTACTS_FAVORITES:
4663                qb.setTables(mDbHelper.getContactView());
4664                qb.setProjectionMap(sLiveFoldersProjectionMap);
4665                qb.appendWhere(Contacts.STARRED + "=1");
4666                break;
4667
4668            case LIVE_FOLDERS_CONTACTS_GROUP_NAME:
4669                qb.setTables(mDbHelper.getContactView());
4670                qb.setProjectionMap(sLiveFoldersProjectionMap);
4671                qb.appendWhere(CONTACTS_IN_GROUP_SELECT);
4672                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
4673                break;
4674
4675            case RAW_CONTACT_ENTITIES: {
4676                setTablesAndProjectionMapForRawContactsEntities(qb, uri);
4677                break;
4678            }
4679
4680            case RAW_CONTACT_ENTITY_ID: {
4681                long rawContactId = Long.parseLong(uri.getPathSegments().get(1));
4682                setTablesAndProjectionMapForRawContactsEntities(qb, uri);
4683                selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId));
4684                qb.appendWhere(" AND " + RawContacts._ID + "=?");
4685                break;
4686            }
4687
4688            case PROVIDER_STATUS: {
4689                return queryProviderStatus(uri, projection);
4690            }
4691
4692            default:
4693                return mLegacyApiSupport.query(uri, projection, selection, selectionArgs,
4694                        sortOrder, limit);
4695        }
4696
4697        qb.setStrictProjectionMap(true);
4698
4699        Cursor cursor =
4700                query(db, qb, projection, selection, selectionArgs, sortOrder, groupBy, limit);
4701        if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) {
4702            cursor = bundleLetterCountExtras(cursor, db, qb, selection, selectionArgs, sortOrder);
4703        }
4704        return cursor;
4705    }
4706
4707    private Cursor query(final SQLiteDatabase db, SQLiteQueryBuilder qb, String[] projection,
4708            String selection, String[] selectionArgs, String sortOrder, String groupBy,
4709            String limit) {
4710        if (projection != null && projection.length == 1
4711                && BaseColumns._COUNT.equals(projection[0])) {
4712            qb.setProjectionMap(sCountProjectionMap);
4713        }
4714        final Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null,
4715                sortOrder, limit);
4716        if (c != null) {
4717            c.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI);
4718        }
4719        return c;
4720    }
4721
4722    /**
4723     * Creates a single-row cursor containing the current status of the provider.
4724     */
4725    private Cursor queryProviderStatus(Uri uri, String[] projection) {
4726        MatrixCursor cursor = new MatrixCursor(projection);
4727        RowBuilder row = cursor.newRow();
4728        for (int i = 0; i < projection.length; i++) {
4729            if (ProviderStatus.STATUS.equals(projection[i])) {
4730                row.add(mProviderStatus);
4731            } else if (ProviderStatus.DATA1.equals(projection[i])) {
4732                row.add(mEstimatedStorageRequirement);
4733            }
4734        }
4735        return cursor;
4736    }
4737
4738
4739    private static final class AddressBookIndexQuery {
4740        public static final String LETTER = "letter";
4741        public static final String TITLE = "title";
4742        public static final String COUNT = "count";
4743
4744        public static final String[] COLUMNS = new String[] {
4745                LETTER, TITLE, COUNT
4746        };
4747
4748        public static final int COLUMN_LETTER = 0;
4749        public static final int COLUMN_TITLE = 1;
4750        public static final int COLUMN_COUNT = 2;
4751
4752        public static final String ORDER_BY = LETTER + " COLLATE " + PHONEBOOK_COLLATOR_NAME;
4753    }
4754
4755    /**
4756     * Computes counts by the address book index titles and adds the resulting tally
4757     * to the returned cursor as a bundle of extras.
4758     */
4759    private Cursor bundleLetterCountExtras(Cursor cursor, final SQLiteDatabase db,
4760            SQLiteQueryBuilder qb, String selection, String[] selectionArgs, String sortOrder) {
4761        String sortKey;
4762
4763        // The sort order suffix could be something like "DESC".
4764        // We want to preserve it in the query even though we will change
4765        // the sort column itself.
4766        String sortOrderSuffix = "";
4767        if (sortOrder != null) {
4768            int spaceIndex = sortOrder.indexOf(' ');
4769            if (spaceIndex != -1) {
4770                sortKey = sortOrder.substring(0, spaceIndex);
4771                sortOrderSuffix = sortOrder.substring(spaceIndex);
4772            } else {
4773                sortKey = sortOrder;
4774            }
4775        } else {
4776            sortKey = Contacts.SORT_KEY_PRIMARY;
4777        }
4778
4779        String locale = getLocale().toString();
4780        HashMap<String, String> projectionMap = Maps.newHashMap();
4781        projectionMap.put(AddressBookIndexQuery.LETTER,
4782                "SUBSTR(" + sortKey + ",1,1) AS " + AddressBookIndexQuery.LETTER);
4783
4784        /**
4785         * Use the GET_PHONEBOOK_INDEX function, which is an android extension for SQLite3,
4786         * to map the first letter of the sort key to a character that is traditionally
4787         * used in phonebooks to represent that letter.  For example, in Korean it will
4788         * be the first consonant in the letter; for Japanese it will be Hiragana rather
4789         * than Katakana.
4790         */
4791        projectionMap.put(AddressBookIndexQuery.TITLE,
4792                "GET_PHONEBOOK_INDEX(SUBSTR(" + sortKey + ",1,1),'" + locale + "')"
4793                        + " AS " + AddressBookIndexQuery.TITLE);
4794        projectionMap.put(AddressBookIndexQuery.COUNT,
4795                "COUNT(" + Contacts._ID + ") AS " + AddressBookIndexQuery.COUNT);
4796        qb.setProjectionMap(projectionMap);
4797
4798        Cursor indexCursor = qb.query(db, AddressBookIndexQuery.COLUMNS, selection, selectionArgs,
4799                AddressBookIndexQuery.ORDER_BY, null /* having */,
4800                AddressBookIndexQuery.ORDER_BY + sortOrderSuffix);
4801
4802        try {
4803            int groupCount = indexCursor.getCount();
4804            String titles[] = new String[groupCount];
4805            int counts[] = new int[groupCount];
4806            int indexCount = 0;
4807            String currentTitle = null;
4808
4809            // Since GET_PHONEBOOK_INDEX is a many-to-1 function, we may end up
4810            // with multiple entries for the same title.  The following code
4811            // collapses those duplicates.
4812            for (int i = 0; i < groupCount; i++) {
4813                indexCursor.moveToNext();
4814                String title = indexCursor.getString(AddressBookIndexQuery.COLUMN_TITLE);
4815                int count = indexCursor.getInt(AddressBookIndexQuery.COLUMN_COUNT);
4816                if (indexCount == 0 || !TextUtils.equals(title, currentTitle)) {
4817                    titles[indexCount] = currentTitle = title;
4818                    counts[indexCount] = count;
4819                    indexCount++;
4820                } else {
4821                    counts[indexCount - 1] += count;
4822                }
4823            }
4824
4825            if (indexCount < groupCount) {
4826                String[] newTitles = new String[indexCount];
4827                System.arraycopy(titles, 0, newTitles, 0, indexCount);
4828                titles = newTitles;
4829
4830                int[] newCounts = new int[indexCount];
4831                System.arraycopy(counts, 0, newCounts, 0, indexCount);
4832                counts = newCounts;
4833            }
4834
4835            final Bundle bundle = new Bundle();
4836            bundle.putStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES, titles);
4837            bundle.putIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS, counts);
4838            return new CursorWrapper(cursor) {
4839
4840                @Override
4841                public Bundle getExtras() {
4842                    return bundle;
4843                }
4844            };
4845        } finally {
4846            indexCursor.close();
4847        }
4848    }
4849
4850    /**
4851     * Returns the contact Id for the contact identified by the lookupKey.
4852     * Robust against changes in the lookup key: if the key has changed, will
4853     * look up the contact by the raw contact IDs or name encoded in the lookup
4854     * key.
4855     */
4856    public long lookupContactIdByLookupKey(SQLiteDatabase db, String lookupKey) {
4857        ContactLookupKey key = new ContactLookupKey();
4858        ArrayList<LookupKeySegment> segments = key.parse(lookupKey);
4859
4860        long contactId = -1;
4861        if (lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_SOURCE_ID)) {
4862            contactId = lookupContactIdBySourceIds(db, segments);
4863            if (contactId != -1) {
4864                return contactId;
4865            }
4866        }
4867
4868        boolean hasRawContactIds =
4869                lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID);
4870        if (hasRawContactIds) {
4871            contactId = lookupContactIdByRawContactIds(db, segments);
4872            if (contactId != -1) {
4873                return contactId;
4874            }
4875        }
4876
4877        if (hasRawContactIds
4878                || lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME)) {
4879            contactId = lookupContactIdByDisplayNames(db, segments);
4880        }
4881
4882        return contactId;
4883    }
4884
4885    private interface LookupBySourceIdQuery {
4886        String TABLE = Tables.RAW_CONTACTS;
4887
4888        String COLUMNS[] = {
4889                RawContacts.CONTACT_ID,
4890                RawContacts.ACCOUNT_TYPE,
4891                RawContacts.ACCOUNT_NAME,
4892                RawContacts.SOURCE_ID
4893        };
4894
4895        int CONTACT_ID = 0;
4896        int ACCOUNT_TYPE = 1;
4897        int ACCOUNT_NAME = 2;
4898        int SOURCE_ID = 3;
4899    }
4900
4901    private long lookupContactIdBySourceIds(SQLiteDatabase db,
4902                ArrayList<LookupKeySegment> segments) {
4903        StringBuilder sb = new StringBuilder();
4904        sb.append(RawContacts.SOURCE_ID + " IN (");
4905        for (int i = 0; i < segments.size(); i++) {
4906            LookupKeySegment segment = segments.get(i);
4907            if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_SOURCE_ID) {
4908                DatabaseUtils.appendEscapedSQLString(sb, segment.key);
4909                sb.append(",");
4910            }
4911        }
4912        sb.setLength(sb.length() - 1);      // Last comma
4913        sb.append(") AND " + RawContacts.CONTACT_ID + " NOT NULL");
4914
4915        Cursor c = db.query(LookupBySourceIdQuery.TABLE, LookupBySourceIdQuery.COLUMNS,
4916                 sb.toString(), null, null, null, null);
4917        try {
4918            while (c.moveToNext()) {
4919                String accountType = c.getString(LookupBySourceIdQuery.ACCOUNT_TYPE);
4920                String accountName = c.getString(LookupBySourceIdQuery.ACCOUNT_NAME);
4921                int accountHashCode =
4922                        ContactLookupKey.getAccountHashCode(accountType, accountName);
4923                String sourceId = c.getString(LookupBySourceIdQuery.SOURCE_ID);
4924                for (int i = 0; i < segments.size(); i++) {
4925                    LookupKeySegment segment = segments.get(i);
4926                    if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_SOURCE_ID
4927                            && accountHashCode == segment.accountHashCode
4928                            && segment.key.equals(sourceId)) {
4929                        segment.contactId = c.getLong(LookupBySourceIdQuery.CONTACT_ID);
4930                        break;
4931                    }
4932                }
4933            }
4934        } finally {
4935            c.close();
4936        }
4937
4938        return getMostReferencedContactId(segments);
4939    }
4940
4941    private interface LookupByRawContactIdQuery {
4942        String TABLE = Tables.RAW_CONTACTS;
4943
4944        String COLUMNS[] = {
4945                RawContacts.CONTACT_ID,
4946                RawContacts.ACCOUNT_TYPE,
4947                RawContacts.ACCOUNT_NAME,
4948                RawContacts._ID,
4949        };
4950
4951        int CONTACT_ID = 0;
4952        int ACCOUNT_TYPE = 1;
4953        int ACCOUNT_NAME = 2;
4954        int ID = 3;
4955    }
4956
4957    private long lookupContactIdByRawContactIds(SQLiteDatabase db,
4958            ArrayList<LookupKeySegment> segments) {
4959        StringBuilder sb = new StringBuilder();
4960        sb.append(RawContacts._ID + " IN (");
4961        for (int i = 0; i < segments.size(); i++) {
4962            LookupKeySegment segment = segments.get(i);
4963            if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) {
4964                sb.append(segment.rawContactId);
4965                sb.append(",");
4966            }
4967        }
4968        sb.setLength(sb.length() - 1);      // Last comma
4969        sb.append(") AND " + RawContacts.CONTACT_ID + " NOT NULL");
4970
4971        Cursor c = db.query(LookupByRawContactIdQuery.TABLE, LookupByRawContactIdQuery.COLUMNS,
4972                 sb.toString(), null, null, null, null);
4973        try {
4974            while (c.moveToNext()) {
4975                String accountType = c.getString(LookupByRawContactIdQuery.ACCOUNT_TYPE);
4976                String accountName = c.getString(LookupByRawContactIdQuery.ACCOUNT_NAME);
4977                int accountHashCode =
4978                        ContactLookupKey.getAccountHashCode(accountType, accountName);
4979                String rawContactId = c.getString(LookupByRawContactIdQuery.ID);
4980                for (int i = 0; i < segments.size(); i++) {
4981                    LookupKeySegment segment = segments.get(i);
4982                    if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID
4983                            && accountHashCode == segment.accountHashCode
4984                            && segment.rawContactId.equals(rawContactId)) {
4985                        segment.contactId = c.getLong(LookupByRawContactIdQuery.CONTACT_ID);
4986                        break;
4987                    }
4988                }
4989            }
4990        } finally {
4991            c.close();
4992        }
4993
4994        return getMostReferencedContactId(segments);
4995    }
4996
4997    private interface LookupByDisplayNameQuery {
4998        String TABLE = Tables.NAME_LOOKUP_JOIN_RAW_CONTACTS;
4999
5000        String COLUMNS[] = {
5001                RawContacts.CONTACT_ID,
5002                RawContacts.ACCOUNT_TYPE,
5003                RawContacts.ACCOUNT_NAME,
5004                NameLookupColumns.NORMALIZED_NAME
5005        };
5006
5007        int CONTACT_ID = 0;
5008        int ACCOUNT_TYPE = 1;
5009        int ACCOUNT_NAME = 2;
5010        int NORMALIZED_NAME = 3;
5011    }
5012
5013    private long lookupContactIdByDisplayNames(SQLiteDatabase db,
5014                ArrayList<LookupKeySegment> segments) {
5015        StringBuilder sb = new StringBuilder();
5016        sb.append(NameLookupColumns.NORMALIZED_NAME + " IN (");
5017        for (int i = 0; i < segments.size(); i++) {
5018            LookupKeySegment segment = segments.get(i);
5019            if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME
5020                    || segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) {
5021                DatabaseUtils.appendEscapedSQLString(sb, segment.key);
5022                sb.append(",");
5023            }
5024        }
5025        sb.setLength(sb.length() - 1);      // Last comma
5026        sb.append(") AND " + NameLookupColumns.NAME_TYPE + "=" + NameLookupType.NAME_COLLATION_KEY
5027                + " AND " + RawContacts.CONTACT_ID + " NOT NULL");
5028
5029        Cursor c = db.query(LookupByDisplayNameQuery.TABLE, LookupByDisplayNameQuery.COLUMNS,
5030                 sb.toString(), null, null, null, null);
5031        try {
5032            while (c.moveToNext()) {
5033                String accountType = c.getString(LookupByDisplayNameQuery.ACCOUNT_TYPE);
5034                String accountName = c.getString(LookupByDisplayNameQuery.ACCOUNT_NAME);
5035                int accountHashCode =
5036                        ContactLookupKey.getAccountHashCode(accountType, accountName);
5037                String name = c.getString(LookupByDisplayNameQuery.NORMALIZED_NAME);
5038                for (int i = 0; i < segments.size(); i++) {
5039                    LookupKeySegment segment = segments.get(i);
5040                    if ((segment.lookupType == ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME
5041                            || segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID)
5042                            && accountHashCode == segment.accountHashCode
5043                            && segment.key.equals(name)) {
5044                        segment.contactId = c.getLong(LookupByDisplayNameQuery.CONTACT_ID);
5045                        break;
5046                    }
5047                }
5048            }
5049        } finally {
5050            c.close();
5051        }
5052
5053        return getMostReferencedContactId(segments);
5054    }
5055
5056    private boolean lookupKeyContainsType(ArrayList<LookupKeySegment> segments, int lookupType) {
5057        for (int i = 0; i < segments.size(); i++) {
5058            LookupKeySegment segment = segments.get(i);
5059            if (segment.lookupType == lookupType) {
5060                return true;
5061            }
5062        }
5063
5064        return false;
5065    }
5066
5067    public void updateLookupKeyForRawContact(SQLiteDatabase db, long rawContactId) {
5068        mContactAggregator.updateLookupKeyForRawContact(db, rawContactId);
5069    }
5070
5071    /**
5072     * Returns the contact ID that is mentioned the highest number of times.
5073     */
5074    private long getMostReferencedContactId(ArrayList<LookupKeySegment> segments) {
5075        Collections.sort(segments);
5076
5077        long bestContactId = -1;
5078        int bestRefCount = 0;
5079
5080        long contactId = -1;
5081        int count = 0;
5082
5083        int segmentCount = segments.size();
5084        for (int i = 0; i < segmentCount; i++) {
5085            LookupKeySegment segment = segments.get(i);
5086            if (segment.contactId != -1) {
5087                if (segment.contactId == contactId) {
5088                    count++;
5089                } else {
5090                    if (count > bestRefCount) {
5091                        bestContactId = contactId;
5092                        bestRefCount = count;
5093                    }
5094                    contactId = segment.contactId;
5095                    count = 1;
5096                }
5097            }
5098        }
5099        if (count > bestRefCount) {
5100            return contactId;
5101        } else {
5102            return bestContactId;
5103        }
5104    }
5105
5106    private void setTablesAndProjectionMapForContacts(SQLiteQueryBuilder qb, Uri uri,
5107            String[] projection) {
5108        StringBuilder sb = new StringBuilder();
5109        appendContactsTables(sb, uri, projection);
5110        qb.setTables(sb.toString());
5111        qb.setProjectionMap(sContactsProjectionMap);
5112    }
5113
5114    /**
5115     * Finds name lookup records matching the supplied filter, picks one arbitrary match per
5116     * contact and joins that with other contacts tables.
5117     */
5118    private void setTablesAndProjectionMapForContactsWithSnippet(SQLiteQueryBuilder qb, Uri uri,
5119            String[] projection, String filter) {
5120
5121        StringBuilder sb = new StringBuilder();
5122        appendContactsTables(sb, uri, projection);
5123
5124        sb.append(" JOIN (SELECT " +
5125                RawContacts.CONTACT_ID + " AS snippet_contact_id");
5126
5127        if (mDbHelper.isInProjection(projection, SearchSnippetColumns.SNIPPET_DATA_ID)) {
5128            sb.append(", " + DataColumns.CONCRETE_ID + " AS "
5129                    + SearchSnippetColumns.SNIPPET_DATA_ID);
5130        }
5131
5132        if (mDbHelper.isInProjection(projection, SearchSnippetColumns.SNIPPET_DATA1)) {
5133            sb.append(", " + Data.DATA1 + " AS " + SearchSnippetColumns.SNIPPET_DATA1);
5134        }
5135
5136        if (mDbHelper.isInProjection(projection, SearchSnippetColumns.SNIPPET_DATA2)) {
5137            sb.append(", " + Data.DATA2 + " AS " + SearchSnippetColumns.SNIPPET_DATA2);
5138        }
5139
5140        if (mDbHelper.isInProjection(projection, SearchSnippetColumns.SNIPPET_DATA3)) {
5141            sb.append(", " + Data.DATA3 + " AS " + SearchSnippetColumns.SNIPPET_DATA3);
5142        }
5143
5144        if (mDbHelper.isInProjection(projection, SearchSnippetColumns.SNIPPET_DATA4)) {
5145            sb.append(", " + Data.DATA4 + " AS " + SearchSnippetColumns.SNIPPET_DATA4);
5146        }
5147
5148        if (mDbHelper.isInProjection(projection, SearchSnippetColumns.SNIPPET_MIMETYPE)) {
5149            sb.append(", (" +
5150                    "SELECT " + MimetypesColumns.MIMETYPE +
5151                    " FROM " + Tables.MIMETYPES +
5152                    " WHERE " + MimetypesColumns._ID + "=" + DataColumns.MIMETYPE_ID +
5153                    ") AS " + SearchSnippetColumns.SNIPPET_MIMETYPE);
5154        }
5155
5156        sb.append(" FROM " + Tables.DATA_JOIN_RAW_CONTACTS +
5157                " WHERE " + DataColumns.CONCRETE_ID +
5158                " IN (");
5159
5160        // Construct a query that gives us exactly one data _id per matching contact.
5161        // MIN stands in for ANY in this context.
5162        sb.append(
5163                "SELECT MIN(" + Tables.NAME_LOOKUP + "." + NameLookupColumns.DATA_ID + ")" +
5164                " FROM " + Tables.NAME_LOOKUP +
5165                " JOIN " + Tables.RAW_CONTACTS +
5166                " ON (" + RawContactsColumns.CONCRETE_ID
5167                        + "=" + Tables.NAME_LOOKUP + "." + NameLookupColumns.RAW_CONTACT_ID + ")" +
5168                " WHERE " + NameLookupColumns.NORMALIZED_NAME + " GLOB '");
5169        sb.append(NameNormalizer.normalize(filter));
5170        sb.append("*' AND " + NameLookupColumns.NAME_TYPE +
5171                    " IN(" + CONTACT_LOOKUP_NAME_TYPES + ")" +
5172                " GROUP BY " + RawContactsColumns.CONCRETE_CONTACT_ID);
5173
5174        sb.append(")) ON (" + Contacts._ID + "=snippet_contact_id)");
5175
5176        qb.setTables(sb.toString());
5177        qb.setProjectionMap(sContactsProjectionWithSnippetMap);
5178    }
5179
5180    private void appendContactsTables(StringBuilder sb, Uri uri, String[] projection) {
5181        boolean excludeRestrictedData = false;
5182        String requestingPackage = getQueryParameter(uri,
5183                ContactsContract.REQUESTING_PACKAGE_PARAM_KEY);
5184        if (requestingPackage != null) {
5185            excludeRestrictedData = !mDbHelper.hasAccessToRestrictedData(requestingPackage);
5186        }
5187        sb.append(mDbHelper.getContactView(excludeRestrictedData));
5188        if (mDbHelper.isInProjection(projection,
5189                Contacts.CONTACT_PRESENCE)) {
5190            sb.append(" LEFT OUTER JOIN " + Tables.AGGREGATED_PRESENCE +
5191                    " ON (" + Contacts._ID + " = " + AggregatedPresenceColumns.CONTACT_ID + ")");
5192        }
5193        if (mDbHelper.isInProjection(projection,
5194                Contacts.CONTACT_STATUS,
5195                Contacts.CONTACT_STATUS_RES_PACKAGE,
5196                Contacts.CONTACT_STATUS_ICON,
5197                Contacts.CONTACT_STATUS_LABEL,
5198                Contacts.CONTACT_STATUS_TIMESTAMP)) {
5199            sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES + " "
5200                    + ContactsStatusUpdatesColumns.ALIAS +
5201                    " ON (" + ContactsColumns.LAST_STATUS_UPDATE_ID + "="
5202                            + ContactsStatusUpdatesColumns.CONCRETE_DATA_ID + ")");
5203        }
5204    }
5205
5206    private void setTablesAndProjectionMapForRawContacts(SQLiteQueryBuilder qb, Uri uri) {
5207        StringBuilder sb = new StringBuilder();
5208        boolean excludeRestrictedData = false;
5209        String requestingPackage = getQueryParameter(uri,
5210                ContactsContract.REQUESTING_PACKAGE_PARAM_KEY);
5211        if (requestingPackage != null) {
5212            excludeRestrictedData = !mDbHelper.hasAccessToRestrictedData(requestingPackage);
5213        }
5214        sb.append(mDbHelper.getRawContactView(excludeRestrictedData));
5215        qb.setTables(sb.toString());
5216        qb.setProjectionMap(sRawContactsProjectionMap);
5217        appendAccountFromParameter(qb, uri);
5218    }
5219
5220    private void setTablesAndProjectionMapForRawContactsEntities(SQLiteQueryBuilder qb, Uri uri) {
5221        // Note: currently, "export only" equals to "restricted", but may not in the future.
5222        boolean excludeRestrictedData = readBooleanQueryParameter(uri,
5223                Data.FOR_EXPORT_ONLY, false);
5224
5225        String requestingPackage = getQueryParameter(uri,
5226                ContactsContract.REQUESTING_PACKAGE_PARAM_KEY);
5227        if (requestingPackage != null) {
5228            excludeRestrictedData = excludeRestrictedData
5229                    || !mDbHelper.hasAccessToRestrictedData(requestingPackage);
5230        }
5231        qb.setTables(mDbHelper.getContactEntitiesView(excludeRestrictedData));
5232        qb.setProjectionMap(sRawContactsEntityProjectionMap);
5233        appendAccountFromParameter(qb, uri);
5234    }
5235
5236    private void setTablesAndProjectionMapForData(SQLiteQueryBuilder qb, Uri uri,
5237            String[] projection, boolean distinct) {
5238        StringBuilder sb = new StringBuilder();
5239        // Note: currently, "export only" equals to "restricted", but may not in the future.
5240        boolean excludeRestrictedData = readBooleanQueryParameter(uri,
5241                Data.FOR_EXPORT_ONLY, false);
5242
5243        String requestingPackage = getQueryParameter(uri,
5244                ContactsContract.REQUESTING_PACKAGE_PARAM_KEY);
5245        if (requestingPackage != null) {
5246            excludeRestrictedData = excludeRestrictedData
5247                    || !mDbHelper.hasAccessToRestrictedData(requestingPackage);
5248        }
5249
5250        sb.append(mDbHelper.getDataView(excludeRestrictedData));
5251        sb.append(" data");
5252
5253        // Include aggregated presence when requested
5254        if (mDbHelper.isInProjection(projection, Data.CONTACT_PRESENCE)) {
5255            sb.append(" LEFT OUTER JOIN " + Tables.AGGREGATED_PRESENCE +
5256                    " ON (" + AggregatedPresenceColumns.CONCRETE_CONTACT_ID + "="
5257                    + RawContacts.CONTACT_ID + ")");
5258        }
5259
5260        // Include aggregated status updates when requested
5261        if (mDbHelper.isInProjection(projection,
5262                Data.CONTACT_STATUS,
5263                Data.CONTACT_STATUS_RES_PACKAGE,
5264                Data.CONTACT_STATUS_ICON,
5265                Data.CONTACT_STATUS_LABEL,
5266                Data.CONTACT_STATUS_TIMESTAMP)) {
5267            sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES + " "
5268                    + ContactsStatusUpdatesColumns.ALIAS +
5269                    " ON (" + ContactsColumns.LAST_STATUS_UPDATE_ID + "="
5270                            + ContactsStatusUpdatesColumns.CONCRETE_DATA_ID + ")");
5271        }
5272
5273        // Include individual presence when requested
5274        if (mDbHelper.isInProjection(projection, Data.PRESENCE)) {
5275            sb.append(" LEFT OUTER JOIN " + Tables.PRESENCE +
5276                    " ON (" + StatusUpdates.DATA_ID + "="
5277                    + DataColumns.CONCRETE_ID + ")");
5278        }
5279
5280        // Include individual status updates when requested
5281        if (mDbHelper.isInProjection(projection,
5282                Data.STATUS,
5283                Data.STATUS_RES_PACKAGE,
5284                Data.STATUS_ICON,
5285                Data.STATUS_LABEL,
5286                Data.STATUS_TIMESTAMP)) {
5287            sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES +
5288                    " ON (" + StatusUpdatesColumns.CONCRETE_DATA_ID + "="
5289                            + DataColumns.CONCRETE_ID + ")");
5290        }
5291
5292        qb.setTables(sb.toString());
5293        qb.setProjectionMap(distinct ? sDistinctDataProjectionMap : sDataProjectionMap);
5294        appendAccountFromParameter(qb, uri);
5295    }
5296
5297    private void setTableAndProjectionMapForStatusUpdates(SQLiteQueryBuilder qb,
5298            String[] projection) {
5299        StringBuilder sb = new StringBuilder();
5300        sb.append(mDbHelper.getDataView());
5301        sb.append(" data");
5302
5303        if (mDbHelper.isInProjection(projection, StatusUpdates.PRESENCE)) {
5304            sb.append(" LEFT OUTER JOIN " + Tables.PRESENCE +
5305                    " ON(" + Tables.PRESENCE + "." + StatusUpdates.DATA_ID
5306                    + "=" + DataColumns.CONCRETE_ID + ")");
5307        }
5308
5309        if (mDbHelper.isInProjection(projection,
5310                StatusUpdates.STATUS,
5311                StatusUpdates.STATUS_RES_PACKAGE,
5312                StatusUpdates.STATUS_ICON,
5313                StatusUpdates.STATUS_LABEL,
5314                StatusUpdates.STATUS_TIMESTAMP)) {
5315            sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES +
5316                    " ON(" + Tables.STATUS_UPDATES + "." + StatusUpdatesColumns.DATA_ID
5317                    + "=" + DataColumns.CONCRETE_ID + ")");
5318        }
5319        qb.setTables(sb.toString());
5320        qb.setProjectionMap(sStatusUpdatesProjectionMap);
5321    }
5322
5323    private void appendAccountFromParameter(SQLiteQueryBuilder qb, Uri uri) {
5324        final String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME);
5325        final String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE);
5326
5327        final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType);
5328        if (partialUri) {
5329            // Throw when either account is incomplete
5330            throw new IllegalArgumentException(mDbHelper.exceptionMessage(
5331                    "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri));
5332        }
5333
5334        // Accounts are valid by only checking one parameter, since we've
5335        // already ruled out partial accounts.
5336        final boolean validAccount = !TextUtils.isEmpty(accountName);
5337        if (validAccount) {
5338            qb.appendWhere(RawContacts.ACCOUNT_NAME + "="
5339                    + DatabaseUtils.sqlEscapeString(accountName) + " AND "
5340                    + RawContacts.ACCOUNT_TYPE + "="
5341                    + DatabaseUtils.sqlEscapeString(accountType));
5342        } else {
5343            qb.appendWhere("1");
5344        }
5345    }
5346
5347    private String appendAccountToSelection(Uri uri, String selection) {
5348        final String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME);
5349        final String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE);
5350
5351        final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType);
5352        if (partialUri) {
5353            // Throw when either account is incomplete
5354            throw new IllegalArgumentException(mDbHelper.exceptionMessage(
5355                    "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri));
5356        }
5357
5358        // Accounts are valid by only checking one parameter, since we've
5359        // already ruled out partial accounts.
5360        final boolean validAccount = !TextUtils.isEmpty(accountName);
5361        if (validAccount) {
5362            StringBuilder selectionSb = new StringBuilder(RawContacts.ACCOUNT_NAME + "="
5363                    + DatabaseUtils.sqlEscapeString(accountName) + " AND "
5364                    + RawContacts.ACCOUNT_TYPE + "="
5365                    + DatabaseUtils.sqlEscapeString(accountType));
5366            if (!TextUtils.isEmpty(selection)) {
5367                selectionSb.append(" AND (");
5368                selectionSb.append(selection);
5369                selectionSb.append(')');
5370            }
5371            return selectionSb.toString();
5372        } else {
5373            return selection;
5374        }
5375    }
5376
5377    /**
5378     * Gets the value of the "limit" URI query parameter.
5379     *
5380     * @return A string containing a non-negative integer, or <code>null</code> if
5381     *         the parameter is not set, or is set to an invalid value.
5382     */
5383    private String getLimit(Uri uri) {
5384        String limitParam = getQueryParameter(uri, "limit");
5385        if (limitParam == null) {
5386            return null;
5387        }
5388        // make sure that the limit is a non-negative integer
5389        try {
5390            int l = Integer.parseInt(limitParam);
5391            if (l < 0) {
5392                Log.w(TAG, "Invalid limit parameter: " + limitParam);
5393                return null;
5394            }
5395            return String.valueOf(l);
5396        } catch (NumberFormatException ex) {
5397            Log.w(TAG, "Invalid limit parameter: " + limitParam);
5398            return null;
5399        }
5400    }
5401
5402    /**
5403     * Returns true if all the characters are meaningful as digits
5404     * in a phone number -- letters, digits, and a few punctuation marks.
5405     */
5406    private boolean isPhoneNumber(CharSequence cons) {
5407        int len = cons.length();
5408
5409        for (int i = 0; i < len; i++) {
5410            char c = cons.charAt(i);
5411
5412            if ((c >= '0') && (c <= '9')) {
5413                continue;
5414            }
5415            if ((c == ' ') || (c == '-') || (c == '(') || (c == ')') || (c == '.') || (c == '+')
5416                    || (c == '#') || (c == '*')) {
5417                continue;
5418            }
5419            if ((c >= 'A') && (c <= 'Z')) {
5420                continue;
5421            }
5422            if ((c >= 'a') && (c <= 'z')) {
5423                continue;
5424            }
5425
5426            return false;
5427        }
5428
5429        return true;
5430    }
5431
5432    String getContactsRestrictions() {
5433        if (mDbHelper.hasAccessToRestrictedData()) {
5434            return "1";
5435        } else {
5436            return RawContactsColumns.CONCRETE_IS_RESTRICTED + "=0";
5437        }
5438    }
5439
5440    public String getContactsRestrictionExceptionAsNestedQuery(String contactIdColumn) {
5441        if (mDbHelper.hasAccessToRestrictedData()) {
5442            return "1";
5443        } else {
5444            return "(SELECT " + RawContacts.IS_RESTRICTED + " FROM " + Tables.RAW_CONTACTS
5445                    + " WHERE " + RawContactsColumns.CONCRETE_ID + "=" + contactIdColumn + ")=0";
5446        }
5447    }
5448
5449    @Override
5450    public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
5451        int match = sUriMatcher.match(uri);
5452        switch (match) {
5453            case CONTACTS_PHOTO: {
5454                return openPhotoAssetFile(uri, mode,
5455                        Data._ID + "=" + Contacts.PHOTO_ID + " AND " + RawContacts.CONTACT_ID + "=?",
5456                        new String[]{uri.getPathSegments().get(1)});
5457            }
5458
5459            case DATA_ID: {
5460                return openPhotoAssetFile(uri, mode,
5461                        Data._ID + "=? AND " + Data.MIMETYPE + "='" + Photo.CONTENT_ITEM_TYPE + "'",
5462                        new String[]{uri.getPathSegments().get(1)});
5463            }
5464
5465            case CONTACTS_AS_VCARD: {
5466                final String lookupKey = Uri.encode(uri.getPathSegments().get(2));
5467                mSelectionArgs1[0] = String.valueOf(lookupContactIdByLookupKey(mDb, lookupKey));
5468                final String selection = Contacts._ID + "=?";
5469
5470                // When opening a contact as file, we pass back contents as a
5471                // vCard-encoded stream. We build into a local buffer first,
5472                // then pipe into MemoryFile once the exact size is known.
5473                final ByteArrayOutputStream localStream = new ByteArrayOutputStream();
5474                outputRawContactsAsVCard(localStream, selection, mSelectionArgs1);
5475                return buildAssetFileDescriptor(localStream);
5476            }
5477
5478            case CONTACTS_AS_MULTI_VCARD: {
5479                final String lookupKeys = uri.getPathSegments().get(2);
5480                final String[] loopupKeyList = lookupKeys.split(":");
5481                final StringBuilder inBuilder = new StringBuilder();
5482                int index = 0;
5483                // SQLite has limits on how many parameters can be used
5484                // so the IDs are concatenated to a query string here instead
5485                for (String lookupKey : loopupKeyList) {
5486                    if (index == 0) {
5487                        inBuilder.append("(");
5488                    } else {
5489                        inBuilder.append(",");
5490                    }
5491                    inBuilder.append(lookupContactIdByLookupKey(mDb, lookupKey));
5492                    index++;
5493                }
5494                inBuilder.append(')');
5495                final String selection = Contacts._ID + " IN " + inBuilder.toString();
5496
5497                // When opening a contact as file, we pass back contents as a
5498                // vCard-encoded stream. We build into a local buffer first,
5499                // then pipe into MemoryFile once the exact size is known.
5500                final ByteArrayOutputStream localStream = new ByteArrayOutputStream();
5501                outputRawContactsAsVCard(localStream, selection, null);
5502                return buildAssetFileDescriptor(localStream);
5503            }
5504
5505            default:
5506                throw new FileNotFoundException(mDbHelper.exceptionMessage("File does not exist",
5507                        uri));
5508        }
5509    }
5510
5511    private AssetFileDescriptor openPhotoAssetFile(Uri uri, String mode, String selection,
5512            String[] selectionArgs)
5513            throws FileNotFoundException {
5514        if (!"r".equals(mode)) {
5515            throw new FileNotFoundException(mDbHelper.exceptionMessage("Mode " + mode
5516                    + " not supported.", uri));
5517        }
5518
5519        String sql =
5520                "SELECT " + Photo.PHOTO + " FROM " + mDbHelper.getDataView() +
5521                " WHERE " + selection;
5522        SQLiteDatabase db = mDbHelper.getReadableDatabase();
5523        return SQLiteContentHelper.getBlobColumnAsAssetFile(db, sql,
5524                selectionArgs);
5525    }
5526
5527    private static final String CONTACT_MEMORY_FILE_NAME = "contactAssetFile";
5528
5529    /**
5530     * Build a {@link AssetFileDescriptor} through a {@link MemoryFile} with the
5531     * contents of the given {@link ByteArrayOutputStream}.
5532     */
5533    private AssetFileDescriptor buildAssetFileDescriptor(ByteArrayOutputStream stream) {
5534        AssetFileDescriptor fd = null;
5535        try {
5536            stream.flush();
5537
5538            final byte[] byteData = stream.toByteArray();
5539            final int size = byteData.length;
5540
5541            final MemoryFile memoryFile = new MemoryFile(CONTACT_MEMORY_FILE_NAME, size);
5542            memoryFile.writeBytes(byteData, 0, 0, size);
5543            memoryFile.deactivate();
5544
5545            fd = AssetFileDescriptor.fromMemoryFile(memoryFile);
5546        } catch (IOException e) {
5547            Log.w(TAG, "Problem writing stream into an AssetFileDescriptor: " + e.toString());
5548        }
5549        return fd;
5550    }
5551
5552    /**
5553     * Output {@link RawContacts} matching the requested selection in the vCard
5554     * format to the given {@link OutputStream}. This method returns silently if
5555     * any errors encountered.
5556     */
5557    private void outputRawContactsAsVCard(OutputStream stream, String selection,
5558            String[] selectionArgs) {
5559        final Context context = this.getContext();
5560        final VCardComposer composer =
5561                new VCardComposer(context, VCardConfig.VCARD_TYPE_DEFAULT, false);
5562        composer.addHandler(composer.new HandlerForOutputStream(stream));
5563
5564        // No extra checks since composer always uses restricted views
5565        if (!composer.init(selection, selectionArgs)) {
5566            Log.w(TAG, "Failed to init VCardComposer");
5567            return;
5568        }
5569
5570        while (!composer.isAfterLast()) {
5571            if (!composer.createOneEntry()) {
5572                Log.w(TAG, "Failed to output a contact.");
5573            }
5574        }
5575        composer.terminate();
5576    }
5577
5578    @Override
5579    public String getType(Uri uri) {
5580        final int match = sUriMatcher.match(uri);
5581        switch (match) {
5582            case CONTACTS:
5583                return Contacts.CONTENT_TYPE;
5584            case CONTACTS_LOOKUP:
5585            case CONTACTS_ID:
5586            case CONTACTS_LOOKUP_ID:
5587                return Contacts.CONTENT_ITEM_TYPE;
5588            case CONTACTS_AS_VCARD:
5589            case CONTACTS_AS_MULTI_VCARD:
5590                return Contacts.CONTENT_VCARD_TYPE;
5591            case RAW_CONTACTS:
5592                return RawContacts.CONTENT_TYPE;
5593            case RAW_CONTACTS_ID:
5594                return RawContacts.CONTENT_ITEM_TYPE;
5595            case DATA_ID:
5596                return mDbHelper.getDataMimeType(ContentUris.parseId(uri));
5597            case PHONES:
5598                return Phone.CONTENT_TYPE;
5599            case PHONES_ID:
5600                return Phone.CONTENT_ITEM_TYPE;
5601            case PHONE_LOOKUP:
5602                return PhoneLookup.CONTENT_TYPE;
5603            case EMAILS:
5604                return Email.CONTENT_TYPE;
5605            case EMAILS_ID:
5606                return Email.CONTENT_ITEM_TYPE;
5607            case POSTALS:
5608                return StructuredPostal.CONTENT_TYPE;
5609            case POSTALS_ID:
5610                return StructuredPostal.CONTENT_ITEM_TYPE;
5611            case AGGREGATION_EXCEPTIONS:
5612                return AggregationExceptions.CONTENT_TYPE;
5613            case AGGREGATION_EXCEPTION_ID:
5614                return AggregationExceptions.CONTENT_ITEM_TYPE;
5615            case SETTINGS:
5616                return Settings.CONTENT_TYPE;
5617            case AGGREGATION_SUGGESTIONS:
5618                return Contacts.CONTENT_TYPE;
5619            case SEARCH_SUGGESTIONS:
5620                return SearchManager.SUGGEST_MIME_TYPE;
5621            case SEARCH_SHORTCUT:
5622                return SearchManager.SHORTCUT_MIME_TYPE;
5623
5624            default:
5625                return mLegacyApiSupport.getType(uri);
5626        }
5627    }
5628
5629    private void setDisplayName(long rawContactId, int displayNameSource,
5630            String displayNamePrimary, String displayNameAlternative, String phoneticName,
5631            int phoneticNameStyle, String sortKeyPrimary, String sortKeyAlternative) {
5632        mRawContactDisplayNameUpdate.bindLong(1, displayNameSource);
5633        bindString(mRawContactDisplayNameUpdate, 2, displayNamePrimary);
5634        bindString(mRawContactDisplayNameUpdate, 3, displayNameAlternative);
5635        bindString(mRawContactDisplayNameUpdate, 4, phoneticName);
5636        mRawContactDisplayNameUpdate.bindLong(5, phoneticNameStyle);
5637        bindString(mRawContactDisplayNameUpdate, 6, sortKeyPrimary);
5638        bindString(mRawContactDisplayNameUpdate, 7, sortKeyAlternative);
5639        mRawContactDisplayNameUpdate.bindLong(8, rawContactId);
5640        mRawContactDisplayNameUpdate.execute();
5641    }
5642
5643    /**
5644     * Sets the {@link RawContacts#DIRTY} for the specified raw contact.
5645     */
5646    private void setRawContactDirty(long rawContactId) {
5647        mDirtyRawContacts.add(rawContactId);
5648    }
5649
5650    /*
5651     * Sets the given dataId record in the "data" table to primary, and resets all data records of
5652     * the same mimetype and under the same contact to not be primary.
5653     *
5654     * @param dataId the id of the data record to be set to primary.
5655     */
5656    private void setIsPrimary(long rawContactId, long dataId, long mimeTypeId) {
5657        mSetPrimaryStatement.bindLong(1, dataId);
5658        mSetPrimaryStatement.bindLong(2, mimeTypeId);
5659        mSetPrimaryStatement.bindLong(3, rawContactId);
5660        mSetPrimaryStatement.execute();
5661    }
5662
5663    /*
5664     * Sets the given dataId record in the "data" table to "super primary", and resets all data
5665     * records of the same mimetype and under the same aggregate to not be "super primary".
5666     *
5667     * @param dataId the id of the data record to be set to primary.
5668     */
5669    private void setIsSuperPrimary(long rawContactId, long dataId, long mimeTypeId) {
5670        mSetSuperPrimaryStatement.bindLong(1, dataId);
5671        mSetSuperPrimaryStatement.bindLong(2, mimeTypeId);
5672        mSetSuperPrimaryStatement.bindLong(3, rawContactId);
5673        mSetSuperPrimaryStatement.execute();
5674    }
5675
5676    public String insertNameLookupForEmail(long rawContactId, long dataId, String email) {
5677        if (TextUtils.isEmpty(email)) {
5678            return null;
5679        }
5680
5681        String address = mDbHelper.extractHandleFromEmailAddress(email);
5682        if (address == null) {
5683            return null;
5684        }
5685
5686        insertNameLookup(rawContactId, dataId,
5687                NameLookupType.EMAIL_BASED_NICKNAME, NameNormalizer.normalize(address));
5688        return address;
5689    }
5690
5691    /**
5692     * Normalizes the nickname and inserts it in the name lookup table.
5693     */
5694    public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) {
5695        if (TextUtils.isEmpty(nickname)) {
5696            return;
5697        }
5698
5699        insertNameLookup(rawContactId, dataId,
5700                NameLookupType.NICKNAME, NameNormalizer.normalize(nickname));
5701    }
5702
5703    public void insertNameLookupForOrganization(long rawContactId, long dataId, String company,
5704            String title) {
5705        if (!TextUtils.isEmpty(company)) {
5706            insertNameLookup(rawContactId, dataId,
5707                    NameLookupType.ORGANIZATION, NameNormalizer.normalize(company));
5708        }
5709        if (!TextUtils.isEmpty(title)) {
5710            insertNameLookup(rawContactId, dataId,
5711                    NameLookupType.ORGANIZATION, NameNormalizer.normalize(title));
5712        }
5713    }
5714
5715    public void insertNameLookupForStructuredName(long rawContactId, long dataId, String name,
5716            int fullNameStyle) {
5717        mNameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle);
5718    }
5719
5720    private class StructuredNameLookupBuilder extends NameLookupBuilder {
5721
5722        public StructuredNameLookupBuilder(NameSplitter splitter) {
5723            super(splitter);
5724        }
5725
5726        @Override
5727        protected void insertNameLookup(long rawContactId, long dataId, int lookupType,
5728                String name) {
5729            ContactsProvider2.this.insertNameLookup(rawContactId, dataId, lookupType, name);
5730        }
5731
5732        @Override
5733        protected String[] getCommonNicknameClusters(String normalizedName) {
5734            return mCommonNicknameCache.getCommonNicknameClusters(normalizedName);
5735        }
5736    }
5737
5738    public void insertNameLookupForPhoneticName(long rawContactId, long dataId,
5739            ContentValues values) {
5740        if (values.containsKey(StructuredName.PHONETIC_FAMILY_NAME)
5741                || values.containsKey(StructuredName.PHONETIC_GIVEN_NAME)
5742                || values.containsKey(StructuredName.PHONETIC_MIDDLE_NAME)) {
5743            insertNameLookupForPhoneticName(rawContactId, dataId,
5744                    values.getAsString(StructuredName.PHONETIC_FAMILY_NAME),
5745                    values.getAsString(StructuredName.PHONETIC_MIDDLE_NAME),
5746                    values.getAsString(StructuredName.PHONETIC_GIVEN_NAME));
5747        }
5748    }
5749
5750    public void insertNameLookupForPhoneticName(long rawContactId, long dataId, String familyName,
5751            String middleName, String givenName) {
5752        mSb.setLength(0);
5753        if (familyName != null) {
5754            mSb.append(familyName.trim());
5755        }
5756        if (middleName != null) {
5757            mSb.append(middleName.trim());
5758        }
5759        if (givenName != null) {
5760            mSb.append(givenName.trim());
5761        }
5762
5763        if (mSb.length() > 0) {
5764            insertNameLookup(rawContactId, dataId, NameLookupType.NAME_COLLATION_KEY,
5765                    NameNormalizer.normalize(mSb.toString()));
5766        }
5767
5768        if (givenName != null) {
5769            // We want the phonetic given name to be used for search, but not for aggregation,
5770            // which is why we are using NAME_SHORTHAND rather than NAME_COLLATION_KEY
5771            insertNameLookup(rawContactId, dataId, NameLookupType.NAME_SHORTHAND,
5772                    NameNormalizer.normalize(givenName.trim()));
5773        }
5774    }
5775
5776    /**
5777     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
5778     */
5779    public void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) {
5780        mNameLookupInsert.bindLong(1, rawContactId);
5781        mNameLookupInsert.bindLong(2, dataId);
5782        mNameLookupInsert.bindLong(3, lookupType);
5783        bindString(mNameLookupInsert, 4, name);
5784        mNameLookupInsert.executeInsert();
5785    }
5786
5787    /**
5788     * Deletes all {@link Tables#NAME_LOOKUP} table rows associated with the specified data element.
5789     */
5790    public void deleteNameLookup(long dataId) {
5791        mNameLookupDelete.bindLong(1, dataId);
5792        mNameLookupDelete.execute();
5793    }
5794
5795    public void appendContactFilterAsNestedQuery(StringBuilder sb, String filterParam) {
5796        sb.append("(" +
5797                "SELECT DISTINCT " + RawContacts.CONTACT_ID +
5798                " FROM " + Tables.RAW_CONTACTS +
5799                " JOIN " + Tables.NAME_LOOKUP +
5800                " ON(" + RawContactsColumns.CONCRETE_ID + "="
5801                        + NameLookupColumns.RAW_CONTACT_ID + ")" +
5802                " WHERE normalized_name GLOB '");
5803        sb.append(NameNormalizer.normalize(filterParam));
5804        sb.append("*' AND " + NameLookupColumns.NAME_TYPE +
5805                    " IN(" + CONTACT_LOOKUP_NAME_TYPES + "))");
5806    }
5807
5808    public String getRawContactsByFilterAsNestedQuery(String filterParam) {
5809        StringBuilder sb = new StringBuilder();
5810        appendRawContactsByFilterAsNestedQuery(sb, filterParam);
5811        return sb.toString();
5812    }
5813
5814    public void appendRawContactsByFilterAsNestedQuery(StringBuilder sb, String filterParam) {
5815        appendRawContactsByNormalizedNameFilter(sb, NameNormalizer.normalize(filterParam), true);
5816    }
5817
5818    private void appendRawContactsByNormalizedNameFilter(StringBuilder sb, String normalizedName,
5819            boolean allowEmailMatch) {
5820        sb.append("(" +
5821                "SELECT " + NameLookupColumns.RAW_CONTACT_ID +
5822                " FROM " + Tables.NAME_LOOKUP +
5823                " WHERE " + NameLookupColumns.NORMALIZED_NAME +
5824                " GLOB '");
5825        sb.append(normalizedName);
5826        sb.append("*' AND " + NameLookupColumns.NAME_TYPE + " IN ("
5827                + NameLookupType.NAME_COLLATION_KEY + ","
5828                + NameLookupType.NICKNAME + ","
5829                + NameLookupType.NAME_SHORTHAND + ","
5830                + NameLookupType.ORGANIZATION + ","
5831                + NameLookupType.NAME_CONSONANTS);
5832        if (allowEmailMatch) {
5833            sb.append("," + NameLookupType.EMAIL_BASED_NICKNAME);
5834        }
5835        sb.append("))");
5836    }
5837
5838    /**
5839     * Inserts an argument at the beginning of the selection arg list.
5840     */
5841    private String[] insertSelectionArg(String[] selectionArgs, String arg) {
5842        if (selectionArgs == null) {
5843            return new String[] {arg};
5844        } else {
5845            int newLength = selectionArgs.length + 1;
5846            String[] newSelectionArgs = new String[newLength];
5847            newSelectionArgs[0] = arg;
5848            System.arraycopy(selectionArgs, 0, newSelectionArgs, 1, selectionArgs.length);
5849            return newSelectionArgs;
5850        }
5851    }
5852
5853    private String[] appendProjectionArg(String[] projection, String arg) {
5854        if (projection == null) {
5855            return null;
5856        }
5857        final int length = projection.length;
5858        String[] newProjection = new String[length + 1];
5859        System.arraycopy(projection, 0, newProjection, 0, length);
5860        newProjection[length] = arg;
5861        return newProjection;
5862    }
5863
5864    protected Account getDefaultAccount() {
5865        AccountManager accountManager = AccountManager.get(getContext());
5866        try {
5867            Account[] accounts = accountManager.getAccountsByTypeAndFeatures(DEFAULT_ACCOUNT_TYPE,
5868                    new String[] {FEATURE_LEGACY_HOSTED_OR_GOOGLE}, null, null).getResult();
5869            if (accounts != null && accounts.length > 0) {
5870                return accounts[0];
5871            }
5872        } catch (Throwable e) {
5873            Log.e(TAG, "Cannot determine the default account for contacts compatibility", e);
5874        }
5875        return null;
5876    }
5877
5878    /**
5879     * Returns true if the specified account type is writable.
5880     */
5881    protected boolean isWritableAccount(String accountType) {
5882        if (accountType == null) {
5883            return true;
5884        }
5885
5886        Boolean writable = mAccountWritability.get(accountType);
5887        if (writable != null) {
5888            return writable;
5889        }
5890
5891        IContentService contentService = ContentResolver.getContentService();
5892        try {
5893            for (SyncAdapterType sync : contentService.getSyncAdapterTypes()) {
5894                if (ContactsContract.AUTHORITY.equals(sync.authority) &&
5895                        accountType.equals(sync.accountType)) {
5896                    writable = sync.supportsUploading();
5897                    break;
5898                }
5899            }
5900        } catch (RemoteException e) {
5901            Log.e(TAG, "Could not acquire sync adapter types");
5902        }
5903
5904        if (writable == null) {
5905            writable = false;
5906        }
5907
5908        mAccountWritability.put(accountType, writable);
5909        return writable;
5910    }
5911
5912    /* package */ static boolean readBooleanQueryParameter(Uri uri, String parameter,
5913            boolean defaultValue) {
5914
5915        // Manually parse the query, which is much faster than calling uri.getQueryParameter
5916        String query = uri.getEncodedQuery();
5917        if (query == null) {
5918            return defaultValue;
5919        }
5920
5921        int index = query.indexOf(parameter);
5922        if (index == -1) {
5923            return defaultValue;
5924        }
5925
5926        index += parameter.length();
5927
5928        return !matchQueryParameter(query, index, "=0", false)
5929                && !matchQueryParameter(query, index, "=false", true);
5930    }
5931
5932    private static boolean matchQueryParameter(String query, int index, String value,
5933            boolean ignoreCase) {
5934        int length = value.length();
5935        return query.regionMatches(ignoreCase, index, value, 0, length)
5936                && (query.length() == index + length || query.charAt(index + length) == '&');
5937    }
5938
5939    /**
5940     * A fast re-implementation of {@link Uri#getQueryParameter}
5941     */
5942    /* package */ static String getQueryParameter(Uri uri, String parameter) {
5943        String query = uri.getEncodedQuery();
5944        if (query == null) {
5945            return null;
5946        }
5947
5948        int queryLength = query.length();
5949        int parameterLength = parameter.length();
5950
5951        String value;
5952        int index = 0;
5953        while (true) {
5954            index = query.indexOf(parameter, index);
5955            if (index == -1) {
5956                return null;
5957            }
5958
5959            index += parameterLength;
5960
5961            if (queryLength == index) {
5962                return null;
5963            }
5964
5965            if (query.charAt(index) == '=') {
5966                index++;
5967                break;
5968            }
5969        }
5970
5971        int ampIndex = query.indexOf('&', index);
5972        if (ampIndex == -1) {
5973            value = query.substring(index);
5974        } else {
5975            value = query.substring(index, ampIndex);
5976        }
5977
5978        return Uri.decode(value);
5979    }
5980
5981    private void bindString(SQLiteStatement stmt, int index, String value) {
5982        if (value == null) {
5983            stmt.bindNull(index);
5984        } else {
5985            stmt.bindString(index, value);
5986        }
5987    }
5988
5989    private void bindLong(SQLiteStatement stmt, int index, Number value) {
5990        if (value == null) {
5991            stmt.bindNull(index);
5992        } else {
5993            stmt.bindLong(index, value.longValue());
5994        }
5995    }
5996}
5997