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