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