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