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