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