ContactsDatabaseHelper.java revision 155accbcb95fc13b984cf0ea8e5498a9c619cbf5
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.common.content.SyncStateContentProviderHelper;
20
21import android.content.ContentResolver;
22import android.content.ContentValues;
23import android.content.Context;
24import android.content.pm.ApplicationInfo;
25import android.content.pm.PackageManager;
26import android.content.pm.PackageManager.NameNotFoundException;
27import android.content.res.Resources;
28import android.database.Cursor;
29import android.database.DatabaseUtils;
30import android.database.SQLException;
31import android.database.sqlite.SQLiteConstraintException;
32import android.database.sqlite.SQLiteDatabase;
33import android.database.sqlite.SQLiteDoneException;
34import android.database.sqlite.SQLiteException;
35import android.database.sqlite.SQLiteOpenHelper;
36import android.database.sqlite.SQLiteQueryBuilder;
37import android.database.sqlite.SQLiteStatement;
38import android.location.CountryDetector;
39import android.net.Uri;
40import android.os.Binder;
41import android.os.Bundle;
42import android.os.SystemClock;
43import android.provider.BaseColumns;
44import android.provider.CallLog.Calls;
45import android.provider.ContactsContract;
46import android.provider.ContactsContract.AggregationExceptions;
47import android.provider.ContactsContract.CommonDataKinds.Email;
48import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
49import android.provider.ContactsContract.CommonDataKinds.Im;
50import android.provider.ContactsContract.CommonDataKinds.Nickname;
51import android.provider.ContactsContract.CommonDataKinds.Organization;
52import android.provider.ContactsContract.CommonDataKinds.Phone;
53import android.provider.ContactsContract.CommonDataKinds.SipAddress;
54import android.provider.ContactsContract.CommonDataKinds.StructuredName;
55import android.provider.ContactsContract.Contacts;
56import android.provider.ContactsContract.Contacts.Photo;
57import android.provider.ContactsContract.Data;
58import android.provider.ContactsContract.Directory;
59import android.provider.ContactsContract.DisplayNameSources;
60import android.provider.ContactsContract.FullNameStyle;
61import android.provider.ContactsContract.Groups;
62import android.provider.ContactsContract.RawContacts;
63import android.provider.ContactsContract.Settings;
64import android.provider.ContactsContract.StatusUpdates;
65import android.provider.SocialContract.Activities;
66import android.telephony.PhoneNumberUtils;
67import android.text.TextUtils;
68import android.text.util.Rfc822Token;
69import android.text.util.Rfc822Tokenizer;
70import android.util.Log;
71
72import java.util.HashMap;
73import java.util.Locale;
74
75/**
76 * Database helper for contacts. Designed as a singleton to make sure that all
77 * {@link android.content.ContentProvider} users get the same reference.
78 * Provides handy methods for maintaining package and mime-type lookup tables.
79 */
80/* package */ class ContactsDatabaseHelper extends SQLiteOpenHelper {
81    private static final String TAG = "ContactsDatabaseHelper";
82
83    /**
84     * Contacts DB version ranges:
85     * <pre>
86     *   0-98    Cupcake/Donut
87     *   100-199 Eclair
88     *   200-299 Eclair-MR1
89     *   300-349 Froyo
90     *   350-399 Gingerbread
91     *   400-499 Honeycomb
92     *   500-599 Honeycomb-MR1
93     * </pre>
94     */
95    static final int DATABASE_VERSION = 503;
96
97    private static final String DATABASE_NAME = "contacts2.db";
98    private static final String DATABASE_PRESENCE = "presence_db";
99
100    public interface Tables {
101        public static final String CONTACTS = "contacts";
102        public static final String RAW_CONTACTS = "raw_contacts";
103        public static final String PACKAGES = "packages";
104        public static final String MIMETYPES = "mimetypes";
105        public static final String PHONE_LOOKUP = "phone_lookup";
106        public static final String NAME_LOOKUP = "name_lookup";
107        public static final String AGGREGATION_EXCEPTIONS = "agg_exceptions";
108        public static final String SETTINGS = "settings";
109        public static final String DATA = "data";
110        public static final String GROUPS = "groups";
111        public static final String PRESENCE = "presence";
112        public static final String AGGREGATED_PRESENCE = "agg_presence";
113        public static final String NICKNAME_LOOKUP = "nickname_lookup";
114        public static final String CALLS = "calls";
115        public static final String STATUS_UPDATES = "status_updates";
116        public static final String PROPERTIES = "properties";
117        public static final String ACCOUNTS = "accounts";
118        public static final String VISIBLE_CONTACTS = "visible_contacts";
119        public static final String DIRECTORIES = "directories";
120        public static final String DEFAULT_DIRECTORY = "default_directory";
121        public static final String SEARCH_INDEX = "search_index";
122
123        public static final String DATA_JOIN_MIMETYPES = "data "
124                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id)";
125
126        public static final String DATA_JOIN_RAW_CONTACTS = "data "
127                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
128
129        public static final String DATA_JOIN_MIMETYPE_RAW_CONTACTS = "data "
130                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
131                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
132
133        // NOTE: This requires late binding of GroupMembership MIME-type
134        public static final String RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS = "raw_contacts "
135                + "LEFT OUTER JOIN settings ON ("
136                    + "raw_contacts.account_name = settings.account_name AND "
137                    + "raw_contacts.account_type = settings.account_type) "
138                + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND "
139                    + "data.raw_contact_id = raw_contacts._id) "
140                + "LEFT OUTER JOIN groups ON (groups._id = data." + GroupMembership.GROUP_ROW_ID
141                + ")";
142
143        // NOTE: This requires late binding of GroupMembership MIME-type
144        public static final String SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS = "settings "
145                + "LEFT OUTER JOIN raw_contacts ON ("
146                    + "raw_contacts.account_name = settings.account_name AND "
147                    + "raw_contacts.account_type = settings.account_type) "
148                + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND "
149                    + "data.raw_contact_id = raw_contacts._id) "
150                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
151
152        public static final String DATA_JOIN_MIMETYPES_RAW_CONTACTS_CONTACTS = "data "
153                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
154                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
155                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
156
157        public static final String DATA_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_GROUPS = "data "
158                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
159                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
160                + "LEFT OUTER JOIN packages ON (data.package_id = packages._id) "
161                + "LEFT OUTER JOIN groups "
162                + "  ON (mimetypes.mimetype='" + GroupMembership.CONTENT_ITEM_TYPE + "' "
163                + "      AND groups._id = data." + GroupMembership.GROUP_ROW_ID + ") ";
164
165        public static final String GROUPS_JOIN_PACKAGES = "groups "
166                + "LEFT OUTER JOIN packages ON (groups.package_id = packages._id)";
167
168
169        public static final String ACTIVITIES = "activities";
170
171        public static final String ACTIVITIES_JOIN_MIMETYPES = "activities "
172                + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id)";
173
174        public static final String ACTIVITIES_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_CONTACTS =
175                "activities "
176                + "LEFT OUTER JOIN packages ON (activities.package_id = packages._id) "
177                + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id) "
178                + "LEFT OUTER JOIN raw_contacts ON (activities.author_contact_id = " +
179                        "raw_contacts._id) "
180                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
181
182        public static final String NAME_LOOKUP_JOIN_RAW_CONTACTS = "name_lookup "
183                + "INNER JOIN raw_contacts ON (name_lookup.raw_contact_id = raw_contacts._id)";
184    }
185
186    public interface Views {
187        public static final String DATA_ALL = "view_data";
188        public static final String DATA_RESTRICTED = "view_data_restricted";
189
190        public static final String RAW_CONTACTS_ALL = "view_raw_contacts";
191        public static final String RAW_CONTACTS_RESTRICTED = "view_raw_contacts_restricted";
192
193        public static final String CONTACTS_ALL = "view_contacts";
194        public static final String CONTACTS_RESTRICTED = "view_contacts_restricted";
195
196        public static final String ENTITIES = "view_entities";
197        public static final String ENTITIES_RESTRICTED = "view_entities_restricted";
198
199        public static final String RAW_ENTITIES = "view_raw_entities";
200        public static final String RAW_ENTITIES_RESTRICTED = "view_raw_entities_restricted";
201
202        public static final String GROUPS_ALL = "view_groups";
203    }
204
205    public interface Clauses {
206        final String MIMETYPE_IS_GROUP_MEMBERSHIP = MimetypesColumns.CONCRETE_MIMETYPE + "='"
207                + GroupMembership.CONTENT_ITEM_TYPE + "'";
208
209        final String BELONGS_TO_GROUP = DataColumns.CONCRETE_GROUP_ID + "="
210                + GroupsColumns.CONCRETE_ID;
211
212        final String HAVING_NO_GROUPS = "COUNT(" + DataColumns.CONCRETE_GROUP_ID + ") == 0";
213
214        final String GROUP_BY_ACCOUNT_CONTACT_ID = SettingsColumns.CONCRETE_ACCOUNT_NAME + ","
215                + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "," + RawContacts.CONTACT_ID;
216
217        final String RAW_CONTACT_IS_LOCAL = RawContactsColumns.CONCRETE_ACCOUNT_NAME
218                + " IS NULL AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL";
219
220        final String ZERO_GROUP_MEMBERSHIPS = "COUNT(" + GroupsColumns.CONCRETE_ID + ")=0";
221
222        final String OUTER_RAW_CONTACTS = "outer_raw_contacts";
223        final String OUTER_RAW_CONTACTS_ID = OUTER_RAW_CONTACTS + "." + RawContacts._ID;
224
225        final String CONTACT_IS_VISIBLE =
226                "SELECT " +
227                    "MAX((SELECT (CASE WHEN " +
228                        "(CASE" +
229                            " WHEN " + RAW_CONTACT_IS_LOCAL +
230                            " THEN 1 " +
231                            " WHEN " + ZERO_GROUP_MEMBERSHIPS +
232                            " THEN " + Settings.UNGROUPED_VISIBLE +
233                            " ELSE MAX(" + Groups.GROUP_VISIBLE + ")" +
234                         "END)=1 THEN 1 ELSE 0 END)" +
235                " FROM " + Tables.RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS +
236                " WHERE " + RawContactsColumns.CONCRETE_ID + "=" + OUTER_RAW_CONTACTS_ID + "))" +
237                " FROM " + Tables.RAW_CONTACTS + " AS " + OUTER_RAW_CONTACTS +
238                " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
239                " GROUP BY " + RawContacts.CONTACT_ID;
240
241        final String GROUP_HAS_ACCOUNT_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND "
242                + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?";
243
244        public static final String CONTACT_VISIBLE =
245            "EXISTS (SELECT _id FROM " + Tables.VISIBLE_CONTACTS
246                + " WHERE " + Tables.CONTACTS +"." + Contacts._ID
247                        + "=" + Tables.VISIBLE_CONTACTS +"." + Contacts._ID + ")";
248    }
249
250    public interface ContactsColumns {
251        /**
252         * This flag is set for a contact if it has only one constituent raw contact and
253         * it is restricted.
254         */
255        public static final String SINGLE_IS_RESTRICTED = "single_is_restricted";
256
257        public static final String LAST_STATUS_UPDATE_ID = "status_update_id";
258
259        public static final String CONCRETE_ID = Tables.CONTACTS + "." + BaseColumns._ID;
260
261        public static final String CONCRETE_TIMES_CONTACTED = Tables.CONTACTS + "."
262                + Contacts.TIMES_CONTACTED;
263        public static final String CONCRETE_LAST_TIME_CONTACTED = Tables.CONTACTS + "."
264                + Contacts.LAST_TIME_CONTACTED;
265        public static final String CONCRETE_STARRED = Tables.CONTACTS + "." + Contacts.STARRED;
266        public static final String CONCRETE_CUSTOM_RINGTONE = Tables.CONTACTS + "."
267                + Contacts.CUSTOM_RINGTONE;
268        public static final String CONCRETE_SEND_TO_VOICEMAIL = Tables.CONTACTS + "."
269                + Contacts.SEND_TO_VOICEMAIL;
270        public static final String CONCRETE_LOOKUP_KEY = Tables.CONTACTS + "."
271                + Contacts.LOOKUP_KEY;
272    }
273
274    public interface RawContactsColumns {
275        public static final String CONCRETE_ID =
276                Tables.RAW_CONTACTS + "." + BaseColumns._ID;
277        public static final String CONCRETE_ACCOUNT_NAME =
278                Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_NAME;
279        public static final String CONCRETE_ACCOUNT_TYPE =
280                Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE;
281        public static final String CONCRETE_SOURCE_ID =
282                Tables.RAW_CONTACTS + "." + RawContacts.SOURCE_ID;
283        public static final String CONCRETE_VERSION =
284                Tables.RAW_CONTACTS + "." + RawContacts.VERSION;
285        public static final String CONCRETE_DIRTY =
286                Tables.RAW_CONTACTS + "." + RawContacts.DIRTY;
287        public static final String CONCRETE_DELETED =
288                Tables.RAW_CONTACTS + "." + RawContacts.DELETED;
289        public static final String CONCRETE_SYNC1 =
290                Tables.RAW_CONTACTS + "." + RawContacts.SYNC1;
291        public static final String CONCRETE_SYNC2 =
292                Tables.RAW_CONTACTS + "." + RawContacts.SYNC2;
293        public static final String CONCRETE_SYNC3 =
294                Tables.RAW_CONTACTS + "." + RawContacts.SYNC3;
295        public static final String CONCRETE_SYNC4 =
296                Tables.RAW_CONTACTS + "." + RawContacts.SYNC4;
297        public static final String CONCRETE_STARRED =
298                Tables.RAW_CONTACTS + "." + RawContacts.STARRED;
299        public static final String CONCRETE_IS_RESTRICTED =
300                Tables.RAW_CONTACTS + "." + RawContacts.IS_RESTRICTED;
301
302        public static final String DISPLAY_NAME = RawContacts.DISPLAY_NAME_PRIMARY;
303        public static final String DISPLAY_NAME_SOURCE = RawContacts.DISPLAY_NAME_SOURCE;
304        public static final String AGGREGATION_NEEDED = "aggregation_needed";
305
306        public static final String CONCRETE_DISPLAY_NAME =
307                Tables.RAW_CONTACTS + "." + DISPLAY_NAME;
308        public static final String CONCRETE_CONTACT_ID =
309                Tables.RAW_CONTACTS + "." + RawContacts.CONTACT_ID;
310        public static final String CONCRETE_NAME_VERIFIED =
311                Tables.RAW_CONTACTS + "." + RawContacts.NAME_VERIFIED;
312    }
313
314    public interface DataColumns {
315        public static final String PACKAGE_ID = "package_id";
316        public static final String MIMETYPE_ID = "mimetype_id";
317
318        public static final String CONCRETE_ID = Tables.DATA + "." + BaseColumns._ID;
319        public static final String CONCRETE_MIMETYPE_ID = Tables.DATA + "." + MIMETYPE_ID;
320        public static final String CONCRETE_RAW_CONTACT_ID = Tables.DATA + "."
321                + Data.RAW_CONTACT_ID;
322        public static final String CONCRETE_GROUP_ID = Tables.DATA + "."
323                + GroupMembership.GROUP_ROW_ID;
324
325        public static final String CONCRETE_DATA1 = Tables.DATA + "." + Data.DATA1;
326        public static final String CONCRETE_DATA2 = Tables.DATA + "." + Data.DATA2;
327        public static final String CONCRETE_DATA3 = Tables.DATA + "." + Data.DATA3;
328        public static final String CONCRETE_DATA4 = Tables.DATA + "." + Data.DATA4;
329        public static final String CONCRETE_DATA5 = Tables.DATA + "." + Data.DATA5;
330        public static final String CONCRETE_DATA6 = Tables.DATA + "." + Data.DATA6;
331        public static final String CONCRETE_DATA7 = Tables.DATA + "." + Data.DATA7;
332        public static final String CONCRETE_DATA8 = Tables.DATA + "." + Data.DATA8;
333        public static final String CONCRETE_DATA9 = Tables.DATA + "." + Data.DATA9;
334        public static final String CONCRETE_DATA10 = Tables.DATA + "." + Data.DATA10;
335        public static final String CONCRETE_DATA11 = Tables.DATA + "." + Data.DATA11;
336        public static final String CONCRETE_DATA12 = Tables.DATA + "." + Data.DATA12;
337        public static final String CONCRETE_DATA13 = Tables.DATA + "." + Data.DATA13;
338        public static final String CONCRETE_DATA14 = Tables.DATA + "." + Data.DATA14;
339        public static final String CONCRETE_DATA15 = Tables.DATA + "." + Data.DATA15;
340        public static final String CONCRETE_IS_PRIMARY = Tables.DATA + "." + Data.IS_PRIMARY;
341        public static final String CONCRETE_PACKAGE_ID = Tables.DATA + "." + PACKAGE_ID;
342    }
343
344    // Used only for legacy API support
345    public interface ExtensionsColumns {
346        public static final String NAME = Data.DATA1;
347        public static final String VALUE = Data.DATA2;
348    }
349
350    public interface GroupMembershipColumns {
351        public static final String RAW_CONTACT_ID = Data.RAW_CONTACT_ID;
352        public static final String GROUP_ROW_ID = GroupMembership.GROUP_ROW_ID;
353    }
354
355    public interface PhoneColumns {
356        public static final String NORMALIZED_NUMBER = Data.DATA4;
357        public static final String CONCRETE_NORMALIZED_NUMBER = DataColumns.CONCRETE_DATA4;
358    }
359
360    public interface GroupsColumns {
361        public static final String PACKAGE_ID = "package_id";
362
363        public static final String CONCRETE_ID = Tables.GROUPS + "." + BaseColumns._ID;
364        public static final String CONCRETE_SOURCE_ID = Tables.GROUPS + "." + Groups.SOURCE_ID;
365        public static final String CONCRETE_ACCOUNT_NAME = Tables.GROUPS + "." + Groups.ACCOUNT_NAME;
366        public static final String CONCRETE_ACCOUNT_TYPE = Tables.GROUPS + "." + Groups.ACCOUNT_TYPE;
367    }
368
369    public interface ActivitiesColumns {
370        public static final String PACKAGE_ID = "package_id";
371        public static final String MIMETYPE_ID = "mimetype_id";
372    }
373
374    public interface PhoneLookupColumns {
375        public static final String _ID = BaseColumns._ID;
376        public static final String DATA_ID = "data_id";
377        public static final String RAW_CONTACT_ID = "raw_contact_id";
378        public static final String NORMALIZED_NUMBER = "normalized_number";
379        public static final String MIN_MATCH = "min_match";
380    }
381
382    public interface NameLookupColumns {
383        public static final String RAW_CONTACT_ID = "raw_contact_id";
384        public static final String DATA_ID = "data_id";
385        public static final String NORMALIZED_NAME = "normalized_name";
386        public static final String NAME_TYPE = "name_type";
387    }
388
389    public final static class NameLookupType {
390        public static final int NAME_EXACT = 0;
391        public static final int NAME_VARIANT = 1;
392        public static final int NAME_COLLATION_KEY = 2;
393        public static final int NICKNAME = 3;
394        public static final int EMAIL_BASED_NICKNAME = 4;
395
396        // This is the highest name lookup type code plus one
397        public static final int TYPE_COUNT = 5;
398
399        public static boolean isBasedOnStructuredName(int nameLookupType) {
400            return nameLookupType == NameLookupType.NAME_EXACT
401                    || nameLookupType == NameLookupType.NAME_VARIANT
402                    || nameLookupType == NameLookupType.NAME_COLLATION_KEY;
403        }
404    }
405
406    public interface PackagesColumns {
407        public static final String _ID = BaseColumns._ID;
408        public static final String PACKAGE = "package";
409
410        public static final String CONCRETE_ID = Tables.PACKAGES + "." + _ID;
411    }
412
413    public interface MimetypesColumns {
414        public static final String _ID = BaseColumns._ID;
415        public static final String MIMETYPE = "mimetype";
416
417        public static final String CONCRETE_ID = Tables.MIMETYPES + "." + BaseColumns._ID;
418        public static final String CONCRETE_MIMETYPE = Tables.MIMETYPES + "." + MIMETYPE;
419    }
420
421    public interface AggregationExceptionColumns {
422        public static final String _ID = BaseColumns._ID;
423    }
424
425    public interface NicknameLookupColumns {
426        public static final String NAME = "name";
427        public static final String CLUSTER = "cluster";
428    }
429
430    public interface SettingsColumns {
431        public static final String CONCRETE_ACCOUNT_NAME = Tables.SETTINGS + "."
432                + Settings.ACCOUNT_NAME;
433        public static final String CONCRETE_ACCOUNT_TYPE = Tables.SETTINGS + "."
434                + Settings.ACCOUNT_TYPE;
435    }
436
437    public interface PresenceColumns {
438        String RAW_CONTACT_ID = "presence_raw_contact_id";
439        String CONTACT_ID = "presence_contact_id";
440    }
441
442    public interface AggregatedPresenceColumns {
443        String CONTACT_ID = "presence_contact_id";
444
445        String CONCRETE_CONTACT_ID = Tables.AGGREGATED_PRESENCE + "." + CONTACT_ID;
446    }
447
448    public interface StatusUpdatesColumns {
449        String DATA_ID = "status_update_data_id";
450
451        String CONCRETE_DATA_ID = Tables.STATUS_UPDATES + "." + DATA_ID;
452
453        String CONCRETE_PRESENCE = Tables.STATUS_UPDATES + "." + StatusUpdates.PRESENCE;
454        String CONCRETE_STATUS = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS;
455        String CONCRETE_STATUS_TIMESTAMP = Tables.STATUS_UPDATES + "."
456                + StatusUpdates.STATUS_TIMESTAMP;
457        String CONCRETE_STATUS_RES_PACKAGE = Tables.STATUS_UPDATES + "."
458                + StatusUpdates.STATUS_RES_PACKAGE;
459        String CONCRETE_STATUS_LABEL = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_LABEL;
460        String CONCRETE_STATUS_ICON = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_ICON;
461    }
462
463    public interface ContactsStatusUpdatesColumns {
464        String ALIAS = "contacts_" + Tables.STATUS_UPDATES;
465
466        String CONCRETE_DATA_ID = ALIAS + "." + StatusUpdatesColumns.DATA_ID;
467
468        String CONCRETE_PRESENCE = ALIAS + "." + StatusUpdates.PRESENCE;
469        String CONCRETE_STATUS = ALIAS + "." + StatusUpdates.STATUS;
470        String CONCRETE_STATUS_TIMESTAMP = ALIAS + "." + StatusUpdates.STATUS_TIMESTAMP;
471        String CONCRETE_STATUS_RES_PACKAGE = ALIAS + "." + StatusUpdates.STATUS_RES_PACKAGE;
472        String CONCRETE_STATUS_LABEL = ALIAS + "." + StatusUpdates.STATUS_LABEL;
473        String CONCRETE_STATUS_ICON = ALIAS + "." + StatusUpdates.STATUS_ICON;
474    }
475
476    public interface PropertiesColumns {
477        String PROPERTY_KEY = "property_key";
478        String PROPERTY_VALUE = "property_value";
479    }
480
481    public static final class DirectoryColumns {
482        public static final String TYPE_RESOURCE_NAME = "typeResourceName";
483    }
484
485    public static final class SearchIndexColumns {
486        public static final String CONTACT_ID = "contact_id";
487        public static final String CONTENT = "content";
488        public static final String NAME = "name";
489        public static final String TOKENS = "tokens";
490    }
491
492    /** In-memory cache of previously found MIME-type mappings */
493    private final HashMap<String, Long> mMimetypeCache = new HashMap<String, Long>();
494    /** In-memory cache of previously found package name mappings */
495    private final HashMap<String, Long> mPackageCache = new HashMap<String, Long>();
496
497    private long mMimeTypeIdEmail;
498    private long mMimeTypeIdIm;
499    private long mMimeTypeIdSip;
500    private long mMimeTypeIdStructuredName;
501    private long mMimeTypeIdOrganization;
502    private long mMimeTypeIdNickname;
503    private long mMimeTypeIdPhone;
504
505    /** Compiled statements for querying and inserting mappings */
506    private SQLiteStatement mMimetypeQuery;
507    private SQLiteStatement mPackageQuery;
508    private SQLiteStatement mContactIdQuery;
509    private SQLiteStatement mAggregationModeQuery;
510    private SQLiteStatement mMimetypeInsert;
511    private SQLiteStatement mPackageInsert;
512    private SQLiteStatement mDataMimetypeQuery;
513    private SQLiteStatement mActivitiesMimetypeQuery;
514
515    /** Precompiled sql statement for setting a data record to the primary. */
516    private SQLiteStatement mSetPrimaryStatement;
517    /** Precompiled sql statement for setting a data record to the super primary. */
518    private SQLiteStatement mSetSuperPrimaryStatement;
519    /** Precompiled sql statement for clearing super primary of a single record. */
520    private SQLiteStatement mClearSuperPrimaryStatement;
521    /** Precompiled sql statement for updating a contact display name */
522    private SQLiteStatement mRawContactDisplayNameUpdate;
523
524    private SQLiteStatement mNameLookupInsert;
525    private SQLiteStatement mNameLookupDelete;
526    private SQLiteStatement mStatusUpdateAutoTimestamp;
527    private SQLiteStatement mStatusUpdateInsert;
528    private SQLiteStatement mStatusUpdateReplace;
529    private SQLiteStatement mStatusAttributionUpdate;
530    private SQLiteStatement mStatusUpdateDelete;
531    private SQLiteStatement mResetNameVerifiedForOtherRawContacts;
532    private SQLiteStatement mContactInDefaultDirectoryQuery;
533
534    private final Context mContext;
535    private final boolean mDatabaseOptimizationEnabled;
536    private final SyncStateContentProviderHelper mSyncState;
537    private final CountryMonitor mCountryMonitor;
538    private StringBuilder mSb = new StringBuilder();
539
540    private boolean mReopenDatabase = false;
541
542    private static ContactsDatabaseHelper sSingleton = null;
543
544    private boolean mUseStrictPhoneNumberComparison;
545
546    /**
547     * List of package names with access to {@link RawContacts#IS_RESTRICTED} data.
548     */
549    private String[] mUnrestrictedPackages;
550
551
552    public static synchronized ContactsDatabaseHelper getInstance(Context context) {
553        if (sSingleton == null) {
554            sSingleton = new ContactsDatabaseHelper(context, DATABASE_NAME, true);
555        }
556        return sSingleton;
557    }
558
559    /**
560     * Private constructor, callers except unit tests should obtain an instance through
561     * {@link #getInstance(android.content.Context)} instead.
562     */
563    ContactsDatabaseHelper(Context context) {
564        this(context, null, false);
565    }
566
567    private ContactsDatabaseHelper(
568            Context context, String databaseName, boolean optimizationEnabled) {
569        super(context, databaseName, null, DATABASE_VERSION);
570        mDatabaseOptimizationEnabled = optimizationEnabled;
571        Resources resources = context.getResources();
572
573        mContext = context;
574        mSyncState = new SyncStateContentProviderHelper();
575        mCountryMonitor = new CountryMonitor(context);
576        mUseStrictPhoneNumberComparison =
577                resources.getBoolean(
578                        com.android.internal.R.bool.config_use_strict_phone_number_comparation);
579        int resourceId = resources.getIdentifier("unrestricted_packages", "array",
580                context.getPackageName());
581        if (resourceId != 0) {
582            mUnrestrictedPackages = resources.getStringArray(resourceId);
583        } else {
584            mUnrestrictedPackages = new String[0];
585        }
586    }
587
588    private void refreshDatabaseCaches(SQLiteDatabase db) {
589        mStatusUpdateDelete = null;
590        mStatusUpdateReplace = null;
591        mStatusUpdateInsert = null;
592        mStatusUpdateAutoTimestamp = null;
593        mStatusAttributionUpdate = null;
594        mResetNameVerifiedForOtherRawContacts = null;
595        mRawContactDisplayNameUpdate = null;
596        mSetPrimaryStatement = null;
597        mClearSuperPrimaryStatement = null;
598        mSetSuperPrimaryStatement = null;
599        mNameLookupInsert = null;
600        mNameLookupDelete = null;
601        mPackageQuery = null;
602        mPackageInsert = null;
603        mDataMimetypeQuery = null;
604        mActivitiesMimetypeQuery = null;
605        mContactIdQuery = null;
606        mAggregationModeQuery = null;
607        mContactInDefaultDirectoryQuery = null;
608
609        mMimetypeCache.clear();
610        mPackageCache.clear();
611
612        mMimetypeQuery = db.compileStatement(
613                "SELECT " + MimetypesColumns._ID +
614                " FROM " + Tables.MIMETYPES +
615                " WHERE " + MimetypesColumns.MIMETYPE + "=?");
616
617        mMimetypeInsert = db.compileStatement(
618                "INSERT INTO " + Tables.MIMETYPES + "("
619                        + MimetypesColumns.MIMETYPE +
620                ") VALUES (?)");
621
622        mMimeTypeIdEmail = getMimeTypeId(Email.CONTENT_ITEM_TYPE);
623        mMimeTypeIdIm = getMimeTypeId(Im.CONTENT_ITEM_TYPE);
624        mMimeTypeIdSip = getMimeTypeId(SipAddress.CONTENT_ITEM_TYPE);
625        mMimeTypeIdStructuredName = getMimeTypeId(StructuredName.CONTENT_ITEM_TYPE);
626        mMimeTypeIdOrganization = getMimeTypeId(Organization.CONTENT_ITEM_TYPE);
627        mMimeTypeIdNickname = getMimeTypeId(Nickname.CONTENT_ITEM_TYPE);
628        mMimeTypeIdPhone = getMimeTypeId(Phone.CONTENT_ITEM_TYPE);
629    }
630
631    @Override
632    public void onOpen(SQLiteDatabase db) {
633        refreshDatabaseCaches(db);
634
635        mSyncState.onDatabaseOpened(db);
636
637        db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";");
638        db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_PRESENCE + "." + Tables.PRESENCE + " ("+
639                StatusUpdates.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
640                StatusUpdates.PROTOCOL + " INTEGER NOT NULL," +
641                StatusUpdates.CUSTOM_PROTOCOL + " TEXT," +
642                StatusUpdates.IM_HANDLE + " TEXT," +
643                StatusUpdates.IM_ACCOUNT + " TEXT," +
644                PresenceColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
645                PresenceColumns.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
646                StatusUpdates.PRESENCE + " INTEGER," +
647                StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0," +
648                "UNIQUE(" + StatusUpdates.PROTOCOL + ", " + StatusUpdates.CUSTOM_PROTOCOL
649                    + ", " + StatusUpdates.IM_HANDLE + ", " + StatusUpdates.IM_ACCOUNT + ")" +
650        ");");
651
652        db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex" + " ON "
653                + Tables.PRESENCE + " (" + PresenceColumns.RAW_CONTACT_ID + ");");
654        db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex2" + " ON "
655                + Tables.PRESENCE + " (" + PresenceColumns.CONTACT_ID + ");");
656
657        db.execSQL("CREATE TABLE IF NOT EXISTS "
658                + DATABASE_PRESENCE + "." + Tables.AGGREGATED_PRESENCE + " ("+
659                AggregatedPresenceColumns.CONTACT_ID
660                        + " INTEGER PRIMARY KEY REFERENCES contacts(_id)," +
661                StatusUpdates.PRESENCE + " INTEGER," +
662                StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0" +
663        ");");
664
665
666        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_deleted"
667                + " BEFORE DELETE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
668                + " BEGIN "
669                + "   DELETE FROM " + Tables.AGGREGATED_PRESENCE
670                + "     WHERE " + AggregatedPresenceColumns.CONTACT_ID + " = " +
671                        "(SELECT " + PresenceColumns.CONTACT_ID +
672                        " FROM " + Tables.PRESENCE +
673                        " WHERE " + PresenceColumns.RAW_CONTACT_ID
674                                + "=OLD." + PresenceColumns.RAW_CONTACT_ID +
675                        " AND NOT EXISTS" +
676                                "(SELECT " + PresenceColumns.RAW_CONTACT_ID +
677                                " FROM " + Tables.PRESENCE +
678                                " WHERE " + PresenceColumns.CONTACT_ID
679                                        + "=OLD." + PresenceColumns.CONTACT_ID +
680                                " AND " + PresenceColumns.RAW_CONTACT_ID
681                                        + "!=OLD." + PresenceColumns.RAW_CONTACT_ID + "));"
682                + " END");
683
684        final String replaceAggregatePresenceSql =
685                "INSERT OR REPLACE INTO " + Tables.AGGREGATED_PRESENCE + "("
686                        + AggregatedPresenceColumns.CONTACT_ID + ", "
687                        + StatusUpdates.PRESENCE + ", "
688                        + StatusUpdates.CHAT_CAPABILITY + ")"
689                + " SELECT "
690                        + PresenceColumns.CONTACT_ID + ","
691                        + StatusUpdates.PRESENCE + ","
692                        + StatusUpdates.CHAT_CAPABILITY
693                + " FROM " + Tables.PRESENCE
694                + " WHERE "
695                    + " (ifnull(" + StatusUpdates.PRESENCE + ",0)  * 10 "
696                            + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))"
697                    + " = (SELECT "
698                        + "MAX (ifnull(" + StatusUpdates.PRESENCE + ",0)  * 10 "
699                                + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))"
700                        + " FROM " + Tables.PRESENCE
701                        + " WHERE " + PresenceColumns.CONTACT_ID
702                            + "=NEW." + PresenceColumns.CONTACT_ID
703                    + ")"
704                + " AND " + PresenceColumns.CONTACT_ID + "=NEW." + PresenceColumns.CONTACT_ID + ";";
705
706        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_inserted"
707                + " AFTER INSERT ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
708                + " BEGIN "
709                + replaceAggregatePresenceSql
710                + " END");
711
712        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_updated"
713                + " AFTER UPDATE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
714                + " BEGIN "
715                + replaceAggregatePresenceSql
716                + " END");
717    }
718
719    @Override
720    public void onCreate(SQLiteDatabase db) {
721        Log.i(TAG, "Bootstrapping database");
722
723        mSyncState.createDatabase(db);
724
725        // One row per group of contacts corresponding to the same person
726        db.execSQL("CREATE TABLE " + Tables.CONTACTS + " (" +
727                BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
728                Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
729                Contacts.PHOTO_ID + " INTEGER REFERENCES data(_id)," +
730                Contacts.CUSTOM_RINGTONE + " TEXT," +
731                Contacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
732                Contacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
733                Contacts.LAST_TIME_CONTACTED + " INTEGER," +
734                Contacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
735                Contacts.HAS_PHONE_NUMBER + " INTEGER NOT NULL DEFAULT 0," +
736                Contacts.LOOKUP_KEY + " TEXT," +
737                ContactsColumns.LAST_STATUS_UPDATE_ID + " INTEGER REFERENCES data(_id)," +
738                ContactsColumns.SINGLE_IS_RESTRICTED + " INTEGER NOT NULL DEFAULT 0" +
739        ");");
740
741        db.execSQL("CREATE INDEX contacts_has_phone_index ON " + Tables.CONTACTS + " (" +
742                Contacts.HAS_PHONE_NUMBER +
743        ");");
744
745        db.execSQL("CREATE INDEX contacts_restricted_index ON " + Tables.CONTACTS + " (" +
746                ContactsColumns.SINGLE_IS_RESTRICTED +
747        ");");
748
749        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
750                Contacts.NAME_RAW_CONTACT_ID +
751        ");");
752
753        // Contacts table
754        db.execSQL("CREATE TABLE " + Tables.RAW_CONTACTS + " (" +
755                RawContacts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
756                RawContacts.IS_RESTRICTED + " INTEGER DEFAULT 0," +
757                RawContacts.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
758                RawContacts.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
759                RawContacts.SOURCE_ID + " TEXT," +
760                RawContacts.RAW_CONTACT_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," +
761                RawContacts.VERSION + " INTEGER NOT NULL DEFAULT 1," +
762                RawContacts.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
763                RawContacts.DELETED + " INTEGER NOT NULL DEFAULT 0," +
764                RawContacts.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
765                RawContacts.AGGREGATION_MODE + " INTEGER NOT NULL DEFAULT " +
766                        RawContacts.AGGREGATION_MODE_DEFAULT + "," +
767                RawContactsColumns.AGGREGATION_NEEDED + " INTEGER NOT NULL DEFAULT 1," +
768                RawContacts.CUSTOM_RINGTONE + " TEXT," +
769                RawContacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
770                RawContacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
771                RawContacts.LAST_TIME_CONTACTED + " INTEGER," +
772                RawContacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
773                RawContacts.DISPLAY_NAME_PRIMARY + " TEXT," +
774                RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT," +
775                RawContacts.DISPLAY_NAME_SOURCE + " INTEGER NOT NULL DEFAULT " +
776                        DisplayNameSources.UNDEFINED + "," +
777                RawContacts.PHONETIC_NAME + " TEXT," +
778                RawContacts.PHONETIC_NAME_STYLE + " TEXT," +
779                RawContacts.SORT_KEY_PRIMARY + " TEXT COLLATE " +
780                        ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," +
781                RawContacts.SORT_KEY_ALTERNATIVE + " TEXT COLLATE " +
782                        ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," +
783                RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0," +
784                RawContacts.SYNC1 + " TEXT, " +
785                RawContacts.SYNC2 + " TEXT, " +
786                RawContacts.SYNC3 + " TEXT, " +
787                RawContacts.SYNC4 + " TEXT " +
788        ");");
789
790        db.execSQL("CREATE INDEX raw_contacts_contact_id_index ON " + Tables.RAW_CONTACTS + " (" +
791                RawContacts.CONTACT_ID +
792        ");");
793
794        db.execSQL("CREATE INDEX raw_contacts_source_id_index ON " + Tables.RAW_CONTACTS + " (" +
795                RawContacts.SOURCE_ID + ", " +
796                RawContacts.ACCOUNT_TYPE + ", " +
797                RawContacts.ACCOUNT_NAME +
798        ");");
799
800        // TODO readd the index and investigate a controlled use of it
801//        db.execSQL("CREATE INDEX raw_contacts_agg_index ON " + Tables.RAW_CONTACTS + " (" +
802//                RawContactsColumns.AGGREGATION_NEEDED +
803//        ");");
804
805        // Package name mapping table
806        db.execSQL("CREATE TABLE " + Tables.PACKAGES + " (" +
807                PackagesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
808                PackagesColumns.PACKAGE + " TEXT NOT NULL" +
809        ");");
810
811        // Mimetype mapping table
812        db.execSQL("CREATE TABLE " + Tables.MIMETYPES + " (" +
813                MimetypesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
814                MimetypesColumns.MIMETYPE + " TEXT NOT NULL" +
815        ");");
816
817        // Mimetype table requires an index on mime type
818        db.execSQL("CREATE UNIQUE INDEX mime_type ON " + Tables.MIMETYPES + " (" +
819                MimetypesColumns.MIMETYPE +
820        ");");
821
822        // Public generic data table
823        db.execSQL("CREATE TABLE " + Tables.DATA + " (" +
824                Data._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
825                DataColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
826                DataColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
827                Data.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
828                Data.IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," +
829                Data.IS_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
830                Data.IS_SUPER_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
831                Data.DATA_VERSION + " INTEGER NOT NULL DEFAULT 0," +
832                Data.DATA1 + " TEXT," +
833                Data.DATA2 + " TEXT," +
834                Data.DATA3 + " TEXT," +
835                Data.DATA4 + " TEXT," +
836                Data.DATA5 + " TEXT," +
837                Data.DATA6 + " TEXT," +
838                Data.DATA7 + " TEXT," +
839                Data.DATA8 + " TEXT," +
840                Data.DATA9 + " TEXT," +
841                Data.DATA10 + " TEXT," +
842                Data.DATA11 + " TEXT," +
843                Data.DATA12 + " TEXT," +
844                Data.DATA13 + " TEXT," +
845                Data.DATA14 + " TEXT," +
846                Data.DATA15 + " TEXT," +
847                Data.SYNC1 + " TEXT, " +
848                Data.SYNC2 + " TEXT, " +
849                Data.SYNC3 + " TEXT, " +
850                Data.SYNC4 + " TEXT " +
851        ");");
852
853        db.execSQL("CREATE INDEX data_raw_contact_id ON " + Tables.DATA + " (" +
854                Data.RAW_CONTACT_ID +
855        ");");
856
857        /**
858         * For email lookup and similar queries.
859         */
860        db.execSQL("CREATE INDEX data_mimetype_data1_index ON " + Tables.DATA + " (" +
861                DataColumns.MIMETYPE_ID + "," +
862                Data.DATA1 +
863        ");");
864
865        // Private phone numbers table used for lookup
866        db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
867                PhoneLookupColumns.DATA_ID
868                        + " INTEGER REFERENCES data(_id) NOT NULL," +
869                PhoneLookupColumns.RAW_CONTACT_ID
870                        + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
871                PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
872                PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
873        ");");
874
875        db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
876                PhoneLookupColumns.NORMALIZED_NUMBER + "," +
877                PhoneLookupColumns.RAW_CONTACT_ID + "," +
878                PhoneLookupColumns.DATA_ID +
879        ");");
880
881        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
882                PhoneLookupColumns.MIN_MATCH + "," +
883                PhoneLookupColumns.RAW_CONTACT_ID + "," +
884                PhoneLookupColumns.DATA_ID +
885        ");");
886
887        db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP +
888                " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");");
889
890        // Private name/nickname table used for lookup
891        db.execSQL("CREATE TABLE " + Tables.NAME_LOOKUP + " (" +
892                NameLookupColumns.DATA_ID
893                        + " INTEGER REFERENCES data(_id) NOT NULL," +
894                NameLookupColumns.RAW_CONTACT_ID
895                        + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
896                NameLookupColumns.NORMALIZED_NAME + " TEXT NOT NULL," +
897                NameLookupColumns.NAME_TYPE + " INTEGER NOT NULL," +
898                "PRIMARY KEY ("
899                        + NameLookupColumns.DATA_ID + ", "
900                        + NameLookupColumns.NORMALIZED_NAME + ", "
901                        + NameLookupColumns.NAME_TYPE + ")" +
902        ");");
903
904        db.execSQL("CREATE INDEX name_lookup_raw_contact_id_index ON " + Tables.NAME_LOOKUP + " (" +
905                NameLookupColumns.RAW_CONTACT_ID +
906        ");");
907
908        db.execSQL("CREATE TABLE " + Tables.NICKNAME_LOOKUP + " (" +
909                NicknameLookupColumns.NAME + " TEXT," +
910                NicknameLookupColumns.CLUSTER + " TEXT" +
911        ");");
912
913        db.execSQL("CREATE UNIQUE INDEX nickname_lookup_index ON " + Tables.NICKNAME_LOOKUP + " (" +
914                NicknameLookupColumns.NAME + ", " +
915                NicknameLookupColumns.CLUSTER +
916        ");");
917
918        // Groups table
919        db.execSQL("CREATE TABLE " + Tables.GROUPS + " (" +
920                Groups._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
921                GroupsColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
922                Groups.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
923                Groups.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
924                Groups.SOURCE_ID + " TEXT," +
925                Groups.VERSION + " INTEGER NOT NULL DEFAULT 1," +
926                Groups.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
927                Groups.TITLE + " TEXT," +
928                Groups.TITLE_RES + " INTEGER," +
929                Groups.NOTES + " TEXT," +
930                Groups.SYSTEM_ID + " TEXT," +
931                Groups.DELETED + " INTEGER NOT NULL DEFAULT 0," +
932                Groups.GROUP_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
933                Groups.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1," +
934                Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0," +
935                Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0," +
936                Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," +
937                Groups.SYNC1 + " TEXT, " +
938                Groups.SYNC2 + " TEXT, " +
939                Groups.SYNC3 + " TEXT, " +
940                Groups.SYNC4 + " TEXT " +
941        ");");
942
943        db.execSQL("CREATE INDEX groups_source_id_index ON " + Tables.GROUPS + " (" +
944                Groups.SOURCE_ID + ", " +
945                Groups.ACCOUNT_TYPE + ", " +
946                Groups.ACCOUNT_NAME +
947        ");");
948
949        db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.AGGREGATION_EXCEPTIONS + " (" +
950                AggregationExceptionColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
951                AggregationExceptions.TYPE + " INTEGER NOT NULL, " +
952                AggregationExceptions.RAW_CONTACT_ID1
953                        + " INTEGER REFERENCES raw_contacts(_id), " +
954                AggregationExceptions.RAW_CONTACT_ID2
955                        + " INTEGER REFERENCES raw_contacts(_id)" +
956        ");");
957
958        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index1 ON " +
959                Tables.AGGREGATION_EXCEPTIONS + " (" +
960                AggregationExceptions.RAW_CONTACT_ID1 + ", " +
961                AggregationExceptions.RAW_CONTACT_ID2 +
962        ");");
963
964        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index2 ON " +
965                Tables.AGGREGATION_EXCEPTIONS + " (" +
966                AggregationExceptions.RAW_CONTACT_ID2 + ", " +
967                AggregationExceptions.RAW_CONTACT_ID1 +
968        ");");
969
970        db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.SETTINGS + " (" +
971                Settings.ACCOUNT_NAME + " STRING NOT NULL," +
972                Settings.ACCOUNT_TYPE + " STRING NOT NULL," +
973                Settings.UNGROUPED_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
974                Settings.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1, " +
975                "PRIMARY KEY (" + Settings.ACCOUNT_NAME + ", " +
976                    Settings.ACCOUNT_TYPE + ") ON CONFLICT REPLACE" +
977        ");");
978
979        db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" +
980                Contacts._ID + " INTEGER PRIMARY KEY" +
981        ");");
982
983        db.execSQL("CREATE TABLE " + Tables.DEFAULT_DIRECTORY + " (" +
984                Contacts._ID + " INTEGER PRIMARY KEY" +
985        ");");
986
987        // The table for recent calls is here so we can do table joins
988        // on people, phones, and calls all in one place.
989        db.execSQL("CREATE TABLE " + Tables.CALLS + " (" +
990                Calls._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
991                Calls.NUMBER + " TEXT," +
992                Calls.DATE + " INTEGER," +
993                Calls.DURATION + " INTEGER," +
994                Calls.TYPE + " INTEGER," +
995                Calls.NEW + " INTEGER," +
996                Calls.CACHED_NAME + " TEXT," +
997                Calls.CACHED_NUMBER_TYPE + " INTEGER," +
998                Calls.CACHED_NUMBER_LABEL + " TEXT," +
999                Calls.COUNTRY_ISO + " TEXT" + ");");
1000
1001        // Activities table
1002        db.execSQL("CREATE TABLE " + Tables.ACTIVITIES + " (" +
1003                Activities._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1004                ActivitiesColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
1005                ActivitiesColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
1006                Activities.RAW_ID + " TEXT," +
1007                Activities.IN_REPLY_TO + " TEXT," +
1008                Activities.AUTHOR_CONTACT_ID +  " INTEGER REFERENCES raw_contacts(_id)," +
1009                Activities.TARGET_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
1010                Activities.PUBLISHED + " INTEGER NOT NULL," +
1011                Activities.THREAD_PUBLISHED + " INTEGER NOT NULL," +
1012                Activities.TITLE + " TEXT NOT NULL," +
1013                Activities.SUMMARY + " TEXT," +
1014                Activities.LINK + " TEXT, " +
1015                Activities.THUMBNAIL + " BLOB" +
1016        ");");
1017
1018        db.execSQL("CREATE TABLE " + Tables.STATUS_UPDATES + " (" +
1019                StatusUpdatesColumns.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
1020                StatusUpdates.STATUS + " TEXT," +
1021                StatusUpdates.STATUS_TIMESTAMP + " INTEGER," +
1022                StatusUpdates.STATUS_RES_PACKAGE + " TEXT, " +
1023                StatusUpdates.STATUS_LABEL + " INTEGER, " +
1024                StatusUpdates.STATUS_ICON + " INTEGER" +
1025        ");");
1026
1027        db.execSQL("CREATE TABLE " + Tables.PROPERTIES + " (" +
1028                PropertiesColumns.PROPERTY_KEY + " TEXT PRIMARY KEY, " +
1029                PropertiesColumns.PROPERTY_VALUE + " TEXT " +
1030        ");");
1031
1032        db.execSQL("CREATE TABLE " + Tables.ACCOUNTS + " (" +
1033                RawContacts.ACCOUNT_NAME + " TEXT, " +
1034                RawContacts.ACCOUNT_TYPE + " TEXT " +
1035        ");");
1036
1037        // Allow contacts without any account to be created for now.  Achieve that
1038        // by inserting a fake account with both type and name as NULL.
1039        // This "account" should be eliminated as soon as the first real writable account
1040        // is added to the phone.
1041        db.execSQL("INSERT INTO accounts VALUES(NULL, NULL)");
1042
1043        createDirectoriesTable(db);
1044        createSearchIndexTable(db);
1045
1046        createContactsViews(db);
1047        createGroupsView(db);
1048        createContactsTriggers(db);
1049        createContactsIndexes(db);
1050
1051        loadNicknameLookupTable(db);
1052
1053        // Add the legacy API support views, etc
1054        LegacyApiSupport.createDatabase(db);
1055
1056        if (mDatabaseOptimizationEnabled) {
1057            // This will create a sqlite_stat1 table that is used for query optimization
1058            db.execSQL("ANALYZE;");
1059
1060            updateSqliteStats(db);
1061
1062            // We need to close and reopen the database connection so that the stats are
1063            // taken into account. Make a note of it and do the actual reopening in the
1064            // getWritableDatabase method.
1065            mReopenDatabase = true;
1066        }
1067
1068        ContentResolver.requestSync(null /* all accounts */,
1069                ContactsContract.AUTHORITY, new Bundle());
1070    }
1071
1072    private void createDirectoriesTable(SQLiteDatabase db) {
1073        db.execSQL("CREATE TABLE " + Tables.DIRECTORIES + "(" +
1074                Directory._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1075                Directory.PACKAGE_NAME + " TEXT NOT NULL," +
1076                Directory.DIRECTORY_AUTHORITY + " TEXT NOT NULL," +
1077                Directory.TYPE_RESOURCE_ID + " INTEGER," +
1078                DirectoryColumns.TYPE_RESOURCE_NAME + " TEXT," +
1079                Directory.ACCOUNT_TYPE + " TEXT," +
1080                Directory.ACCOUNT_NAME + " TEXT," +
1081                Directory.DISPLAY_NAME + " TEXT, " +
1082                Directory.EXPORT_SUPPORT + " INTEGER NOT NULL" +
1083                        " DEFAULT " + Directory.EXPORT_SUPPORT_NONE + "," +
1084                Directory.SHORTCUT_SUPPORT + " INTEGER NOT NULL" +
1085                        " DEFAULT " + Directory.SHORTCUT_SUPPORT_NONE + "," +
1086                Directory.PHOTO_SUPPORT + " INTEGER NOT NULL" +
1087                        " DEFAULT " + Directory.PHOTO_SUPPORT_NONE +
1088        ");");
1089
1090        // Trigger a full scan of directories in the system
1091        setProperty(db, ContactDirectoryManager.PROPERTY_DIRECTORY_SCAN_COMPLETE, "0");
1092    }
1093
1094    public void createSearchIndexTable(SQLiteDatabase db) {
1095        db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_INDEX);
1096        db.execSQL("CREATE VIRTUAL TABLE " + Tables.SEARCH_INDEX
1097                + " USING FTS4 ("
1098                    + SearchIndexColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id) NOT NULL,"
1099                    + SearchIndexColumns.CONTENT + " TEXT, "
1100                    + SearchIndexColumns.NAME + " TEXT, "
1101                    + SearchIndexColumns.TOKENS + " TEXT"
1102                + ")");
1103    }
1104
1105    private static void createContactsTriggers(SQLiteDatabase db) {
1106
1107        /*
1108         * Automatically delete Data rows when a raw contact is deleted.
1109         */
1110        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;");
1111        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted "
1112                + "   BEFORE DELETE ON " + Tables.RAW_CONTACTS
1113                + " BEGIN "
1114                + "   DELETE FROM " + Tables.DATA
1115                + "     WHERE " + Data.RAW_CONTACT_ID
1116                                + "=OLD." + RawContacts._ID + ";"
1117                + "   DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS
1118                + "     WHERE " + AggregationExceptions.RAW_CONTACT_ID1
1119                                + "=OLD." + RawContacts._ID
1120                + "        OR " + AggregationExceptions.RAW_CONTACT_ID2
1121                                + "=OLD." + RawContacts._ID + ";"
1122                + "   DELETE FROM " + Tables.VISIBLE_CONTACTS
1123                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1124                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1125                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1126                + "           )=1;"
1127                + "   DELETE FROM " + Tables.DEFAULT_DIRECTORY
1128                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1129                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1130                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1131                + "           )=1;"
1132                + "   DELETE FROM " + Tables.CONTACTS
1133                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1134                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1135                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1136                + "           )=1;"
1137                + " END");
1138
1139
1140        db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;");
1141        db.execSQL("DROP TRIGGER IF EXISTS raw_contacts_times_contacted;");
1142
1143        /*
1144         * Triggers that update {@link RawContacts#VERSION} when the contact is
1145         * marked for deletion or any time a data row is inserted, updated or
1146         * deleted.
1147         */
1148        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;");
1149        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted "
1150                + "   AFTER UPDATE ON " + Tables.RAW_CONTACTS
1151                + " BEGIN "
1152                + "   UPDATE " + Tables.RAW_CONTACTS
1153                + "     SET "
1154                +         RawContacts.VERSION + "=OLD." + RawContacts.VERSION + "+1 "
1155                + "     WHERE " + RawContacts._ID + "=OLD." + RawContacts._ID
1156                + "       AND NEW." + RawContacts.DELETED + "!= OLD." + RawContacts.DELETED + ";"
1157                + " END");
1158
1159        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_updated;");
1160        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_updated AFTER UPDATE ON " + Tables.DATA
1161                + " BEGIN "
1162                + "   UPDATE " + Tables.DATA
1163                + "     SET " + Data.DATA_VERSION + "=OLD." + Data.DATA_VERSION + "+1 "
1164                + "     WHERE " + Data._ID + "=OLD." + Data._ID + ";"
1165                + "   UPDATE " + Tables.RAW_CONTACTS
1166                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
1167                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
1168                + " END");
1169
1170        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_deleted;");
1171        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_deleted BEFORE DELETE ON " + Tables.DATA
1172                + " BEGIN "
1173                + "   UPDATE " + Tables.RAW_CONTACTS
1174                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
1175                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
1176                + "   DELETE FROM " + Tables.PHONE_LOOKUP
1177                + "     WHERE " + PhoneLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1178                + "   DELETE FROM " + Tables.STATUS_UPDATES
1179                + "     WHERE " + StatusUpdatesColumns.DATA_ID + "=OLD." + Data._ID + ";"
1180                + "   DELETE FROM " + Tables.NAME_LOOKUP
1181                + "     WHERE " + NameLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1182                + " END");
1183
1184
1185        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_updated1;");
1186        db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_updated1 "
1187                + "   AFTER UPDATE ON " + Tables.GROUPS
1188                + " BEGIN "
1189                + "   UPDATE " + Tables.GROUPS
1190                + "     SET "
1191                +         Groups.VERSION + "=OLD." + Groups.VERSION + "+1"
1192                + "     WHERE " + Groups._ID + "=OLD." + Groups._ID + ";"
1193                + " END");
1194    }
1195
1196    private static void createContactsIndexes(SQLiteDatabase db) {
1197        db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
1198        db.execSQL("CREATE INDEX name_lookup_index ON " + Tables.NAME_LOOKUP + " (" +
1199                NameLookupColumns.NORMALIZED_NAME + "," +
1200                NameLookupColumns.NAME_TYPE + ", " +
1201                NameLookupColumns.RAW_CONTACT_ID + ", " +
1202                NameLookupColumns.DATA_ID +
1203        ");");
1204
1205        db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key1_index");
1206        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
1207                RawContacts.SORT_KEY_PRIMARY +
1208        ");");
1209
1210        db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key2_index");
1211        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
1212                RawContacts.SORT_KEY_ALTERNATIVE +
1213        ");");
1214    }
1215
1216    private static void createContactsViews(SQLiteDatabase db) {
1217        db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS_ALL + ";");
1218        db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS_RESTRICTED + ";");
1219        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_ALL + ";");
1220        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_RESTRICTED + ";");
1221        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS_ALL + ";");
1222        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS_RESTRICTED + ";");
1223        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_ENTITIES + ";");
1224        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_ENTITIES_RESTRICTED + ";");
1225        db.execSQL("DROP VIEW IF EXISTS " + Views.ENTITIES + ";");
1226        db.execSQL("DROP VIEW IF EXISTS " + Views.ENTITIES_RESTRICTED + ";");
1227
1228        String dataColumns =
1229                Data.IS_PRIMARY + ", "
1230                + Data.IS_SUPER_PRIMARY + ", "
1231                + Data.DATA_VERSION + ", "
1232                + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + ","
1233                + MimetypesColumns.MIMETYPE + " AS " + Data.MIMETYPE + ", "
1234                + Data.IS_READ_ONLY + ", "
1235                + Data.DATA1 + ", "
1236                + Data.DATA2 + ", "
1237                + Data.DATA3 + ", "
1238                + Data.DATA4 + ", "
1239                + Data.DATA5 + ", "
1240                + Data.DATA6 + ", "
1241                + Data.DATA7 + ", "
1242                + Data.DATA8 + ", "
1243                + Data.DATA9 + ", "
1244                + Data.DATA10 + ", "
1245                + Data.DATA11 + ", "
1246                + Data.DATA12 + ", "
1247                + Data.DATA13 + ", "
1248                + Data.DATA14 + ", "
1249                + Data.DATA15 + ", "
1250                + Data.SYNC1 + ", "
1251                + Data.SYNC2 + ", "
1252                + Data.SYNC3 + ", "
1253                + Data.SYNC4;
1254
1255        String syncColumns =
1256                RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ","
1257                + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ","
1258                + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + ","
1259                + RawContactsColumns.CONCRETE_NAME_VERIFIED + " AS " + RawContacts.NAME_VERIFIED + ","
1260                + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + ","
1261                + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + ","
1262                + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + ","
1263                + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + ","
1264                + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + ","
1265                + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4;
1266
1267        String baseContactColumns =
1268                Contacts.HAS_PHONE_NUMBER + ", "
1269                + Contacts.NAME_RAW_CONTACT_ID + ", "
1270                + Contacts.LOOKUP_KEY + ", "
1271                + Contacts.PHOTO_ID + ", "
1272                + Clauses.CONTACT_VISIBLE + " AS " + Contacts.IN_VISIBLE_GROUP + ", "
1273                + ContactsColumns.LAST_STATUS_UPDATE_ID;
1274
1275        String contactOptionColumns =
1276                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1277                        + " AS " + RawContacts.CUSTOM_RINGTONE + ","
1278                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1279                        + " AS " + RawContacts.SEND_TO_VOICEMAIL + ","
1280                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1281                        + " AS " + RawContacts.LAST_TIME_CONTACTED + ","
1282                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1283                        + " AS " + RawContacts.TIMES_CONTACTED + ","
1284                + ContactsColumns.CONCRETE_STARRED
1285                        + " AS " + RawContacts.STARRED;
1286
1287        String contactNameColumns =
1288                "name_raw_contact." + RawContacts.DISPLAY_NAME_SOURCE
1289                        + " AS " + Contacts.DISPLAY_NAME_SOURCE + ", "
1290                + "name_raw_contact." + RawContacts.DISPLAY_NAME_PRIMARY
1291                        + " AS " + Contacts.DISPLAY_NAME_PRIMARY + ", "
1292                + "name_raw_contact." + RawContacts.DISPLAY_NAME_ALTERNATIVE
1293                        + " AS " + Contacts.DISPLAY_NAME_ALTERNATIVE + ", "
1294                + "name_raw_contact." + RawContacts.PHONETIC_NAME
1295                        + " AS " + Contacts.PHONETIC_NAME + ", "
1296                + "name_raw_contact." + RawContacts.PHONETIC_NAME_STYLE
1297                        + " AS " + Contacts.PHONETIC_NAME_STYLE + ", "
1298                + "name_raw_contact." + RawContacts.SORT_KEY_PRIMARY
1299                        + " AS " + Contacts.SORT_KEY_PRIMARY + ", "
1300                + "name_raw_contact." + RawContacts.SORT_KEY_ALTERNATIVE
1301                        + " AS " + Contacts.SORT_KEY_ALTERNATIVE;
1302
1303        String dataSelect = "SELECT "
1304                + DataColumns.CONCRETE_ID + " AS " + Data._ID + ","
1305                + Data.RAW_CONTACT_ID + ", "
1306                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1307                + syncColumns + ", "
1308                + dataColumns + ", "
1309                + contactOptionColumns + ", "
1310                + contactNameColumns + ", "
1311                + baseContactColumns + ", "
1312                + buildPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1313                        Contacts.PHOTO_URI) + ", "
1314                + buildPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1315                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1316                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1317                + " FROM " + Tables.DATA
1318                + " JOIN " + Tables.MIMETYPES + " ON ("
1319                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1320                + " JOIN " + Tables.RAW_CONTACTS + " ON ("
1321                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1322                + " JOIN " + Tables.CONTACTS + " ON ("
1323                +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
1324                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1325                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
1326                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1327                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1328                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1329                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1330                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1331                        + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1332
1333        db.execSQL("CREATE VIEW " + Views.DATA_ALL + " AS " + dataSelect);
1334        db.execSQL("CREATE VIEW " + Views.DATA_RESTRICTED + " AS " + dataSelect + " WHERE "
1335                + RawContactsColumns.CONCRETE_IS_RESTRICTED + "=0");
1336
1337        String rawContactOptionColumns =
1338                RawContacts.CUSTOM_RINGTONE + ","
1339                + RawContacts.SEND_TO_VOICEMAIL + ","
1340                + RawContacts.LAST_TIME_CONTACTED + ","
1341                + RawContacts.TIMES_CONTACTED + ","
1342                + RawContacts.STARRED;
1343
1344        String rawContactsSelect = "SELECT "
1345                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ","
1346                + RawContacts.CONTACT_ID + ", "
1347                + RawContacts.AGGREGATION_MODE + ", "
1348                + RawContacts.RAW_CONTACT_IS_READ_ONLY + ", "
1349                + RawContacts.DELETED + ", "
1350                + RawContacts.DISPLAY_NAME_SOURCE  + ", "
1351                + RawContacts.DISPLAY_NAME_PRIMARY  + ", "
1352                + RawContacts.DISPLAY_NAME_ALTERNATIVE  + ", "
1353                + RawContacts.PHONETIC_NAME  + ", "
1354                + RawContacts.PHONETIC_NAME_STYLE  + ", "
1355                + RawContacts.SORT_KEY_PRIMARY  + ", "
1356                + RawContacts.SORT_KEY_ALTERNATIVE + ", "
1357                + rawContactOptionColumns + ", "
1358                + syncColumns
1359                + " FROM " + Tables.RAW_CONTACTS;
1360
1361        db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS_ALL + " AS " + rawContactsSelect);
1362        db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS_RESTRICTED + " AS " + rawContactsSelect
1363                + " WHERE " + RawContacts.IS_RESTRICTED + "=0");
1364
1365        String contactsColumns =
1366                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1367                        + " AS " + Contacts.CUSTOM_RINGTONE + ", "
1368                + contactNameColumns + ", "
1369                + baseContactColumns + ", "
1370                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1371                        + " AS " + Contacts.LAST_TIME_CONTACTED + ", "
1372                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1373                        + " AS " + Contacts.SEND_TO_VOICEMAIL + ", "
1374                + ContactsColumns.CONCRETE_STARRED
1375                        + " AS " + Contacts.STARRED + ", "
1376                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1377                        + " AS " + Contacts.TIMES_CONTACTED;
1378
1379        String contactsSelect = "SELECT "
1380                + ContactsColumns.CONCRETE_ID + " AS " + Contacts._ID + ","
1381                + contactsColumns + ", "
1382                + buildPhotoUriAlias(ContactsColumns.CONCRETE_ID, Contacts.PHOTO_URI) + ", "
1383                + buildPhotoUriAlias(ContactsColumns.CONCRETE_ID, Contacts.PHOTO_THUMBNAIL_URI)
1384                + " FROM " + Tables.CONTACTS
1385                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1386                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")";
1387
1388        db.execSQL("CREATE VIEW " + Views.CONTACTS_ALL + " AS " + contactsSelect);
1389        db.execSQL("CREATE VIEW " + Views.CONTACTS_RESTRICTED + " AS " + contactsSelect
1390                + " WHERE " + ContactsColumns.SINGLE_IS_RESTRICTED + "=0");
1391
1392        String rawEntitiesSelect = "SELECT "
1393                + RawContacts.CONTACT_ID + ", "
1394                + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
1395                + dataColumns + ", "
1396                + syncColumns + ", "
1397                + Data.SYNC1 + ", "
1398                + Data.SYNC2 + ", "
1399                + Data.SYNC3 + ", "
1400                + Data.SYNC4 + ", "
1401                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ", "
1402                + DataColumns.CONCRETE_ID + " AS " + RawContacts.Entity.DATA_ID + ","
1403                + RawContactsColumns.CONCRETE_STARRED + " AS " + RawContacts.STARRED + ","
1404                + RawContactsColumns.CONCRETE_IS_RESTRICTED + " AS "
1405                        + RawContacts.IS_RESTRICTED + ","
1406                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1407                + " FROM " + Tables.RAW_CONTACTS
1408                + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
1409                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1410                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1411                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1412                + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
1413                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1414                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1415                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1416                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1417                + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1418
1419        db.execSQL("CREATE VIEW " + Views.RAW_ENTITIES + " AS "
1420                + rawEntitiesSelect);
1421        db.execSQL("CREATE VIEW " + Views.RAW_ENTITIES_RESTRICTED + " AS "
1422                + rawEntitiesSelect + " WHERE " + RawContacts.IS_RESTRICTED + "=0");
1423
1424        String entitiesSelect = "SELECT "
1425                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + Contacts._ID + ", "
1426                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1427                + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
1428                + RawContactsColumns.CONCRETE_IS_RESTRICTED
1429                        + " AS " + RawContacts.IS_RESTRICTED + ","
1430                + dataColumns + ", "
1431                + syncColumns + ", "
1432                + contactsColumns + ", "
1433                + buildPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1434                        Contacts.PHOTO_URI) + ", "
1435                + buildPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1436                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1437                + Data.SYNC1 + ", "
1438                + Data.SYNC2 + ", "
1439                + Data.SYNC3 + ", "
1440                + Data.SYNC4 + ", "
1441                + RawContactsColumns.CONCRETE_ID + " AS " + Contacts.Entity.RAW_CONTACT_ID + ", "
1442                + DataColumns.CONCRETE_ID + " AS " + Contacts.Entity.DATA_ID + ","
1443                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1444                + " FROM " + Tables.RAW_CONTACTS
1445                + " JOIN " + Tables.CONTACTS + " ON ("
1446                +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
1447                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1448                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
1449                + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
1450                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1451                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1452                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1453                + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
1454                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1455                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1456                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1457                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1458                + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1459
1460        db.execSQL("CREATE VIEW " + Views.ENTITIES + " AS "
1461                + entitiesSelect);
1462        db.execSQL("CREATE VIEW " + Views.ENTITIES_RESTRICTED + " AS "
1463                + entitiesSelect + " WHERE " + RawContactsColumns.CONCRETE_IS_RESTRICTED + "=0");
1464    }
1465
1466    private static String buildPhotoUriAlias(String contactIdColumn, String alias) {
1467        return "(CASE WHEN " + Contacts.PHOTO_ID + " IS NULL"
1468                + " OR " + Contacts.PHOTO_ID + "=0"
1469                + " THEN NULL"
1470                + " ELSE " + "'" + Contacts.CONTENT_URI + "/'||"
1471                        + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'"
1472                + " END)"
1473                + " AS " + alias;
1474    }
1475
1476    private static void createGroupsView(SQLiteDatabase db) {
1477        db.execSQL("DROP VIEW IF EXISTS " + Views.GROUPS_ALL + ";");
1478        String groupsColumns =
1479                Groups.ACCOUNT_NAME + ","
1480                + Groups.ACCOUNT_TYPE + ","
1481                + Groups.SOURCE_ID + ","
1482                + Groups.VERSION + ","
1483                + Groups.DIRTY + ","
1484                + Groups.TITLE + ","
1485                + Groups.TITLE_RES + ","
1486                + Groups.NOTES + ","
1487                + Groups.SYSTEM_ID + ","
1488                + Groups.DELETED + ","
1489                + Groups.GROUP_VISIBLE + ","
1490                + Groups.SHOULD_SYNC + ","
1491                + Groups.AUTO_ADD + ","
1492                + Groups.FAVORITES + ","
1493                + Groups.GROUP_IS_READ_ONLY + ","
1494                + Groups.SYNC1 + ","
1495                + Groups.SYNC2 + ","
1496                + Groups.SYNC3 + ","
1497                + Groups.SYNC4 + ","
1498                + PackagesColumns.PACKAGE + " AS " + Groups.RES_PACKAGE;
1499
1500        String groupsSelect = "SELECT "
1501                + GroupsColumns.CONCRETE_ID + " AS " + Groups._ID + ","
1502                + groupsColumns
1503                + " FROM " + Tables.GROUPS_JOIN_PACKAGES;
1504
1505        db.execSQL("CREATE VIEW " + Views.GROUPS_ALL + " AS " + groupsSelect);
1506    }
1507
1508    @Override
1509    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1510        if (oldVersion < 99) {
1511            Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion
1512                    + ", data will be lost!");
1513
1514            db.execSQL("DROP TABLE IF EXISTS " + Tables.CONTACTS + ";");
1515            db.execSQL("DROP TABLE IF EXISTS " + Tables.RAW_CONTACTS + ";");
1516            db.execSQL("DROP TABLE IF EXISTS " + Tables.PACKAGES + ";");
1517            db.execSQL("DROP TABLE IF EXISTS " + Tables.MIMETYPES + ";");
1518            db.execSQL("DROP TABLE IF EXISTS " + Tables.DATA + ";");
1519            db.execSQL("DROP TABLE IF EXISTS " + Tables.PHONE_LOOKUP + ";");
1520            db.execSQL("DROP TABLE IF EXISTS " + Tables.NAME_LOOKUP + ";");
1521            db.execSQL("DROP TABLE IF EXISTS " + Tables.NICKNAME_LOOKUP + ";");
1522            db.execSQL("DROP TABLE IF EXISTS " + Tables.GROUPS + ";");
1523            db.execSQL("DROP TABLE IF EXISTS " + Tables.ACTIVITIES + ";");
1524            db.execSQL("DROP TABLE IF EXISTS " + Tables.CALLS + ";");
1525            db.execSQL("DROP TABLE IF EXISTS " + Tables.SETTINGS + ";");
1526            db.execSQL("DROP TABLE IF EXISTS " + Tables.STATUS_UPDATES + ";");
1527
1528            // TODO: we should not be dropping agg_exceptions and contact_options. In case that
1529            // table's schema changes, we should try to preserve the data, because it was entered
1530            // by the user and has never been synched to the server.
1531            db.execSQL("DROP TABLE IF EXISTS " + Tables.AGGREGATION_EXCEPTIONS + ";");
1532
1533            onCreate(db);
1534            return;
1535        }
1536
1537        Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion);
1538
1539        boolean upgradeViewsAndTriggers = false;
1540        boolean upgradeNameLookup = false;
1541        boolean upgradeLegacyApiSupport = false;
1542        boolean upgradeSearchIndex = false;
1543
1544        if (oldVersion == 99) {
1545            upgradeViewsAndTriggers = true;
1546            oldVersion++;
1547        }
1548
1549        if (oldVersion == 100) {
1550            db.execSQL("CREATE INDEX IF NOT EXISTS mimetypes_mimetype_index ON "
1551                    + Tables.MIMETYPES + " ("
1552                            + MimetypesColumns.MIMETYPE + ","
1553                            + MimetypesColumns._ID + ");");
1554            updateIndexStats(db, Tables.MIMETYPES,
1555                    "mimetypes_mimetype_index", "50 1 1");
1556
1557            upgradeViewsAndTriggers = true;
1558            oldVersion++;
1559        }
1560
1561        if (oldVersion == 101) {
1562            upgradeViewsAndTriggers = true;
1563            oldVersion++;
1564        }
1565
1566        if (oldVersion == 102) {
1567            upgradeViewsAndTriggers = true;
1568            oldVersion++;
1569        }
1570
1571        if (oldVersion == 103) {
1572            upgradeViewsAndTriggers = true;
1573            oldVersion++;
1574        }
1575
1576        if (oldVersion == 104 || oldVersion == 201) {
1577            LegacyApiSupport.createSettingsTable(db);
1578            upgradeViewsAndTriggers = true;
1579            oldVersion++;
1580        }
1581
1582        if (oldVersion == 105) {
1583            upgradeToVersion202(db);
1584            upgradeNameLookup = true;
1585            oldVersion = 202;
1586        }
1587
1588        if (oldVersion == 202) {
1589            upgradeToVersion203(db);
1590            upgradeViewsAndTriggers = true;
1591            oldVersion++;
1592        }
1593
1594        if (oldVersion == 203) {
1595            upgradeViewsAndTriggers = true;
1596            oldVersion++;
1597        }
1598
1599        if (oldVersion == 204) {
1600            upgradeToVersion205(db);
1601            upgradeViewsAndTriggers = true;
1602            oldVersion++;
1603        }
1604
1605        if (oldVersion == 205) {
1606            upgrateToVersion206(db);
1607            upgradeViewsAndTriggers = true;
1608            oldVersion++;
1609        }
1610
1611        if (oldVersion == 206) {
1612            upgradeToVersion300(db);
1613            oldVersion = 300;
1614        }
1615
1616        if (oldVersion == 300) {
1617            upgradeViewsAndTriggers = true;
1618            oldVersion = 301;
1619        }
1620
1621        if (oldVersion == 301) {
1622            upgradeViewsAndTriggers = true;
1623            oldVersion = 302;
1624        }
1625
1626        if (oldVersion == 302) {
1627            upgradeEmailToVersion303(db);
1628            upgradeNicknameToVersion303(db);
1629            oldVersion = 303;
1630        }
1631
1632        if (oldVersion == 303) {
1633            upgradeToVersion304(db);
1634            oldVersion = 304;
1635        }
1636
1637        if (oldVersion == 304) {
1638            upgradeNameLookup = true;
1639            oldVersion = 305;
1640        }
1641
1642        if (oldVersion == 305) {
1643            upgradeToVersion306(db);
1644            oldVersion = 306;
1645        }
1646
1647        if (oldVersion == 306) {
1648            upgradeToVersion307(db);
1649            oldVersion = 307;
1650        }
1651
1652        if (oldVersion == 307) {
1653            upgradeToVersion308(db);
1654            oldVersion = 308;
1655        }
1656
1657        // Gingerbread upgrades
1658        if (oldVersion < 350) {
1659            upgradeViewsAndTriggers = true;
1660            oldVersion = 351;
1661        }
1662
1663        if (oldVersion == 351) {
1664            upgradeNameLookup = true;
1665            oldVersion = 352;
1666        }
1667
1668        if (oldVersion == 352) {
1669            upgradeToVersion353(db);
1670            oldVersion = 353;
1671        }
1672
1673        // Honeycomb upgrades
1674        if (oldVersion < 400) {
1675            upgradeViewsAndTriggers = true;
1676            upgradeToVersion400(db);
1677            oldVersion = 400;
1678        }
1679
1680        if (oldVersion == 400) {
1681            upgradeViewsAndTriggers = true;
1682            upgradeToVersion401(db);
1683            oldVersion = 401;
1684        }
1685
1686        if (oldVersion == 401) {
1687            upgradeToVersion402(db);
1688            oldVersion = 402;
1689        }
1690
1691        if (oldVersion == 402) {
1692            upgradeViewsAndTriggers = true;
1693            upgradeToVersion403(db);
1694            oldVersion = 403;
1695        }
1696
1697        if (oldVersion == 403) {
1698            upgradeViewsAndTriggers = true;
1699            oldVersion = 404;
1700        }
1701
1702        if (oldVersion == 404) {
1703            upgradeViewsAndTriggers = true;
1704            upgradeToVersion405(db);
1705            oldVersion = 405;
1706        }
1707
1708        if (oldVersion == 405) {
1709            upgradeViewsAndTriggers = true;
1710            upgradeToVersion406(db);
1711            oldVersion = 406;
1712        }
1713
1714        if (oldVersion == 406) {
1715            upgradeViewsAndTriggers = true;
1716            oldVersion = 407;
1717        }
1718
1719        if (oldVersion == 407) {
1720            // Obsolete
1721            oldVersion = 408;
1722        }
1723
1724        if (oldVersion == 408) {
1725            upgradeViewsAndTriggers = true;
1726            upgradeToVersion409(db);
1727            oldVersion = 409;
1728        }
1729
1730        if (oldVersion == 409) {
1731            upgradeViewsAndTriggers = true;
1732            oldVersion = 410;
1733        }
1734
1735        if (oldVersion == 410) {
1736            upgradeToVersion411(db);
1737            oldVersion = 411;
1738        }
1739
1740        if (oldVersion == 411) {
1741            // Same upgrade as 353, only on Honeycomb devices
1742            upgradeToVersion353(db);
1743            oldVersion = 412;
1744        }
1745
1746        if (oldVersion == 412) {
1747            upgradeToVersion413(db);
1748            oldVersion = 413;
1749        }
1750
1751        if (oldVersion == 413) {
1752            upgradeNameLookup = true;
1753            oldVersion = 414;
1754        }
1755
1756        if (oldVersion == 414) {
1757            upgradeToVersion415(db);
1758            upgradeViewsAndTriggers = true;
1759            oldVersion = 415;
1760        }
1761
1762        if (oldVersion == 415) {
1763            upgradeToVersion416(db);
1764            oldVersion = 416;
1765        }
1766
1767        if (oldVersion == 416) {
1768            upgradeLegacyApiSupport = true;
1769            oldVersion = 417;
1770        }
1771
1772        // Honeycomb-MR1 upgrades
1773        if (oldVersion < 500) {
1774            upgradeSearchIndex = true;
1775        }
1776
1777        if (oldVersion < 501) {
1778            upgradeSearchIndex = true;
1779            upgradeToVersion501(db);
1780            oldVersion = 501;
1781        }
1782
1783        if (oldVersion < 502) {
1784            upgradeSearchIndex = true;
1785            upgradeToVersion502(db);
1786            oldVersion = 502;
1787        }
1788
1789        if (oldVersion < 503) {
1790            upgradeSearchIndex = true;
1791            oldVersion = 503;
1792        }
1793
1794        if (upgradeViewsAndTriggers) {
1795            createContactsViews(db);
1796            createGroupsView(db);
1797            createContactsTriggers(db);
1798            createContactsIndexes(db);
1799            updateSqliteStats(db);
1800            upgradeLegacyApiSupport = true;
1801            mReopenDatabase = true;
1802        }
1803
1804        if (upgradeLegacyApiSupport) {
1805            LegacyApiSupport.createViews(db);
1806        }
1807
1808        if (upgradeNameLookup) {
1809            rebuildNameLookup(db);
1810        }
1811
1812        if (upgradeSearchIndex) {
1813            setProperty(db, SearchIndexManager.PROPERTY_SEARCH_INDEX_VERSION, "0");
1814        }
1815
1816        if (oldVersion != newVersion) {
1817            throw new IllegalStateException(
1818                    "error upgrading the database to version " + newVersion);
1819        }
1820    }
1821
1822    private void upgradeToVersion202(SQLiteDatabase db) {
1823        db.execSQL(
1824                "ALTER TABLE " + Tables.PHONE_LOOKUP +
1825                " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;");
1826
1827        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
1828                PhoneLookupColumns.MIN_MATCH + "," +
1829                PhoneLookupColumns.RAW_CONTACT_ID + "," +
1830                PhoneLookupColumns.DATA_ID +
1831        ");");
1832
1833        updateIndexStats(db, Tables.PHONE_LOOKUP,
1834                "phone_lookup_min_match_index", "10000 2 2 1");
1835
1836        SQLiteStatement update = db.compileStatement(
1837                "UPDATE " + Tables.PHONE_LOOKUP +
1838                " SET " + PhoneLookupColumns.MIN_MATCH + "=?" +
1839                " WHERE " + PhoneLookupColumns.DATA_ID + "=?");
1840
1841        // Populate the new column
1842        Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA +
1843                " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")",
1844                new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null);
1845        try {
1846            while (c.moveToNext()) {
1847                long dataId = c.getLong(0);
1848                String number = c.getString(1);
1849                if (!TextUtils.isEmpty(number)) {
1850                    update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number));
1851                    update.bindLong(2, dataId);
1852                    update.execute();
1853                }
1854            }
1855        } finally {
1856            c.close();
1857        }
1858    }
1859
1860    private void upgradeToVersion203(SQLiteDatabase db) {
1861        // Garbage-collect first. A bug in Eclair was sometimes leaving
1862        // raw_contacts in the database that no longer had contacts associated
1863        // with them.  To avoid failures during this database upgrade, drop
1864        // the orphaned raw_contacts.
1865        db.execSQL(
1866                "DELETE FROM raw_contacts" +
1867                " WHERE contact_id NOT NULL" +
1868                " AND contact_id NOT IN (SELECT _id FROM contacts)");
1869
1870        db.execSQL(
1871                "ALTER TABLE " + Tables.CONTACTS +
1872                " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)");
1873        db.execSQL(
1874                "ALTER TABLE " + Tables.RAW_CONTACTS +
1875                " ADD contact_in_visible_group INTEGER NOT NULL DEFAULT 0");
1876
1877        // For each Contact, find the RawContact that contributed the display name
1878        db.execSQL(
1879                "UPDATE " + Tables.CONTACTS +
1880                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
1881                        " SELECT " + RawContacts._ID +
1882                        " FROM " + Tables.RAW_CONTACTS +
1883                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
1884                        " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" +
1885                                Tables.CONTACTS + "." + Contacts.DISPLAY_NAME +
1886                        " ORDER BY " + RawContacts._ID +
1887                        " LIMIT 1)"
1888        );
1889
1890        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
1891                Contacts.NAME_RAW_CONTACT_ID +
1892        ");");
1893
1894        // If for some unknown reason we missed some names, let's make sure there are
1895        // no contacts without a name, picking a raw contact "at random".
1896        db.execSQL(
1897                "UPDATE " + Tables.CONTACTS +
1898                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
1899                        " SELECT " + RawContacts._ID +
1900                        " FROM " + Tables.RAW_CONTACTS +
1901                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
1902                        " ORDER BY " + RawContacts._ID +
1903                        " LIMIT 1)" +
1904                " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL"
1905        );
1906
1907        // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use.
1908        db.execSQL(
1909                "UPDATE " + Tables.CONTACTS +
1910                " SET " + Contacts.DISPLAY_NAME + "=NULL"
1911        );
1912
1913        // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow
1914        // indexing on (display_name, in_visible_group)
1915        db.execSQL(
1916                "UPDATE " + Tables.RAW_CONTACTS +
1917                " SET contact_in_visible_group=(" +
1918                        "SELECT " + Contacts.IN_VISIBLE_GROUP +
1919                        " FROM " + Tables.CONTACTS +
1920                        " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" +
1921                " WHERE " + RawContacts.CONTACT_ID + " NOT NULL"
1922        );
1923
1924        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
1925                "contact_in_visible_group" + "," +
1926                RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" +
1927        ");");
1928
1929        db.execSQL("DROP INDEX contacts_visible_index");
1930        db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
1931                Contacts.IN_VISIBLE_GROUP +
1932        ");");
1933    }
1934
1935    private void upgradeToVersion205(SQLiteDatabase db) {
1936        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1937                + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;");
1938        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1939                + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;");
1940        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1941                + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;");
1942        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1943                + " ADD " + RawContacts.SORT_KEY_PRIMARY
1944                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
1945        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1946                + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE
1947                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
1948
1949        final Locale locale = Locale.getDefault();
1950
1951        NameSplitter splitter = createNameSplitter();
1952
1953        SQLiteStatement rawContactUpdate = db.compileStatement(
1954                "UPDATE " + Tables.RAW_CONTACTS +
1955                " SET " +
1956                        RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
1957                        RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
1958                        RawContacts.PHONETIC_NAME + "=?," +
1959                        RawContacts.PHONETIC_NAME_STYLE + "=?," +
1960                        RawContacts.SORT_KEY_PRIMARY + "=?," +
1961                        RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
1962                " WHERE " + RawContacts._ID + "=?");
1963
1964        upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter);
1965        upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter);
1966
1967        db.execSQL("DROP INDEX raw_contact_sort_key1_index");
1968        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
1969                "contact_in_visible_group" + "," +
1970                RawContacts.SORT_KEY_PRIMARY +
1971        ");");
1972
1973        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
1974                "contact_in_visible_group" + "," +
1975                RawContacts.SORT_KEY_ALTERNATIVE +
1976        ");");
1977    }
1978
1979    private interface StructName205Query {
1980        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
1981
1982        String COLUMNS[] = {
1983                DataColumns.CONCRETE_ID,
1984                Data.RAW_CONTACT_ID,
1985                RawContacts.DISPLAY_NAME_SOURCE,
1986                RawContacts.DISPLAY_NAME_PRIMARY,
1987                StructuredName.PREFIX,
1988                StructuredName.GIVEN_NAME,
1989                StructuredName.MIDDLE_NAME,
1990                StructuredName.FAMILY_NAME,
1991                StructuredName.SUFFIX,
1992                StructuredName.PHONETIC_FAMILY_NAME,
1993                StructuredName.PHONETIC_MIDDLE_NAME,
1994                StructuredName.PHONETIC_GIVEN_NAME,
1995        };
1996
1997        int ID = 0;
1998        int RAW_CONTACT_ID = 1;
1999        int DISPLAY_NAME_SOURCE = 2;
2000        int DISPLAY_NAME = 3;
2001        int PREFIX = 4;
2002        int GIVEN_NAME = 5;
2003        int MIDDLE_NAME = 6;
2004        int FAMILY_NAME = 7;
2005        int SUFFIX = 8;
2006        int PHONETIC_FAMILY_NAME = 9;
2007        int PHONETIC_MIDDLE_NAME = 10;
2008        int PHONETIC_GIVEN_NAME = 11;
2009    }
2010
2011    private void upgradeStructuredNamesToVersion205(SQLiteDatabase db,
2012            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2013
2014        // Process structured names to detect the style of the full name and phonetic name
2015
2016        long mMimeType;
2017        try {
2018            mMimeType = DatabaseUtils.longForQuery(db,
2019                    "SELECT " + MimetypesColumns._ID +
2020                    " FROM " + Tables.MIMETYPES +
2021                    " WHERE " + MimetypesColumns.MIMETYPE
2022                            + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null);
2023        } catch (SQLiteDoneException e) {
2024            // No structured names in the database
2025            return;
2026        }
2027
2028        SQLiteStatement structuredNameUpdate = db.compileStatement(
2029                "UPDATE " + Tables.DATA +
2030                " SET " +
2031                        StructuredName.FULL_NAME_STYLE + "=?," +
2032                        StructuredName.DISPLAY_NAME + "=?," +
2033                        StructuredName.PHONETIC_NAME_STYLE + "=?" +
2034                " WHERE " + Data._ID + "=?");
2035
2036        NameSplitter.Name name = new NameSplitter.Name();
2037        StringBuilder sb = new StringBuilder();
2038        Cursor cursor = db.query(StructName205Query.TABLE,
2039                StructName205Query.COLUMNS,
2040                DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null);
2041        try {
2042            while (cursor.moveToNext()) {
2043                long dataId = cursor.getLong(StructName205Query.ID);
2044                long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID);
2045                int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE);
2046                String displayName = cursor.getString(StructName205Query.DISPLAY_NAME);
2047
2048                name.clear();
2049                name.prefix = cursor.getString(StructName205Query.PREFIX);
2050                name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME);
2051                name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME);
2052                name.familyName = cursor.getString(StructName205Query.FAMILY_NAME);
2053                name.suffix = cursor.getString(StructName205Query.SUFFIX);
2054                name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME);
2055                name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME);
2056                name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME);
2057
2058                upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name,
2059                        structuredNameUpdate, rawContactUpdate, splitter, sb);
2060            }
2061        } finally {
2062            cursor.close();
2063        }
2064    }
2065
2066    private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource,
2067            String currentDisplayName, NameSplitter.Name name,
2068            SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate,
2069            NameSplitter splitter, StringBuilder sb) {
2070
2071        splitter.guessNameStyle(name);
2072        int unadjustedFullNameStyle = name.fullNameStyle;
2073        name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle);
2074        String displayName = splitter.join(name, true);
2075
2076        // Don't update database with the adjusted fullNameStyle as it is locale
2077        // related
2078        structuredNameUpdate.bindLong(1, unadjustedFullNameStyle);
2079        DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName);
2080        structuredNameUpdate.bindLong(3, name.phoneticNameStyle);
2081        structuredNameUpdate.bindLong(4, dataId);
2082        structuredNameUpdate.execute();
2083
2084        if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) {
2085            String displayNameAlternative = splitter.join(name, false);
2086            String phoneticName = splitter.joinPhoneticName(name);
2087            String sortKey = null;
2088            String sortKeyAlternative = null;
2089
2090            if (phoneticName != null) {
2091                sortKey = sortKeyAlternative = phoneticName;
2092            } else if (name.fullNameStyle == FullNameStyle.CHINESE ||
2093                    name.fullNameStyle == FullNameStyle.CJK) {
2094                sortKey = sortKeyAlternative = ContactLocaleUtils.getIntance()
2095                        .getSortKey(displayName, name.fullNameStyle);
2096            }
2097
2098            if (sortKey == null) {
2099                sortKey = displayName;
2100                sortKeyAlternative = displayNameAlternative;
2101            }
2102
2103            updateRawContact205(rawContactUpdate, rawContactId, displayName,
2104                    displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey,
2105                    sortKeyAlternative);
2106        }
2107    }
2108
2109    private interface Organization205Query {
2110        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
2111
2112        String COLUMNS[] = {
2113                DataColumns.CONCRETE_ID,
2114                Data.RAW_CONTACT_ID,
2115                Organization.COMPANY,
2116                Organization.PHONETIC_NAME,
2117        };
2118
2119        int ID = 0;
2120        int RAW_CONTACT_ID = 1;
2121        int COMPANY = 2;
2122        int PHONETIC_NAME = 3;
2123    }
2124
2125    private void upgradeOrganizationsToVersion205(SQLiteDatabase db,
2126            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2127        final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE);
2128
2129        SQLiteStatement organizationUpdate = db.compileStatement(
2130                "UPDATE " + Tables.DATA +
2131                " SET " +
2132                        Organization.PHONETIC_NAME_STYLE + "=?" +
2133                " WHERE " + Data._ID + "=?");
2134
2135        Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS,
2136                DataColumns.MIMETYPE_ID + "=" + mimeType + " AND "
2137                        + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION,
2138                null, null, null, null);
2139        try {
2140            while (cursor.moveToNext()) {
2141                long dataId = cursor.getLong(Organization205Query.ID);
2142                long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID);
2143                String company = cursor.getString(Organization205Query.COMPANY);
2144                String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME);
2145
2146                int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName);
2147
2148                organizationUpdate.bindLong(1, phoneticNameStyle);
2149                organizationUpdate.bindLong(2, dataId);
2150                organizationUpdate.execute();
2151
2152                String sortKey = null;
2153                if (phoneticName == null && company != null) {
2154                    int nameStyle = splitter.guessFullNameStyle(company);
2155                    nameStyle = splitter.getAdjustedFullNameStyle(nameStyle);
2156                    if (nameStyle == FullNameStyle.CHINESE ||
2157                            nameStyle == FullNameStyle.CJK ) {
2158                        sortKey = ContactLocaleUtils.getIntance()
2159                                .getSortKey(company, nameStyle);
2160                    }
2161                }
2162
2163                if (sortKey == null) {
2164                    sortKey = company;
2165                }
2166
2167                updateRawContact205(rawContactUpdate, rawContactId, company,
2168                        company, phoneticNameStyle, phoneticName, sortKey, sortKey);
2169            }
2170        } finally {
2171            cursor.close();
2172        }
2173    }
2174
2175    private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId,
2176            String displayName, String displayNameAlternative, int phoneticNameStyle,
2177            String phoneticName, String sortKeyPrimary, String sortKeyAlternative) {
2178        bindString(rawContactUpdate, 1, displayName);
2179        bindString(rawContactUpdate, 2, displayNameAlternative);
2180        bindString(rawContactUpdate, 3, phoneticName);
2181        rawContactUpdate.bindLong(4, phoneticNameStyle);
2182        bindString(rawContactUpdate, 5, sortKeyPrimary);
2183        bindString(rawContactUpdate, 6, sortKeyAlternative);
2184        rawContactUpdate.bindLong(7, rawContactId);
2185        rawContactUpdate.execute();
2186    }
2187
2188    private void upgrateToVersion206(SQLiteDatabase db) {
2189        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2190                + " ADD " + RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0;");
2191    }
2192
2193    /**
2194     * Fix for the bug where name lookup records for organizations would get removed by
2195     * unrelated updates of the data rows.
2196     */
2197    private void upgradeToVersion300(SQLiteDatabase db) {
2198        // No longer needed
2199    }
2200
2201    private static final class Upgrade303Query {
2202        public static final String TABLE = Tables.DATA;
2203
2204        public static final String SELECTION =
2205                DataColumns.MIMETYPE_ID + "=?" +
2206                    " AND " + Data._ID + " NOT IN " +
2207                    "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" +
2208                    " AND " + Data.DATA1 + " NOT NULL";
2209
2210        public static final String COLUMNS[] = {
2211                Data._ID,
2212                Data.RAW_CONTACT_ID,
2213                Data.DATA1,
2214        };
2215
2216        public static final int ID = 0;
2217        public static final int RAW_CONTACT_ID = 1;
2218        public static final int DATA1 = 2;
2219    }
2220
2221    /**
2222     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2223     * emails during the sync.  We need to restore the lost name lookup rows.
2224     */
2225    private void upgradeEmailToVersion303(SQLiteDatabase db) {
2226        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2227        if (mimeTypeId == -1) {
2228            return;
2229        }
2230
2231        ContentValues values = new ContentValues();
2232
2233        // Find all data rows with the mime type "email" that are missing name lookup
2234        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2235                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2236                null, null, null);
2237        try {
2238            while (cursor.moveToNext()) {
2239                long dataId = cursor.getLong(Upgrade303Query.ID);
2240                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2241                String value = cursor.getString(Upgrade303Query.DATA1);
2242                value = extractHandleFromEmailAddress(value);
2243
2244                if (value != null) {
2245                    values.put(NameLookupColumns.DATA_ID, dataId);
2246                    values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2247                    values.put(NameLookupColumns.NAME_TYPE, NameLookupType.EMAIL_BASED_NICKNAME);
2248                    values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2249                    db.insert(Tables.NAME_LOOKUP, null, values);
2250                }
2251            }
2252        } finally {
2253            cursor.close();
2254        }
2255    }
2256
2257    /**
2258     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2259     * nicknames during the sync.  We need to restore the lost name lookup rows.
2260     */
2261    private void upgradeNicknameToVersion303(SQLiteDatabase db) {
2262        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
2263        if (mimeTypeId == -1) {
2264            return;
2265        }
2266
2267        ContentValues values = new ContentValues();
2268
2269        // Find all data rows with the mime type "nickname" that are missing name lookup
2270        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2271                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2272                null, null, null);
2273        try {
2274            while (cursor.moveToNext()) {
2275                long dataId = cursor.getLong(Upgrade303Query.ID);
2276                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2277                String value = cursor.getString(Upgrade303Query.DATA1);
2278
2279                values.put(NameLookupColumns.DATA_ID, dataId);
2280                values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2281                values.put(NameLookupColumns.NAME_TYPE, NameLookupType.NICKNAME);
2282                values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2283                db.insert(Tables.NAME_LOOKUP, null, values);
2284            }
2285        } finally {
2286            cursor.close();
2287        }
2288    }
2289
2290    private void upgradeToVersion304(SQLiteDatabase db) {
2291        // Mimetype table requires an index on mime type
2292        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" +
2293                MimetypesColumns.MIMETYPE +
2294        ");");
2295    }
2296
2297    private void upgradeToVersion306(SQLiteDatabase db) {
2298        // Fix invalid lookup that was used for Exchange contacts (it was not escaped)
2299        // It happened when a new contact was created AND synchronized
2300        final StringBuilder lookupKeyBuilder = new StringBuilder();
2301        final SQLiteStatement updateStatement = db.compileStatement(
2302                "UPDATE contacts " +
2303                "SET lookup=? " +
2304                "WHERE _id=?");
2305        final Cursor contactIdCursor = db.rawQuery(
2306                "SELECT DISTINCT contact_id " +
2307                "FROM raw_contacts " +
2308                "WHERE deleted=0 AND account_type='com.android.exchange'",
2309                null);
2310        try {
2311            while (contactIdCursor.moveToNext()) {
2312                final long contactId = contactIdCursor.getLong(0);
2313                lookupKeyBuilder.setLength(0);
2314                final Cursor c = db.rawQuery(
2315                        "SELECT account_type, account_name, _id, sourceid, display_name " +
2316                        "FROM raw_contacts " +
2317                        "WHERE contact_id=? " +
2318                        "ORDER BY _id",
2319                        new String[] { String.valueOf(contactId) });
2320                try {
2321                    while (c.moveToNext()) {
2322                        ContactLookupKey.appendToLookupKey(lookupKeyBuilder,
2323                                c.getString(0),
2324                                c.getString(1),
2325                                c.getLong(2),
2326                                c.getString(3),
2327                                c.getString(4));
2328                    }
2329                } finally {
2330                    c.close();
2331                }
2332
2333                if (lookupKeyBuilder.length() == 0) {
2334                    updateStatement.bindNull(1);
2335                } else {
2336                    updateStatement.bindString(1, Uri.encode(lookupKeyBuilder.toString()));
2337                }
2338                updateStatement.bindLong(2, contactId);
2339
2340                updateStatement.execute();
2341            }
2342        } finally {
2343            updateStatement.close();
2344            contactIdCursor.close();
2345        }
2346    }
2347
2348    private void upgradeToVersion307(SQLiteDatabase db) {
2349        db.execSQL("CREATE TABLE properties (" +
2350                "property_key TEXT PRIMARY_KEY, " +
2351                "property_value TEXT" +
2352        ");");
2353    }
2354
2355    private void upgradeToVersion308(SQLiteDatabase db) {
2356        db.execSQL("CREATE TABLE accounts (" +
2357                "account_name TEXT, " +
2358                "account_type TEXT " +
2359        ");");
2360
2361        db.execSQL("INSERT INTO accounts " +
2362                "SELECT DISTINCT account_name, account_type FROM raw_contacts");
2363    }
2364
2365    private void upgradeToVersion400(SQLiteDatabase db) {
2366        db.execSQL("ALTER TABLE " + Tables.GROUPS
2367                + " ADD " + Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0;");
2368        db.execSQL("ALTER TABLE " + Tables.GROUPS
2369                + " ADD " + Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0;");
2370    }
2371
2372    private void upgradeToVersion353(SQLiteDatabase db) {
2373        db.execSQL("DELETE FROM contacts " +
2374                "WHERE NOT EXISTS (SELECT 1 FROM raw_contacts WHERE contact_id=contacts._id)");
2375    }
2376
2377    private void rebuildNameLookup(SQLiteDatabase db) {
2378        db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2379        insertNameLookup(db);
2380        createContactsIndexes(db);
2381    }
2382
2383    /**
2384     * Regenerates all locale-sensitive data: nickname_lookup, name_lookup and sort keys.
2385     */
2386    public void setLocale(ContactsProvider2 provider, Locale locale) {
2387        Log.i(TAG, "Switching to locale " + locale);
2388
2389        long start = SystemClock.uptimeMillis();
2390        SQLiteDatabase db = getWritableDatabase();
2391        db.setLocale(locale);
2392        db.beginTransaction();
2393        try {
2394            db.execSQL("DROP INDEX raw_contact_sort_key1_index");
2395            db.execSQL("DROP INDEX raw_contact_sort_key2_index");
2396            db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2397
2398            loadNicknameLookupTable(db);
2399            insertNameLookup(db);
2400            rebuildSortKeys(db, provider);
2401            createContactsIndexes(db);
2402            db.setTransactionSuccessful();
2403        } finally {
2404            db.endTransaction();
2405        }
2406
2407        Log.i(TAG, "Locale change completed in " + (SystemClock.uptimeMillis() - start) + "ms");
2408    }
2409
2410    /**
2411     * Regenerates sort keys for all contacts.
2412     */
2413    private void rebuildSortKeys(SQLiteDatabase db, ContactsProvider2 provider) {
2414        Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID},
2415                null, null, null, null, null);
2416        try {
2417            while (cursor.moveToNext()) {
2418                long rawContactId = cursor.getLong(0);
2419                provider.updateRawContactDisplayName(db, rawContactId);
2420            }
2421        } finally {
2422            cursor.close();
2423        }
2424    }
2425
2426    private void insertNameLookup(SQLiteDatabase db) {
2427        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP);
2428
2429        SQLiteStatement nameLookupInsert = db.compileStatement(
2430                "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
2431                        + NameLookupColumns.RAW_CONTACT_ID + ","
2432                        + NameLookupColumns.DATA_ID + ","
2433                        + NameLookupColumns.NAME_TYPE + ","
2434                        + NameLookupColumns.NORMALIZED_NAME +
2435                ") VALUES (?,?,?,?)");
2436
2437        try {
2438            insertStructuredNameLookup(db, nameLookupInsert);
2439            insertEmailLookup(db, nameLookupInsert);
2440            insertNicknameLookup(db, nameLookupInsert);
2441        } finally {
2442            nameLookupInsert.close();
2443        }
2444    }
2445
2446    private static final class StructuredNameQuery {
2447        public static final String TABLE = Tables.DATA;
2448
2449        public static final String SELECTION =
2450                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2451
2452        public static final String COLUMNS[] = {
2453                StructuredName._ID,
2454                StructuredName.RAW_CONTACT_ID,
2455                StructuredName.DISPLAY_NAME,
2456        };
2457
2458        public static final int ID = 0;
2459        public static final int RAW_CONTACT_ID = 1;
2460        public static final int DISPLAY_NAME = 2;
2461    }
2462
2463    private class StructuredNameLookupBuilder extends NameLookupBuilder {
2464
2465        private final SQLiteStatement mNameLookupInsert;
2466        private final CommonNicknameCache mCommonNicknameCache;
2467
2468        public StructuredNameLookupBuilder(NameSplitter splitter,
2469                CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) {
2470            super(splitter);
2471            this.mCommonNicknameCache = commonNicknameCache;
2472            this.mNameLookupInsert = nameLookupInsert;
2473        }
2474
2475        @Override
2476        protected void insertNameLookup(long rawContactId, long dataId, int lookupType,
2477                String name) {
2478            if (!TextUtils.isEmpty(name)) {
2479                ContactsDatabaseHelper.this.insertNormalizedNameLookup(mNameLookupInsert,
2480                        rawContactId, dataId, lookupType, name);
2481            }
2482        }
2483
2484        @Override
2485        protected String[] getCommonNicknameClusters(String normalizedName) {
2486            return mCommonNicknameCache.getCommonNicknameClusters(normalizedName);
2487        }
2488    }
2489
2490    /**
2491     * Inserts name lookup rows for all structured names in the database.
2492     */
2493    private void insertStructuredNameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2494        NameSplitter nameSplitter = createNameSplitter();
2495        NameLookupBuilder nameLookupBuilder = new StructuredNameLookupBuilder(nameSplitter,
2496                new CommonNicknameCache(db), nameLookupInsert);
2497        final long mimeTypeId = lookupMimeTypeId(db, StructuredName.CONTENT_ITEM_TYPE);
2498        Cursor cursor = db.query(StructuredNameQuery.TABLE, StructuredNameQuery.COLUMNS,
2499                StructuredNameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2500                null, null, null);
2501        try {
2502            while (cursor.moveToNext()) {
2503                long dataId = cursor.getLong(StructuredNameQuery.ID);
2504                long rawContactId = cursor.getLong(StructuredNameQuery.RAW_CONTACT_ID);
2505                String name = cursor.getString(StructuredNameQuery.DISPLAY_NAME);
2506                int fullNameStyle = nameSplitter.guessFullNameStyle(name);
2507                fullNameStyle = nameSplitter.getAdjustedFullNameStyle(fullNameStyle);
2508                nameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle);
2509            }
2510        } finally {
2511            cursor.close();
2512        }
2513    }
2514
2515    private static final class OrganizationQuery {
2516        public static final String TABLE = Tables.DATA;
2517
2518        public static final String SELECTION =
2519                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2520
2521        public static final String COLUMNS[] = {
2522                Organization._ID,
2523                Organization.RAW_CONTACT_ID,
2524                Organization.COMPANY,
2525                Organization.TITLE,
2526        };
2527
2528        public static final int ID = 0;
2529        public static final int RAW_CONTACT_ID = 1;
2530        public static final int COMPANY = 2;
2531        public static final int TITLE = 3;
2532    }
2533
2534    private static final class EmailQuery {
2535        public static final String TABLE = Tables.DATA;
2536
2537        public static final String SELECTION =
2538                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2539
2540        public static final String COLUMNS[] = {
2541                Email._ID,
2542                Email.RAW_CONTACT_ID,
2543                Email.ADDRESS,
2544        };
2545
2546        public static final int ID = 0;
2547        public static final int RAW_CONTACT_ID = 1;
2548        public static final int ADDRESS = 2;
2549    }
2550
2551    /**
2552     * Inserts name lookup rows for all email addresses in the database.
2553     */
2554    private void insertEmailLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2555        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2556        Cursor cursor = db.query(EmailQuery.TABLE, EmailQuery.COLUMNS,
2557                EmailQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2558                null, null, null);
2559        try {
2560            while (cursor.moveToNext()) {
2561                long dataId = cursor.getLong(EmailQuery.ID);
2562                long rawContactId = cursor.getLong(EmailQuery.RAW_CONTACT_ID);
2563                String address = cursor.getString(EmailQuery.ADDRESS);
2564                address = extractHandleFromEmailAddress(address);
2565                insertNameLookup(nameLookupInsert, rawContactId, dataId,
2566                        NameLookupType.EMAIL_BASED_NICKNAME, address);
2567            }
2568        } finally {
2569            cursor.close();
2570        }
2571    }
2572
2573    private static final class NicknameQuery {
2574        public static final String TABLE = Tables.DATA;
2575
2576        public static final String SELECTION =
2577                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2578
2579        public static final String COLUMNS[] = {
2580                Nickname._ID,
2581                Nickname.RAW_CONTACT_ID,
2582                Nickname.NAME,
2583        };
2584
2585        public static final int ID = 0;
2586        public static final int RAW_CONTACT_ID = 1;
2587        public static final int NAME = 2;
2588    }
2589
2590    /**
2591     * Inserts name lookup rows for all nicknames in the database.
2592     */
2593    private void insertNicknameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2594        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
2595        Cursor cursor = db.query(NicknameQuery.TABLE, NicknameQuery.COLUMNS,
2596                NicknameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2597                null, null, null);
2598        try {
2599            while (cursor.moveToNext()) {
2600                long dataId = cursor.getLong(NicknameQuery.ID);
2601                long rawContactId = cursor.getLong(NicknameQuery.RAW_CONTACT_ID);
2602                String nickname = cursor.getString(NicknameQuery.NAME);
2603                insertNameLookup(nameLookupInsert, rawContactId, dataId,
2604                        NameLookupType.NICKNAME, nickname);
2605            }
2606        } finally {
2607            cursor.close();
2608        }
2609    }
2610
2611    /**
2612     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
2613     */
2614    public void insertNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
2615            int lookupType, String name) {
2616        if (TextUtils.isEmpty(name)) {
2617            return;
2618        }
2619
2620        String normalized = NameNormalizer.normalize(name);
2621        if (TextUtils.isEmpty(normalized)) {
2622            return;
2623        }
2624
2625        insertNormalizedNameLookup(stmt, rawContactId, dataId, lookupType, normalized);
2626    }
2627
2628    private void insertNormalizedNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
2629            int lookupType, String normalizedName) {
2630        stmt.bindLong(1, rawContactId);
2631        stmt.bindLong(2, dataId);
2632        stmt.bindLong(3, lookupType);
2633        stmt.bindString(4, normalizedName);
2634        stmt.executeInsert();
2635    }
2636
2637    /**
2638     * Changing the VISIBLE bit from a field on both RawContacts and Contacts to a separate table.
2639     */
2640    private void upgradeToVersion401(SQLiteDatabase db) {
2641        db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" +
2642                Contacts._ID + " INTEGER PRIMARY KEY" +
2643        ");");
2644        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
2645                " SELECT " + Contacts._ID +
2646                " FROM " + Tables.CONTACTS +
2647                " WHERE " + Contacts.IN_VISIBLE_GROUP + "!=0");
2648        db.execSQL("DROP INDEX contacts_visible_index");
2649    }
2650
2651    /**
2652     * Introducing a new table: directories.
2653     */
2654    private void upgradeToVersion402(SQLiteDatabase db) {
2655        createDirectoriesTable(db);
2656    }
2657
2658    private void upgradeToVersion403(SQLiteDatabase db) {
2659        db.execSQL("DROP TABLE IF EXISTS directories;");
2660        createDirectoriesTable(db);
2661
2662        db.execSQL("ALTER TABLE raw_contacts"
2663                + " ADD raw_contact_is_read_only INTEGER NOT NULL DEFAULT 0;");
2664
2665        db.execSQL("ALTER TABLE data"
2666                + " ADD is_read_only INTEGER NOT NULL DEFAULT 0;");
2667    }
2668
2669    private void upgradeToVersion405(SQLiteDatabase db) {
2670        db.execSQL("DROP TABLE IF EXISTS phone_lookup;");
2671        // Private phone numbers table used for lookup
2672        db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
2673                PhoneLookupColumns.DATA_ID
2674                + " INTEGER REFERENCES data(_id) NOT NULL," +
2675                PhoneLookupColumns.RAW_CONTACT_ID
2676                + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
2677                PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
2678                PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
2679        ");");
2680
2681        db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
2682                PhoneLookupColumns.NORMALIZED_NUMBER + "," +
2683                PhoneLookupColumns.RAW_CONTACT_ID + "," +
2684                PhoneLookupColumns.DATA_ID +
2685        ");");
2686
2687        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
2688                PhoneLookupColumns.MIN_MATCH + "," +
2689                PhoneLookupColumns.RAW_CONTACT_ID + "," +
2690                PhoneLookupColumns.DATA_ID +
2691        ");");
2692
2693        final long mimeTypeId = lookupMimeTypeId(db, Phone.CONTENT_ITEM_TYPE);
2694        if (mimeTypeId == -1) {
2695            return;
2696        }
2697
2698        String mCountryIso = getCountryIso();
2699        Cursor cursor = db.rawQuery(
2700                    "SELECT _id, " + Phone.RAW_CONTACT_ID + ", " + Phone.NUMBER +
2701                    " FROM " + Tables.DATA +
2702                    " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimeTypeId
2703                            + " AND " + Phone.NUMBER + " NOT NULL", null);
2704
2705        ContentValues phoneValues = new ContentValues();
2706        try {
2707            while (cursor.moveToNext()) {
2708                long dataID = cursor.getLong(0);
2709                long rawContactID = cursor.getLong(1);
2710                String number = cursor.getString(2);
2711                String numberE164 = PhoneNumberUtils.formatNumberToE164(number, mCountryIso);
2712                String normalizedNumber = PhoneNumberUtils.normalizeNumber(number);
2713                if (!TextUtils.isEmpty(normalizedNumber)) {
2714                    phoneValues.clear();
2715                    phoneValues.put(PhoneLookupColumns.RAW_CONTACT_ID, rawContactID);
2716                    phoneValues.put(PhoneLookupColumns.DATA_ID, dataID);
2717                    phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, normalizedNumber);
2718                    phoneValues.put(PhoneLookupColumns.MIN_MATCH,
2719                            PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber));
2720                    db.insert(Tables.PHONE_LOOKUP, null, phoneValues);
2721
2722                    if (numberE164 != null && !numberE164.equals(normalizedNumber)) {
2723                        phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, numberE164);
2724                        phoneValues.put(PhoneLookupColumns.MIN_MATCH,
2725                                PhoneNumberUtils.toCallerIDMinMatch(numberE164));
2726                        db.insert(Tables.PHONE_LOOKUP, null, phoneValues);
2727                    }
2728                }
2729            }
2730        } finally {
2731            cursor.close();
2732        }
2733    }
2734
2735    private void upgradeToVersion406(SQLiteDatabase db) {
2736        db.execSQL("ALTER TABLE calls ADD countryiso TEXT;");
2737    }
2738
2739    private void upgradeToVersion409(SQLiteDatabase db) {
2740        db.execSQL("DROP TABLE IF EXISTS directories;");
2741        createDirectoriesTable(db);
2742    }
2743
2744    /**
2745     * Adding DEFAULT_DIRECTORY table.
2746     */
2747    private void upgradeToVersion411(SQLiteDatabase db) {
2748        db.execSQL("DROP TABLE IF EXISTS " + Tables.DEFAULT_DIRECTORY);
2749        db.execSQL("CREATE TABLE " + Tables.DEFAULT_DIRECTORY + " (" +
2750                Contacts._ID + " INTEGER PRIMARY KEY" +
2751        ");");
2752
2753        // Process contacts without an account
2754        db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
2755                " SELECT " + RawContacts.CONTACT_ID +
2756                " FROM " + Tables.RAW_CONTACTS +
2757                " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " +
2758                "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL ");
2759
2760        // Process accounts that don't have a default group (e.g. Exchange)
2761        db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
2762                " SELECT " + RawContacts.CONTACT_ID +
2763                " FROM " + Tables.RAW_CONTACTS +
2764                " WHERE NOT EXISTS" +
2765                " (SELECT " + Groups._ID +
2766                "  FROM " + Tables.GROUPS +
2767                "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
2768                        + GroupsColumns.CONCRETE_ACCOUNT_NAME +
2769                "    AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
2770                        + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
2771                "    AND " + Groups.AUTO_ADD + " != 0" +
2772                ")");
2773
2774        long mimetype = lookupMimeTypeId(db, GroupMembership.CONTENT_ITEM_TYPE);
2775
2776        // Process accounts that do have a default group (e.g. Google)
2777        db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
2778                " SELECT " + RawContacts.CONTACT_ID +
2779                " FROM " + Tables.RAW_CONTACTS +
2780                " JOIN " + Tables.DATA +
2781                "   ON (" + RawContactsColumns.CONCRETE_ID + "=" + Data.RAW_CONTACT_ID + ")" +
2782                " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimetype +
2783                " AND EXISTS" +
2784                " (SELECT " + Groups._ID +
2785                "  FROM " + Tables.GROUPS +
2786                "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
2787                        + GroupsColumns.CONCRETE_ACCOUNT_NAME +
2788                "    AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
2789                        + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
2790                "    AND " + Groups.AUTO_ADD + " != 0" +
2791                ")");
2792    }
2793
2794    private void upgradeToVersion413(SQLiteDatabase db) {
2795        db.execSQL("DROP TABLE IF EXISTS directories;");
2796        createDirectoriesTable(db);
2797    }
2798
2799    private void upgradeToVersion415(SQLiteDatabase db) {
2800        db.execSQL(
2801                "ALTER TABLE " + Tables.GROUPS +
2802                " ADD " + Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0");
2803        db.execSQL(
2804                "UPDATE " + Tables.GROUPS +
2805                "   SET " + Groups.GROUP_IS_READ_ONLY + "=1" +
2806                " WHERE " + Groups.SYSTEM_ID + " NOT NULL");
2807    }
2808
2809    private void upgradeToVersion416(SQLiteDatabase db) {
2810        db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP +
2811                " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");");
2812    }
2813
2814    private void upgradeToVersion501(SQLiteDatabase db) {
2815        // Remove organization rows from the name lookup, we now use search index for that
2816        db.execSQL("DELETE FROM name_lookup WHERE name_type=5");
2817    }
2818
2819    private void upgradeToVersion502(SQLiteDatabase db) {
2820        // Remove Chinese and Korean name lookup - this data is now in the search index
2821        db.execSQL("DELETE FROM name_lookup WHERE name_type IN (6, 7)");
2822    }
2823
2824    public String extractHandleFromEmailAddress(String email) {
2825        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
2826        if (tokens.length == 0) {
2827            return null;
2828        }
2829
2830        String address = tokens[0].getAddress();
2831        int at = address.indexOf('@');
2832        if (at != -1) {
2833            return address.substring(0, at);
2834        }
2835        return null;
2836    }
2837
2838    public String extractAddressFromEmailAddress(String email) {
2839        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
2840        if (tokens.length == 0) {
2841            return null;
2842        }
2843
2844        return tokens[0].getAddress().trim();
2845    }
2846
2847    private long lookupMimeTypeId(SQLiteDatabase db, String mimeType) {
2848        try {
2849            return DatabaseUtils.longForQuery(db,
2850                    "SELECT " + MimetypesColumns._ID +
2851                    " FROM " + Tables.MIMETYPES +
2852                    " WHERE " + MimetypesColumns.MIMETYPE
2853                            + "='" + mimeType + "'", null);
2854        } catch (SQLiteDoneException e) {
2855            // No rows of this type in the database
2856            return -1;
2857        }
2858    }
2859
2860    private void bindString(SQLiteStatement stmt, int index, String value) {
2861        if (value == null) {
2862            stmt.bindNull(index);
2863        } else {
2864            stmt.bindString(index, value);
2865        }
2866    }
2867
2868    private void bindLong(SQLiteStatement stmt, int index, Number value) {
2869        if (value == null) {
2870            stmt.bindNull(index);
2871        } else {
2872            stmt.bindLong(index, value.longValue());
2873        }
2874    }
2875
2876    /**
2877     * Adds index stats into the SQLite database to force it to always use the lookup indexes.
2878     */
2879    private void updateSqliteStats(SQLiteDatabase db) {
2880
2881        // Specific stats strings are based on an actual large database after running ANALYZE
2882        try {
2883            updateIndexStats(db, Tables.CONTACTS,
2884                    "contacts_restricted_index", "10000 9000");
2885            updateIndexStats(db, Tables.CONTACTS,
2886                    "contacts_has_phone_index", "10000 500");
2887
2888            updateIndexStats(db, Tables.RAW_CONTACTS,
2889                    "raw_contacts_source_id_index", "10000 1 1 1");
2890            updateIndexStats(db, Tables.RAW_CONTACTS,
2891                    "raw_contacts_contact_id_index", "10000 2");
2892
2893            updateIndexStats(db, Tables.NAME_LOOKUP,
2894                    "name_lookup_raw_contact_id_index", "10000 3");
2895            updateIndexStats(db, Tables.NAME_LOOKUP,
2896                    "name_lookup_index", "10000 3 2 2 1");
2897            updateIndexStats(db, Tables.NAME_LOOKUP,
2898                    "sqlite_autoindex_name_lookup_1", "10000 3 2 1");
2899
2900            updateIndexStats(db, Tables.PHONE_LOOKUP,
2901                    "phone_lookup_index", "10000 2 2 1");
2902            updateIndexStats(db, Tables.PHONE_LOOKUP,
2903                    "phone_lookup_min_match_index", "10000 2 2 1");
2904
2905            updateIndexStats(db, Tables.DATA,
2906                    "data_mimetype_data1_index", "60000 5000 2");
2907            updateIndexStats(db, Tables.DATA,
2908                    "data_raw_contact_id", "60000 10");
2909
2910            updateIndexStats(db, Tables.GROUPS,
2911                    "groups_source_id_index", "50 1 1 1");
2912
2913            updateIndexStats(db, Tables.NICKNAME_LOOKUP,
2914                    "sqlite_autoindex_name_lookup_1", "500 2 1");
2915
2916        } catch (SQLException e) {
2917            Log.e(TAG, "Could not update index stats", e);
2918        }
2919    }
2920
2921    /**
2922     * Stores statistics for a given index.
2923     *
2924     * @param stats has the following structure: the first index is the expected size of
2925     * the table.  The following integer(s) are the expected number of records selected with the
2926     * index.  There should be one integer per indexed column.
2927     */
2928    private void updateIndexStats(SQLiteDatabase db, String table, String index,
2929            String stats) {
2930        db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl='" + table + "' AND idx='" + index + "';");
2931        db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat)"
2932                + " VALUES ('" + table + "','" + index + "','" + stats + "');");
2933    }
2934
2935    @Override
2936    public synchronized SQLiteDatabase getWritableDatabase() {
2937        SQLiteDatabase db = super.getWritableDatabase();
2938        if (mReopenDatabase) {
2939            mReopenDatabase = false;
2940            close();
2941            db = super.getWritableDatabase();
2942        }
2943        return db;
2944    }
2945
2946    /**
2947     * Wipes all data except mime type and package lookup tables.
2948     */
2949    public void wipeData() {
2950        SQLiteDatabase db = getWritableDatabase();
2951
2952        db.execSQL("DELETE FROM " + Tables.ACCOUNTS + ";");
2953        db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL)");
2954
2955        db.execSQL("DELETE FROM " + Tables.CONTACTS + ";");
2956        db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";");
2957        db.execSQL("DELETE FROM " + Tables.DATA + ";");
2958        db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";");
2959        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";");
2960        db.execSQL("DELETE FROM " + Tables.GROUPS + ";");
2961        db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";");
2962        db.execSQL("DELETE FROM " + Tables.SETTINGS + ";");
2963        db.execSQL("DELETE FROM " + Tables.ACTIVITIES + ";");
2964        db.execSQL("DELETE FROM " + Tables.CALLS + ";");
2965        db.execSQL("DELETE FROM " + Tables.DIRECTORIES + ";");
2966        db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + ";");
2967
2968        // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP
2969    }
2970
2971    public NameSplitter createNameSplitter() {
2972        return new NameSplitter(
2973                mContext.getString(com.android.internal.R.string.common_name_prefixes),
2974                mContext.getString(com.android.internal.R.string.common_last_name_prefixes),
2975                mContext.getString(com.android.internal.R.string.common_name_suffixes),
2976                mContext.getString(com.android.internal.R.string.common_name_conjunctions),
2977                Locale.getDefault());
2978    }
2979
2980    /**
2981     * Return the {@link ApplicationInfo#uid} for the given package name.
2982     */
2983    public static int getUidForPackageName(PackageManager pm, String packageName) {
2984        try {
2985            ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */);
2986            return clientInfo.uid;
2987        } catch (NameNotFoundException e) {
2988            throw new RuntimeException(e);
2989        }
2990    }
2991
2992    /**
2993     * Perform an internal string-to-integer lookup using the compiled
2994     * {@link SQLiteStatement} provided, using the in-memory cache to speed up
2995     * lookups. If a mapping isn't found in cache or database, it will be
2996     * created. All new, uncached answers are added to the cache automatically.
2997     *
2998     * @param query Compiled statement used to query for the mapping.
2999     * @param insert Compiled statement used to insert a new mapping when no
3000     *            existing one is found in cache or from query.
3001     * @param value Value to find mapping for.
3002     * @param cache In-memory cache of previous answers.
3003     * @return An unique integer mapping for the given value.
3004     */
3005    private long getCachedId(SQLiteStatement query, SQLiteStatement insert,
3006            String value, HashMap<String, Long> cache) {
3007        // Try an in-memory cache lookup
3008        if (cache.containsKey(value)) {
3009            return cache.get(value);
3010        }
3011
3012        synchronized (query) {
3013            long id = -1;
3014            try {
3015                // Try searching database for mapping
3016                DatabaseUtils.bindObjectToProgram(query, 1, value);
3017                id = query.simpleQueryForLong();
3018            } catch (SQLiteDoneException e) {
3019                // Nothing found, so try inserting new mapping
3020                DatabaseUtils.bindObjectToProgram(insert, 1, value);
3021                id = insert.executeInsert();
3022            }
3023            if (id != -1) {
3024                // Cache and return the new answer
3025                cache.put(value, id);
3026                return id;
3027            } else {
3028                // Otherwise throw if no mapping found or created
3029                throw new IllegalStateException("Couldn't find or create internal "
3030                        + "lookup table entry for value " + value);
3031            }
3032        }
3033    }
3034
3035    /**
3036     * Convert a package name into an integer, using {@link Tables#PACKAGES} for
3037     * lookups and possible allocation of new IDs as needed.
3038     */
3039    public long getPackageId(String packageName) {
3040        if (mPackageQuery == null) {
3041            mPackageQuery = getWritableDatabase().compileStatement(
3042                    "SELECT " + PackagesColumns._ID +
3043                    " FROM " + Tables.PACKAGES +
3044                    " WHERE " + PackagesColumns.PACKAGE + "=?");
3045
3046        }
3047        if (mPackageInsert == null) {
3048            mPackageInsert = getWritableDatabase().compileStatement(
3049                    "INSERT INTO " + Tables.PACKAGES + "("
3050                            + PackagesColumns.PACKAGE +
3051                    ") VALUES (?)");
3052        }
3053        return getCachedId(mPackageQuery, mPackageInsert, packageName, mPackageCache);
3054    }
3055
3056    /**
3057     * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for
3058     * lookups and possible allocation of new IDs as needed.
3059     */
3060    public long getMimeTypeId(String mimetype) {
3061        return getCachedId(mMimetypeQuery, mMimetypeInsert, mimetype, mMimetypeCache);
3062    }
3063
3064    public long getMimeTypeIdForStructuredName() {
3065        return mMimeTypeIdStructuredName;
3066    }
3067
3068    public long getMimeTypeIdForOrganization() {
3069        return mMimeTypeIdOrganization;
3070    }
3071
3072    public long getMimeTypeIdForIm() {
3073        return mMimeTypeIdIm;
3074    }
3075
3076    public long getMimeTypeIdForEmail() {
3077        return mMimeTypeIdEmail;
3078    }
3079
3080    public long getMimeTypeIdForSip() {
3081        return mMimeTypeIdSip;
3082    }
3083
3084    public int getDisplayNameSourceForMimeTypeId(int mimeTypeId) {
3085        if (mimeTypeId == mMimeTypeIdStructuredName) {
3086            return DisplayNameSources.STRUCTURED_NAME;
3087        } else if (mimeTypeId == mMimeTypeIdEmail) {
3088            return DisplayNameSources.EMAIL;
3089        } else if (mimeTypeId == mMimeTypeIdPhone) {
3090            return DisplayNameSources.PHONE;
3091        } else if (mimeTypeId == mMimeTypeIdOrganization) {
3092            return DisplayNameSources.ORGANIZATION;
3093        } else if (mimeTypeId == mMimeTypeIdNickname) {
3094            return DisplayNameSources.NICKNAME;
3095        } else {
3096            return DisplayNameSources.UNDEFINED;
3097        }
3098    }
3099
3100    /**
3101     * Find the mimetype for the given {@link Data#_ID}.
3102     */
3103    public String getDataMimeType(long dataId) {
3104        if (mDataMimetypeQuery == null) {
3105            mDataMimetypeQuery = getWritableDatabase().compileStatement(
3106                    "SELECT " + MimetypesColumns.MIMETYPE +
3107                    " FROM " + Tables.DATA_JOIN_MIMETYPES +
3108                    " WHERE " + Tables.DATA + "." + Data._ID + "=?");
3109        }
3110        try {
3111            // Try database query to find mimetype
3112            DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId);
3113            String mimetype = mDataMimetypeQuery.simpleQueryForString();
3114            return mimetype;
3115        } catch (SQLiteDoneException e) {
3116            // No valid mapping found, so return null
3117            return null;
3118        }
3119    }
3120
3121    /**
3122     * Find the mime-type for the given {@link Activities#_ID}.
3123     */
3124    public String getActivityMimeType(long activityId) {
3125        if (mActivitiesMimetypeQuery == null) {
3126            mActivitiesMimetypeQuery = getWritableDatabase().compileStatement(
3127                    "SELECT " + MimetypesColumns.MIMETYPE +
3128                    " FROM " + Tables.ACTIVITIES_JOIN_MIMETYPES +
3129                    " WHERE " + Tables.ACTIVITIES + "." + Activities._ID + "=?");
3130        }
3131        try {
3132            // Try database query to find mimetype
3133            DatabaseUtils.bindObjectToProgram(mActivitiesMimetypeQuery, 1, activityId);
3134            String mimetype = mActivitiesMimetypeQuery.simpleQueryForString();
3135            return mimetype;
3136        } catch (SQLiteDoneException e) {
3137            // No valid mapping found, so return null
3138            return null;
3139        }
3140    }
3141
3142    /**
3143     * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts.
3144     */
3145    public void updateAllVisible() {
3146        updateCustomContactVisibility(getWritableDatabase(), "");
3147    }
3148
3149    /**
3150     * Updates contact visibility and return true iff the visibility was actually changed.
3151     */
3152    public boolean updateContactVisibleOnlyIfChanged(TransactionContext txContext, long contactId) {
3153        return updateContactVisible(txContext, contactId, true);
3154    }
3155
3156    /**
3157     * Update {@link Contacts#IN_VISIBLE_GROUP} and
3158     * {@link Tables#DEFAULT_DIRECTORY} for a specific contact.
3159     */
3160    public void updateContactVisible(TransactionContext txContext, long contactId) {
3161        updateContactVisible(txContext, contactId, false);
3162    }
3163
3164    public boolean updateContactVisible(
3165            TransactionContext txContext, long contactId, boolean onlyIfChanged) {
3166        SQLiteDatabase db = getWritableDatabase();
3167        updateCustomContactVisibility(db, " AND " + Contacts._ID + "=" + contactId);
3168
3169        String contactIdAsString = String.valueOf(contactId);
3170        long mimetype = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3171
3172        // The contact will be included in the default directory if contains
3173        // a raw contact that is in any group or in an account that
3174        // does not have any AUTO_ADD groups.
3175        boolean newVisibility = DatabaseUtils.longForQuery(db,
3176                "SELECT EXISTS (" +
3177                    "SELECT " + RawContacts.CONTACT_ID +
3178                    " FROM " + Tables.RAW_CONTACTS +
3179                    " JOIN " + Tables.DATA +
3180                    "   ON (" + RawContactsColumns.CONCRETE_ID + "="
3181                            + Data.RAW_CONTACT_ID + ")" +
3182                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3183                    "   AND " + DataColumns.MIMETYPE_ID + "=?" +
3184                ") OR EXISTS (" +
3185                    "SELECT " + RawContacts._ID +
3186                    " FROM " + Tables.RAW_CONTACTS +
3187                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3188                    "   AND NOT EXISTS" +
3189                        " (SELECT " + Groups._ID +
3190                        "  FROM " + Tables.GROUPS +
3191                        "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
3192                                + GroupsColumns.CONCRETE_ACCOUNT_NAME +
3193                        "  AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
3194                                + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
3195                        "  AND " + Groups.AUTO_ADD + " != 0" +
3196                        ")" +
3197                ") OR EXISTS (" +
3198                    "SELECT " + RawContacts._ID +
3199                    " FROM " + Tables.RAW_CONTACTS +
3200                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3201                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " +
3202                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL" +
3203                ")",
3204                new String[] {
3205                    contactIdAsString,
3206                    String.valueOf(mimetype),
3207                    contactIdAsString,
3208                    contactIdAsString
3209                }) != 0;
3210
3211        if (onlyIfChanged) {
3212            boolean oldVisibility = isContactInDefaultDirectory(db, contactId);
3213            if (oldVisibility == newVisibility) {
3214                return false;
3215            }
3216        }
3217
3218        if (newVisibility) {
3219            db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " VALUES(?)",
3220                    new String[] { contactIdAsString });
3221            txContext.invalidateSearchIndexForContact(contactId);
3222        } else {
3223            db.execSQL("DELETE FROM " + Tables.DEFAULT_DIRECTORY +
3224                        " WHERE " + Contacts._ID + "=?",
3225                    new String[] { contactIdAsString });
3226            db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX +
3227                        " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
3228                    new String[] { contactIdAsString });
3229        }
3230        return true;
3231    }
3232
3233    public boolean isContactInDefaultDirectory(SQLiteDatabase db, long contactId) {
3234        if (mContactInDefaultDirectoryQuery == null) {
3235            mContactInDefaultDirectoryQuery = db.compileStatement(
3236                    "SELECT EXISTS (" +
3237                            "SELECT 1 FROM " + Tables.DEFAULT_DIRECTORY +
3238                            " WHERE " + Contacts._ID + "=?)");
3239        }
3240        mContactInDefaultDirectoryQuery.bindLong(1, contactId);
3241        return mContactInDefaultDirectoryQuery.simpleQueryForLong() != 0;
3242    }
3243
3244    private void updateCustomContactVisibility(SQLiteDatabase db, String selection) {
3245        final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3246        String[] selectionArgs = new String[]{String.valueOf(groupMembershipMimetypeId)};
3247
3248        // First delete what needs to be deleted, then insert what needs to be added.
3249        // Since flash writes are very expensive, this approach is much better than
3250        // delete-all-insert-all.
3251        db.execSQL("DELETE FROM " + Tables.VISIBLE_CONTACTS +
3252                   " WHERE " + "_id NOT IN" +
3253                        "(SELECT " + Contacts._ID +
3254                        " FROM " + Tables.CONTACTS +
3255                        " WHERE (" + Clauses.CONTACT_IS_VISIBLE + ")=1) " + selection,
3256                selectionArgs);
3257
3258        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
3259                   " SELECT " + Contacts._ID +
3260                   " FROM " + Tables.CONTACTS +
3261                   " WHERE " + Contacts._ID +
3262                   " NOT IN " + Tables.VISIBLE_CONTACTS +
3263                           " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=1 " + selection,
3264                selectionArgs);
3265    }
3266
3267    /**
3268     * Returns contact ID for the given contact or zero if it is NULL.
3269     */
3270    public long getContactId(long rawContactId) {
3271        if (mContactIdQuery == null) {
3272            mContactIdQuery = getWritableDatabase().compileStatement(
3273                    "SELECT " + RawContacts.CONTACT_ID +
3274                    " FROM " + Tables.RAW_CONTACTS +
3275                    " WHERE " + RawContacts._ID + "=?");
3276        }
3277        try {
3278            DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId);
3279            return mContactIdQuery.simpleQueryForLong();
3280        } catch (SQLiteDoneException e) {
3281            // No valid mapping found, so return 0
3282            return 0;
3283        }
3284    }
3285
3286    public int getAggregationMode(long rawContactId) {
3287        if (mAggregationModeQuery == null) {
3288            mAggregationModeQuery = getWritableDatabase().compileStatement(
3289                    "SELECT " + RawContacts.AGGREGATION_MODE +
3290                    " FROM " + Tables.RAW_CONTACTS +
3291                    " WHERE " + RawContacts._ID + "=?");
3292        }
3293        try {
3294            DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId);
3295            return (int)mAggregationModeQuery.simpleQueryForLong();
3296        } catch (SQLiteDoneException e) {
3297            // No valid row found, so return "disabled"
3298            return RawContacts.AGGREGATION_MODE_DISABLED;
3299        }
3300    }
3301
3302    public void buildPhoneLookupAndContactQuery(
3303            SQLiteQueryBuilder qb, String normalizedNumber, String numberE164) {
3304        String minMatch = PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber);
3305        StringBuilder sb = new StringBuilder();
3306        appendPhoneLookupTables(sb, minMatch, true);
3307        qb.setTables(sb.toString());
3308
3309        sb = new StringBuilder();
3310        appendPhoneLookupSelection(sb, normalizedNumber, numberE164);
3311        qb.appendWhere(sb.toString());
3312    }
3313
3314    public String buildPhoneLookupAsNestedQuery(String number) {
3315        StringBuilder sb = new StringBuilder();
3316        final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
3317        sb.append("(SELECT DISTINCT raw_contact_id" + " FROM ");
3318        appendPhoneLookupTables(sb, minMatch, false);
3319        sb.append(" WHERE ");
3320        appendPhoneLookupSelection(sb, number, null);
3321        sb.append(")");
3322        return sb.toString();
3323    }
3324
3325    private void appendPhoneLookupTables(StringBuilder sb, final String minMatch,
3326            boolean joinContacts) {
3327        sb.append(Tables.RAW_CONTACTS);
3328        if (joinContacts) {
3329            sb.append(" JOIN " + getContactView() + " contacts_view"
3330                    + " ON (contacts_view._id = raw_contacts.contact_id)");
3331        }
3332        sb.append(", (SELECT data_id, normalized_number, length(normalized_number) as len "
3333                + " FROM phone_lookup " + " WHERE (" + Tables.PHONE_LOOKUP + "."
3334                + PhoneLookupColumns.MIN_MATCH + " = '");
3335        sb.append(minMatch);
3336        sb.append("')) AS lookup, " + Tables.DATA);
3337    }
3338
3339    private void appendPhoneLookupSelection(StringBuilder sb, String number, String numberE164) {
3340        sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id");
3341        boolean hasNumberE164 = !TextUtils.isEmpty(numberE164);
3342        boolean hasNumber = !TextUtils.isEmpty(number);
3343        if (hasNumberE164 || hasNumber) {
3344            sb.append(" AND ( ");
3345            if (hasNumberE164) {
3346                sb.append(" lookup.normalized_number = ");
3347                DatabaseUtils.appendEscapedSQLString(sb, numberE164);
3348            }
3349            if (hasNumberE164 && hasNumber) {
3350                sb.append(" OR ");
3351            }
3352            if (hasNumber) {
3353                int numberLen = number.length();
3354                sb.append(" lookup.len <= ");
3355                sb.append(numberLen);
3356                sb.append(" AND substr(");
3357                DatabaseUtils.appendEscapedSQLString(sb, number);
3358                sb.append(',');
3359                sb.append(numberLen);
3360                sb.append(" - lookup.len + 1) = lookup.normalized_number");
3361            }
3362            sb.append(')');
3363        }
3364    }
3365
3366    public String getUseStrictPhoneNumberComparisonParameter() {
3367        return mUseStrictPhoneNumberComparison ? "1" : "0";
3368    }
3369
3370    /**
3371     * Loads common nickname mappings into the database.
3372     */
3373    private void loadNicknameLookupTable(SQLiteDatabase db) {
3374        db.execSQL("DELETE FROM " + Tables.NICKNAME_LOOKUP);
3375
3376        String[] strings = mContext.getResources().getStringArray(
3377                com.android.internal.R.array.common_nicknames);
3378        if (strings == null || strings.length == 0) {
3379            return;
3380        }
3381
3382        SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO "
3383                + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + ","
3384                + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)");
3385
3386        try {
3387            for (int clusterId = 0; clusterId < strings.length; clusterId++) {
3388                String[] names = strings[clusterId].split(",");
3389                for (int j = 0; j < names.length; j++) {
3390                    String name = NameNormalizer.normalize(names[j]);
3391                    try {
3392                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name);
3393                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2,
3394                                String.valueOf(clusterId));
3395                        nicknameLookupInsert.executeInsert();
3396                    } catch (SQLiteException e) {
3397
3398                        // Print the exception and keep going - this is not a fatal error
3399                        Log.e(TAG, "Cannot insert nickname: " + names[j], e);
3400                    }
3401                }
3402            }
3403        } finally {
3404            nicknameLookupInsert.close();
3405        }
3406    }
3407
3408    public static void copyStringValue(ContentValues toValues, String toKey,
3409            ContentValues fromValues, String fromKey) {
3410        if (fromValues.containsKey(fromKey)) {
3411            toValues.put(toKey, fromValues.getAsString(fromKey));
3412        }
3413    }
3414
3415    public static void copyLongValue(ContentValues toValues, String toKey,
3416            ContentValues fromValues, String fromKey) {
3417        if (fromValues.containsKey(fromKey)) {
3418            long longValue;
3419            Object value = fromValues.get(fromKey);
3420            if (value instanceof Boolean) {
3421                if ((Boolean)value) {
3422                    longValue = 1;
3423                } else {
3424                    longValue = 0;
3425                }
3426            } else if (value instanceof String) {
3427                longValue = Long.parseLong((String)value);
3428            } else {
3429                longValue = ((Number)value).longValue();
3430            }
3431            toValues.put(toKey, longValue);
3432        }
3433    }
3434
3435    public SyncStateContentProviderHelper getSyncState() {
3436        return mSyncState;
3437    }
3438
3439    /**
3440     * Delete the aggregate contact if it has no constituent raw contacts other
3441     * than the supplied one.
3442     */
3443    public void removeContactIfSingleton(long rawContactId) {
3444        SQLiteDatabase db = getWritableDatabase();
3445
3446        // Obtain contact ID from the supplied raw contact ID
3447        String contactIdFromRawContactId = "(SELECT " + RawContacts.CONTACT_ID + " FROM "
3448                + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=" + rawContactId + ")";
3449
3450        // Find other raw contacts in the same aggregate contact
3451        String otherRawContacts = "(SELECT contacts1." + RawContacts._ID + " FROM "
3452                + Tables.RAW_CONTACTS + " contacts1 JOIN " + Tables.RAW_CONTACTS + " contacts2 ON ("
3453                + "contacts1." + RawContacts.CONTACT_ID + "=contacts2." + RawContacts.CONTACT_ID
3454                + ") WHERE contacts1." + RawContacts._ID + "!=" + rawContactId + ""
3455                + " AND contacts2." + RawContacts._ID + "=" + rawContactId + ")";
3456
3457        db.execSQL("DELETE FROM " + Tables.CONTACTS
3458                + " WHERE " + Contacts._ID + "=" + contactIdFromRawContactId
3459                + " AND NOT EXISTS " + otherRawContacts + ";");
3460    }
3461
3462    /**
3463     * Returns the value from the {@link Tables#PROPERTIES} table.
3464     */
3465    public String getProperty(String key, String defaultValue) {
3466        Cursor cursor = getReadableDatabase().query(Tables.PROPERTIES,
3467                new String[]{PropertiesColumns.PROPERTY_VALUE},
3468                PropertiesColumns.PROPERTY_KEY + "=?",
3469                new String[]{key}, null, null, null);
3470        String value = null;
3471        try {
3472            if (cursor.moveToFirst()) {
3473                value = cursor.getString(0);
3474            }
3475        } finally {
3476            cursor.close();
3477        }
3478
3479        return value != null ? value : defaultValue;
3480    }
3481
3482    /**
3483     * Stores a key-value pair in the {@link Tables#PROPERTIES} table.
3484     */
3485    public void setProperty(String key, String value) {
3486        setProperty(getWritableDatabase(), key, value);
3487    }
3488
3489    private void setProperty(SQLiteDatabase db, String key, String value) {
3490        ContentValues values = new ContentValues();
3491        values.put(PropertiesColumns.PROPERTY_KEY, key);
3492        values.put(PropertiesColumns.PROPERTY_VALUE, value);
3493        db.replace(Tables.PROPERTIES, null, values);
3494    }
3495
3496    /**
3497     * Check if {@link Binder#getCallingUid()} should be allowed access to
3498     * {@link RawContacts#IS_RESTRICTED} data.
3499     */
3500    boolean hasAccessToRestrictedData() {
3501        final PackageManager pm = mContext.getPackageManager();
3502        int caller = Binder.getCallingUid();
3503        if (caller == 0) return true; // root can do anything
3504        final String[] callerPackages = pm.getPackagesForUid(caller);
3505
3506        // Has restricted access if caller matches any packages
3507        for (String callerPackage : callerPackages) {
3508            if (hasAccessToRestrictedData(callerPackage)) {
3509                return true;
3510            }
3511        }
3512        return false;
3513    }
3514
3515    /**
3516     * Check if requestingPackage should be allowed access to
3517     * {@link RawContacts#IS_RESTRICTED} data.
3518     */
3519    boolean hasAccessToRestrictedData(String requestingPackage) {
3520        if (mUnrestrictedPackages != null) {
3521            for (String allowedPackage : mUnrestrictedPackages) {
3522                if (allowedPackage.equals(requestingPackage)) {
3523                    return true;
3524                }
3525            }
3526        }
3527        return false;
3528    }
3529
3530    public String getDataView() {
3531        return getDataView(false);
3532    }
3533
3534    public String getDataView(boolean requireRestrictedView) {
3535        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
3536                Views.DATA_ALL : Views.DATA_RESTRICTED;
3537    }
3538
3539    public String getRawContactView() {
3540        return getRawContactView(false);
3541    }
3542
3543    public String getRawContactView(boolean requireRestrictedView) {
3544        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
3545                Views.RAW_CONTACTS_ALL : Views.RAW_CONTACTS_RESTRICTED;
3546    }
3547
3548    public String getContactView() {
3549        return getContactView(false);
3550    }
3551
3552    public String getContactView(boolean requireRestrictedView) {
3553        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
3554                Views.CONTACTS_ALL : Views.CONTACTS_RESTRICTED;
3555    }
3556
3557    public String getGroupView() {
3558        return Views.GROUPS_ALL;
3559    }
3560
3561    public String getRawEntitiesView() {
3562        return getRawEntitiesView(false);
3563    }
3564
3565    public String getRawEntitiesView(boolean requireRestrictedView) {
3566        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
3567                Views.RAW_ENTITIES : Views.RAW_ENTITIES_RESTRICTED;
3568    }
3569
3570    public String getEntitiesView() {
3571        return getEntitiesView(false);
3572    }
3573
3574    public String getEntitiesView(boolean requireRestrictedView) {
3575        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
3576                Views.ENTITIES : Views.ENTITIES_RESTRICTED;
3577    }
3578
3579    /**
3580     * Test if any of the columns appear in the given projection.
3581     */
3582    public boolean isInProjection(String[] projection, String... columns) {
3583        if (projection == null) {
3584            return true;
3585        }
3586
3587        // Optimized for a single-column test
3588        if (columns.length == 1) {
3589            String column = columns[0];
3590            for (String test : projection) {
3591                if (column.equals(test)) {
3592                    return true;
3593                }
3594            }
3595        } else {
3596            for (String test : projection) {
3597                for (String column : columns) {
3598                    if (column.equals(test)) {
3599                        return true;
3600                    }
3601                }
3602            }
3603        }
3604        return false;
3605    }
3606
3607    /**
3608     * Returns a detailed exception message for the supplied URI.  It includes the calling
3609     * user and calling package(s).
3610     */
3611    public String exceptionMessage(Uri uri) {
3612        return exceptionMessage(null, uri);
3613    }
3614
3615    /**
3616     * Returns a detailed exception message for the supplied URI.  It includes the calling
3617     * user and calling package(s).
3618     */
3619    public String exceptionMessage(String message, Uri uri) {
3620        StringBuilder sb = new StringBuilder();
3621        if (message != null) {
3622            sb.append(message).append("; ");
3623        }
3624        sb.append("URI: ").append(uri);
3625        final PackageManager pm = mContext.getPackageManager();
3626        int callingUid = Binder.getCallingUid();
3627        sb.append(", calling user: ");
3628        String userName = pm.getNameForUid(callingUid);
3629        if (userName != null) {
3630            sb.append(userName);
3631        } else {
3632            sb.append(callingUid);
3633        }
3634
3635        final String[] callerPackages = pm.getPackagesForUid(callingUid);
3636        if (callerPackages != null && callerPackages.length > 0) {
3637            if (callerPackages.length == 1) {
3638                sb.append(", calling package:");
3639                sb.append(callerPackages[0]);
3640            } else {
3641                sb.append(", calling package is one of: [");
3642                for (int i = 0; i < callerPackages.length; i++) {
3643                    if (i != 0) {
3644                        sb.append(", ");
3645                    }
3646                    sb.append(callerPackages[i]);
3647                }
3648                sb.append("]");
3649            }
3650        }
3651
3652        return sb.toString();
3653    }
3654
3655    protected String getCountryIso() {
3656        CountryDetector detector =
3657            (CountryDetector) mContext.getSystemService(Context.COUNTRY_DETECTOR);
3658        return detector.detectCountry().getCountryIso();
3659    }
3660
3661    public void deleteStatusUpdate(long dataId) {
3662        if (mStatusUpdateDelete == null) {
3663            mStatusUpdateDelete = getWritableDatabase().compileStatement(
3664                    "DELETE FROM " + Tables.STATUS_UPDATES +
3665                    " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
3666        }
3667        mStatusUpdateDelete.bindLong(1, dataId);
3668        mStatusUpdateDelete.execute();
3669    }
3670
3671    public void replaceStatusUpdate(Long dataId, long timestamp, String status, String resPackage,
3672            Long iconResource, Integer labelResource) {
3673        if (mStatusUpdateReplace == null) {
3674            mStatusUpdateReplace = getWritableDatabase().compileStatement(
3675                    "INSERT OR REPLACE INTO " + Tables.STATUS_UPDATES + "("
3676                            + StatusUpdatesColumns.DATA_ID + ", "
3677                            + StatusUpdates.STATUS_TIMESTAMP + ","
3678                            + StatusUpdates.STATUS + ","
3679                            + StatusUpdates.STATUS_RES_PACKAGE + ","
3680                            + StatusUpdates.STATUS_ICON + ","
3681                            + StatusUpdates.STATUS_LABEL + ")" +
3682                    " VALUES (?,?,?,?,?,?)");
3683        }
3684        mStatusUpdateReplace.bindLong(1, dataId);
3685        mStatusUpdateReplace.bindLong(2, timestamp);
3686        bindString(mStatusUpdateReplace, 3, status);
3687        bindString(mStatusUpdateReplace, 4, resPackage);
3688        bindLong(mStatusUpdateReplace, 5, iconResource);
3689        bindLong(mStatusUpdateReplace, 6, labelResource);
3690        mStatusUpdateReplace.execute();
3691    }
3692
3693    public void insertStatusUpdate(Long dataId, String status, String resPackage, Long iconResource,
3694            Integer labelResource) {
3695        if (mStatusUpdateInsert == null) {
3696            mStatusUpdateInsert = getWritableDatabase().compileStatement(
3697                    "INSERT INTO " + Tables.STATUS_UPDATES + "("
3698                            + StatusUpdatesColumns.DATA_ID + ", "
3699                            + StatusUpdates.STATUS + ","
3700                            + StatusUpdates.STATUS_RES_PACKAGE + ","
3701                            + StatusUpdates.STATUS_ICON + ","
3702                            + StatusUpdates.STATUS_LABEL + ")" +
3703                    " VALUES (?,?,?,?,?)");
3704        }
3705        try {
3706            mStatusUpdateInsert.bindLong(1, dataId);
3707            bindString(mStatusUpdateInsert, 2, status);
3708            bindString(mStatusUpdateInsert, 3, resPackage);
3709            bindLong(mStatusUpdateInsert, 4, iconResource);
3710            bindLong(mStatusUpdateInsert, 5, labelResource);
3711            mStatusUpdateInsert.executeInsert();
3712        } catch (SQLiteConstraintException e) {
3713            // The row already exists - update it
3714            if (mStatusUpdateAutoTimestamp == null) {
3715                mStatusUpdateAutoTimestamp = getWritableDatabase().compileStatement(
3716                        "UPDATE " + Tables.STATUS_UPDATES +
3717                        " SET " + StatusUpdates.STATUS_TIMESTAMP + "=?,"
3718                                + StatusUpdates.STATUS + "=?" +
3719                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"
3720                                + " AND " + StatusUpdates.STATUS + "!=?");
3721            }
3722
3723            long timestamp = System.currentTimeMillis();
3724            mStatusUpdateAutoTimestamp.bindLong(1, timestamp);
3725            bindString(mStatusUpdateAutoTimestamp, 2, status);
3726            mStatusUpdateAutoTimestamp.bindLong(3, dataId);
3727            bindString(mStatusUpdateAutoTimestamp, 4, status);
3728            mStatusUpdateAutoTimestamp.execute();
3729
3730            if (mStatusAttributionUpdate == null) {
3731                mStatusAttributionUpdate = getWritableDatabase().compileStatement(
3732                        "UPDATE " + Tables.STATUS_UPDATES +
3733                        " SET " + StatusUpdates.STATUS_RES_PACKAGE + "=?,"
3734                                + StatusUpdates.STATUS_ICON + "=?,"
3735                                + StatusUpdates.STATUS_LABEL + "=?" +
3736                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
3737            }
3738            bindString(mStatusAttributionUpdate, 1, resPackage);
3739            bindLong(mStatusAttributionUpdate, 2, iconResource);
3740            bindLong(mStatusAttributionUpdate, 3, labelResource);
3741            mStatusAttributionUpdate.bindLong(4, dataId);
3742            mStatusAttributionUpdate.execute();
3743        }
3744    }
3745
3746    /**
3747     * Resets the {@link RawContacts#NAME_VERIFIED} flag to 0 on all other raw
3748     * contacts in the same aggregate
3749     */
3750    public void resetNameVerifiedForOtherRawContacts(long rawContactId) {
3751        if (mResetNameVerifiedForOtherRawContacts == null) {
3752            mResetNameVerifiedForOtherRawContacts = getWritableDatabase().compileStatement(
3753                    "UPDATE " + Tables.RAW_CONTACTS +
3754                    " SET " + RawContacts.NAME_VERIFIED + "=0" +
3755                    " WHERE " + RawContacts.CONTACT_ID + "=(" +
3756                            "SELECT " + RawContacts.CONTACT_ID +
3757                            " FROM " + Tables.RAW_CONTACTS +
3758                            " WHERE " + RawContacts._ID + "=?)" +
3759                    " AND " + RawContacts._ID + "!=?");
3760        }
3761        mResetNameVerifiedForOtherRawContacts.bindLong(1, rawContactId);
3762        mResetNameVerifiedForOtherRawContacts.bindLong(2, rawContactId);
3763        mResetNameVerifiedForOtherRawContacts.execute();
3764    }
3765
3766    public void setDisplayName(long rawContactId, int displayNameSource,
3767            String displayNamePrimary, String displayNameAlternative, String phoneticName,
3768            int phoneticNameStyle, String sortKeyPrimary, String sortKeyAlternative) {
3769        if (mRawContactDisplayNameUpdate == null) {
3770            mRawContactDisplayNameUpdate = getWritableDatabase().compileStatement(
3771                    "UPDATE " + Tables.RAW_CONTACTS +
3772                    " SET " +
3773                            RawContacts.DISPLAY_NAME_SOURCE + "=?," +
3774                            RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
3775                            RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
3776                            RawContacts.PHONETIC_NAME + "=?," +
3777                            RawContacts.PHONETIC_NAME_STYLE + "=?," +
3778                            RawContacts.SORT_KEY_PRIMARY + "=?," +
3779                            RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
3780                    " WHERE " + RawContacts._ID + "=?");
3781        }
3782        mRawContactDisplayNameUpdate.bindLong(1, displayNameSource);
3783        bindString(mRawContactDisplayNameUpdate, 2, displayNamePrimary);
3784        bindString(mRawContactDisplayNameUpdate, 3, displayNameAlternative);
3785        bindString(mRawContactDisplayNameUpdate, 4, phoneticName);
3786        mRawContactDisplayNameUpdate.bindLong(5, phoneticNameStyle);
3787        bindString(mRawContactDisplayNameUpdate, 6, sortKeyPrimary);
3788        bindString(mRawContactDisplayNameUpdate, 7, sortKeyAlternative);
3789        mRawContactDisplayNameUpdate.bindLong(8, rawContactId);
3790        mRawContactDisplayNameUpdate.execute();
3791    }
3792
3793    /*
3794     * Sets the given dataId record in the "data" table to primary, and resets all data records of
3795     * the same mimetype and under the same contact to not be primary.
3796     *
3797     * @param dataId the id of the data record to be set to primary. Pass -1 to clear the primary
3798     * flag of all data items of this raw contacts
3799     */
3800    public void setIsPrimary(long rawContactId, long dataId, long mimeTypeId) {
3801        if (mSetPrimaryStatement == null) {
3802            mSetPrimaryStatement = getWritableDatabase().compileStatement(
3803                    "UPDATE " + Tables.DATA +
3804                    " SET " + Data.IS_PRIMARY + "=(_id=?)" +
3805                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
3806                    "   AND " + Data.RAW_CONTACT_ID + "=?");
3807        }
3808        mSetPrimaryStatement.bindLong(1, dataId);
3809        mSetPrimaryStatement.bindLong(2, mimeTypeId);
3810        mSetPrimaryStatement.bindLong(3, rawContactId);
3811        mSetPrimaryStatement.execute();
3812    }
3813
3814    /*
3815     * Clears the super primary of all data items of the given raw contact. does not touch
3816     * other raw contacts of the same joined aggregate
3817     */
3818    public void clearSuperPrimary(long rawContactId, long mimeTypeId) {
3819        if (mClearSuperPrimaryStatement == null) {
3820            mClearSuperPrimaryStatement = getWritableDatabase().compileStatement(
3821                    "UPDATE " + Tables.DATA +
3822                    " SET " + Data.IS_SUPER_PRIMARY + "=0" +
3823                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
3824                    "   AND " + Data.RAW_CONTACT_ID + "=?");
3825        }
3826        mClearSuperPrimaryStatement.bindLong(1, mimeTypeId);
3827        mClearSuperPrimaryStatement.bindLong(2, rawContactId);
3828        mClearSuperPrimaryStatement.execute();
3829    }
3830
3831    /*
3832     * Sets the given dataId record in the "data" table to "super primary", and resets all data
3833     * records of the same mimetype and under the same aggregate to not be "super primary".
3834     *
3835     * @param dataId the id of the data record to be set to primary.
3836     */
3837    public void setIsSuperPrimary(long rawContactId, long dataId, long mimeTypeId) {
3838        if (mSetSuperPrimaryStatement == null) {
3839            mSetSuperPrimaryStatement = getWritableDatabase().compileStatement(
3840                    "UPDATE " + Tables.DATA +
3841                    " SET " + Data.IS_SUPER_PRIMARY + "=(" + Data._ID + "=?)" +
3842                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
3843                    "   AND " + Data.RAW_CONTACT_ID + " IN (" +
3844                            "SELECT " + RawContacts._ID +
3845                            " FROM " + Tables.RAW_CONTACTS +
3846                            " WHERE " + RawContacts.CONTACT_ID + " =(" +
3847                                    "SELECT " + RawContacts.CONTACT_ID +
3848                                    " FROM " + Tables.RAW_CONTACTS +
3849                                    " WHERE " + RawContacts._ID + "=?))");
3850        }
3851        mSetSuperPrimaryStatement.bindLong(1, dataId);
3852        mSetSuperPrimaryStatement.bindLong(2, mimeTypeId);
3853        mSetSuperPrimaryStatement.bindLong(3, rawContactId);
3854        mSetSuperPrimaryStatement.execute();
3855    }
3856
3857    /**
3858     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
3859     */
3860    public void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) {
3861        if (TextUtils.isEmpty(name)) {
3862            return;
3863        }
3864
3865        if (mNameLookupInsert == null) {
3866            mNameLookupInsert = getWritableDatabase().compileStatement(
3867                    "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
3868                            + NameLookupColumns.RAW_CONTACT_ID + ","
3869                            + NameLookupColumns.DATA_ID + ","
3870                            + NameLookupColumns.NAME_TYPE + ","
3871                            + NameLookupColumns.NORMALIZED_NAME
3872                    + ") VALUES (?,?,?,?)");
3873        }
3874        mNameLookupInsert.bindLong(1, rawContactId);
3875        mNameLookupInsert.bindLong(2, dataId);
3876        mNameLookupInsert.bindLong(3, lookupType);
3877        bindString(mNameLookupInsert, 4, name);
3878        mNameLookupInsert.executeInsert();
3879    }
3880
3881    /**
3882     * Deletes all {@link Tables#NAME_LOOKUP} table rows associated with the specified data element.
3883     */
3884    public void deleteNameLookup(long dataId) {
3885        if (mNameLookupDelete == null) {
3886            mNameLookupDelete = getWritableDatabase().compileStatement(
3887                    "DELETE FROM " + Tables.NAME_LOOKUP +
3888                    " WHERE " + NameLookupColumns.DATA_ID + "=?");
3889        }
3890        mNameLookupDelete.bindLong(1, dataId);
3891        mNameLookupDelete.execute();
3892    }
3893
3894    public String insertNameLookupForEmail(long rawContactId, long dataId, String email) {
3895        if (TextUtils.isEmpty(email)) {
3896            return null;
3897        }
3898
3899        String address = extractHandleFromEmailAddress(email);
3900        if (address == null) {
3901            return null;
3902        }
3903
3904        insertNameLookup(rawContactId, dataId,
3905                NameLookupType.EMAIL_BASED_NICKNAME, NameNormalizer.normalize(address));
3906        return address;
3907    }
3908
3909    /**
3910     * Normalizes the nickname and inserts it in the name lookup table.
3911     */
3912    public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) {
3913        if (TextUtils.isEmpty(nickname)) {
3914            return;
3915        }
3916
3917        insertNameLookup(rawContactId, dataId,
3918                NameLookupType.NICKNAME, NameNormalizer.normalize(nickname));
3919    }
3920
3921    public void insertNameLookupForPhoneticName(long rawContactId, long dataId, String familyName,
3922            String middleName, String givenName) {
3923        mSb.setLength(0);
3924        if (familyName != null) {
3925            mSb.append(familyName.trim());
3926        }
3927        if (middleName != null) {
3928            mSb.append(middleName.trim());
3929        }
3930        if (givenName != null) {
3931            mSb.append(givenName.trim());
3932        }
3933
3934        if (mSb.length() > 0) {
3935            insertNameLookup(rawContactId, dataId, NameLookupType.NAME_COLLATION_KEY,
3936                    NameNormalizer.normalize(mSb.toString()));
3937        }
3938    }
3939
3940    /**
3941     * Performs a query and returns true if any Data item of the raw contact with the given
3942     * id and mimetype is marked as super-primary
3943     */
3944    public boolean rawContactHasSuperPrimary(long rawContactId, long mimeTypeId) {
3945        final Cursor existsCursor = getReadableDatabase().rawQuery(
3946                "SELECT EXISTS(SELECT 1 FROM " + Tables.DATA +
3947                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
3948                " AND " + DataColumns.MIMETYPE_ID + "=?" +
3949                " AND " + Data.IS_SUPER_PRIMARY + "<>0)",
3950                new String[] { String.valueOf(rawContactId), String.valueOf(mimeTypeId) });
3951        try {
3952            if (!existsCursor.moveToFirst()) throw new IllegalStateException();
3953            return existsCursor.getInt(0) != 0;
3954        } finally {
3955            existsCursor.close();
3956        }
3957    }
3958
3959    public String getCurrentCountryIso() {
3960        return mCountryMonitor.getCountryIso();
3961    }
3962
3963    /* visible for testing */
3964    /* package */ String querySearchIndexContent(long contactId) {
3965        return DatabaseUtils.stringForQuery(getReadableDatabase(),
3966                "SELECT " + SearchIndexColumns.CONTENT +
3967                " FROM " + Tables.SEARCH_INDEX +
3968                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
3969                new String[] { String.valueOf(contactId) });
3970    }
3971
3972    /* visible for testing */
3973    /* package */ String querySearchIndexTokens(long contactId) {
3974        return DatabaseUtils.stringForQuery(getReadableDatabase(),
3975                "SELECT " + SearchIndexColumns.TOKENS +
3976                " FROM " + Tables.SEARCH_INDEX +
3977                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
3978                new String[] { String.valueOf(contactId) });
3979    }
3980}
3981