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