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