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