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