ContactsDatabaseHelper.java revision 2c4caaa35be9f8909e8eee26142c4747bbf65aac
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.common.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.CharArrayBuffer;
29import android.database.Cursor;
30import android.database.DatabaseUtils;
31import android.database.SQLException;
32import android.database.sqlite.SQLiteConstraintException;
33import android.database.sqlite.SQLiteDatabase;
34import android.database.sqlite.SQLiteDoneException;
35import android.database.sqlite.SQLiteException;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.database.sqlite.SQLiteQueryBuilder;
38import android.database.sqlite.SQLiteStatement;
39import android.location.CountryDetector;
40import android.net.Uri;
41import android.os.Binder;
42import android.os.Bundle;
43import android.os.SystemClock;
44import android.provider.BaseColumns;
45import android.provider.CallLog.Calls;
46import android.provider.ContactsContract;
47import android.provider.ContactsContract.AggregationExceptions;
48import android.provider.ContactsContract.CommonDataKinds.Email;
49import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
50import android.provider.ContactsContract.CommonDataKinds.Im;
51import android.provider.ContactsContract.CommonDataKinds.Nickname;
52import android.provider.ContactsContract.CommonDataKinds.Organization;
53import android.provider.ContactsContract.CommonDataKinds.Phone;
54import android.provider.ContactsContract.CommonDataKinds.SipAddress;
55import android.provider.ContactsContract.CommonDataKinds.StructuredName;
56import android.provider.ContactsContract.Contacts;
57import android.provider.ContactsContract.Contacts.Photo;
58import android.provider.ContactsContract.Data;
59import android.provider.ContactsContract.Directory;
60import android.provider.ContactsContract.DisplayNameSources;
61import android.provider.ContactsContract.DisplayPhoto;
62import android.provider.ContactsContract.FullNameStyle;
63import android.provider.ContactsContract.Groups;
64import android.provider.ContactsContract.PhoneticNameStyle;
65import android.provider.ContactsContract.PhotoFiles;
66import android.provider.ContactsContract.RawContacts;
67import android.provider.ContactsContract.Settings;
68import android.provider.ContactsContract.StatusUpdates;
69import android.provider.ContactsContract.StreamItemPhotos;
70import android.provider.ContactsContract.StreamItems;
71import android.provider.SocialContract.Activities;
72import android.provider.VoicemailContract;
73import android.provider.VoicemailContract.Voicemails;
74import android.telephony.PhoneNumberUtils;
75import android.text.TextUtils;
76import android.text.util.Rfc822Token;
77import android.text.util.Rfc822Tokenizer;
78import android.util.Log;
79
80import java.util.HashMap;
81import java.util.Locale;
82
83/**
84 * Database helper for contacts. Designed as a singleton to make sure that all
85 * {@link android.content.ContentProvider} users get the same reference.
86 * Provides handy methods for maintaining package and mime-type lookup tables.
87 */
88/* package */ class ContactsDatabaseHelper extends SQLiteOpenHelper {
89    private static final String TAG = "ContactsDatabaseHelper";
90
91    /**
92     * Contacts DB version ranges:
93     * <pre>
94     *   0-98    Cupcake/Donut
95     *   100-199 Eclair
96     *   200-299 Eclair-MR1
97     *   300-349 Froyo
98     *   350-399 Gingerbread
99     *   400-499 Honeycomb
100     *   500-549 Honeycomb-MR1
101     *   550-599 Honeycomb-MR2
102     *   600-699 Ice Cream Sandwich
103     * </pre>
104     */
105    static final int DATABASE_VERSION = 614;
106
107    private static final String DATABASE_NAME = "contacts2.db";
108    private static final String DATABASE_PRESENCE = "presence_db";
109
110    public interface Tables {
111        public static final String CONTACTS = "contacts";
112        public static final String RAW_CONTACTS = "raw_contacts";
113        public static final String STREAM_ITEMS = "stream_items";
114        public static final String STREAM_ITEM_PHOTOS = "stream_item_photos";
115        public static final String PHOTO_FILES = "photo_files";
116        public static final String PACKAGES = "packages";
117        public static final String MIMETYPES = "mimetypes";
118        public static final String PHONE_LOOKUP = "phone_lookup";
119        public static final String NAME_LOOKUP = "name_lookup";
120        public static final String AGGREGATION_EXCEPTIONS = "agg_exceptions";
121        public static final String SETTINGS = "settings";
122        public static final String DATA = "data";
123        public static final String GROUPS = "groups";
124        public static final String PRESENCE = "presence";
125        public static final String AGGREGATED_PRESENCE = "agg_presence";
126        public static final String NICKNAME_LOOKUP = "nickname_lookup";
127        public static final String CALLS = "calls";
128        public static final String STATUS_UPDATES = "status_updates";
129        public static final String PROPERTIES = "properties";
130        public static final String ACCOUNTS = "accounts";
131        public static final String VISIBLE_CONTACTS = "visible_contacts";
132        public static final String DIRECTORIES = "directories";
133        public static final String DEFAULT_DIRECTORY = "default_directory";
134        public static final String SEARCH_INDEX = "search_index";
135        public static final String VOICEMAIL_STATUS = "voicemail_status";
136
137        /**
138         * For {@link ContactsContract.DataUsageFeedback}. The table structure itself
139         * is not exposed outside.
140         */
141        public static final String DATA_USAGE_STAT = "data_usage_stat";
142
143        public static final String DATA_JOIN_MIMETYPES = "data "
144                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id)";
145
146        public static final String DATA_JOIN_RAW_CONTACTS = "data "
147                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
148
149        public static final String DATA_JOIN_MIMETYPE_RAW_CONTACTS = "data "
150                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
151                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
152
153        // NOTE: This requires late binding of GroupMembership MIME-type
154        public static final String RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS = "raw_contacts "
155                + "LEFT OUTER JOIN settings ON ("
156                    + "raw_contacts.account_name = settings.account_name AND "
157                    + "raw_contacts.account_type = settings.account_type) "
158                + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND "
159                    + "data.raw_contact_id = raw_contacts._id) "
160                + "LEFT OUTER JOIN groups ON (groups._id = data." + GroupMembership.GROUP_ROW_ID
161                + ")";
162
163        // NOTE: This requires late binding of GroupMembership MIME-type
164        public static final String SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS = "settings "
165                + "LEFT OUTER JOIN raw_contacts ON ("
166                    + "raw_contacts.account_name = settings.account_name AND "
167                    + "raw_contacts.account_type = settings.account_type) "
168                + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND "
169                    + "data.raw_contact_id = raw_contacts._id) "
170                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
171
172        public static final String CONTACTS_JOIN_RAW_CONTACTS_DATA_FILTERED_BY_GROUPMEMBERSHIP =
173                Tables.CONTACTS
174                    + " INNER JOIN " + Tables.RAW_CONTACTS
175                        + " ON (" + RawContactsColumns.CONCRETE_CONTACT_ID + "="
176                            + ContactsColumns.CONCRETE_ID
177                        + ")"
178                    + " INNER JOIN " + Tables.DATA
179                        + " ON (" + DataColumns.CONCRETE_DATA1 + "=" + GroupsColumns.CONCRETE_ID
180                        + " AND "
181                        + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID
182                        + " AND "
183                        + DataColumns.CONCRETE_MIMETYPE_ID + "="
184                            + "(SELECT " + MimetypesColumns._ID
185                            + " FROM " + Tables.MIMETYPES
186                            + " WHERE "
187                            + MimetypesColumns.CONCRETE_MIMETYPE + "="
188                                + "'" + GroupMembership.CONTENT_ITEM_TYPE + "'"
189                            + ")"
190                        + ")";
191
192        public static final String DATA_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_GROUPS = "data "
193                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
194                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
195                + "LEFT OUTER JOIN packages ON (data.package_id = packages._id) "
196                + "LEFT OUTER JOIN groups "
197                + "  ON (mimetypes.mimetype='" + GroupMembership.CONTENT_ITEM_TYPE + "' "
198                + "      AND groups._id = data." + GroupMembership.GROUP_ROW_ID + ") ";
199
200        public static final String GROUPS_JOIN_PACKAGES = "groups "
201                + "LEFT OUTER JOIN packages ON (groups.package_id = packages._id)";
202
203
204        public static final String ACTIVITIES = "activities";
205
206        public static final String ACTIVITIES_JOIN_MIMETYPES = "activities "
207                + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id)";
208
209        public static final String ACTIVITIES_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_CONTACTS =
210                "activities "
211                + "LEFT OUTER JOIN packages ON (activities.package_id = packages._id) "
212                + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id) "
213                + "LEFT OUTER JOIN raw_contacts ON (activities.author_contact_id = " +
214                        "raw_contacts._id) "
215                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
216
217        public static final String NAME_LOOKUP_JOIN_RAW_CONTACTS = "name_lookup "
218                + "INNER JOIN view_raw_contacts ON (name_lookup.raw_contact_id = "
219                + "view_raw_contacts._id)";
220    }
221
222    public interface Views {
223        public static final String DATA = "view_data";
224        public static final String RAW_CONTACTS = "view_raw_contacts";
225        public static final String CONTACTS = "view_contacts";
226        public static final String ENTITIES = "view_entities";
227        public static final String RAW_ENTITIES = "view_raw_entities";
228        public static final String GROUPS = "view_groups";
229        public static final String DATA_USAGE_STAT = "view_data_usage_stat";
230        public static final String STREAM_ITEMS = "view_stream_items";
231    }
232
233    public interface Clauses {
234        final String HAVING_NO_GROUPS = "COUNT(" + DataColumns.CONCRETE_GROUP_ID + ") == 0";
235
236        final String GROUP_BY_ACCOUNT_CONTACT_ID = SettingsColumns.CONCRETE_ACCOUNT_NAME + ","
237                + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "," + RawContacts.CONTACT_ID;
238
239        final String RAW_CONTACT_IS_LOCAL = RawContactsColumns.CONCRETE_ACCOUNT_NAME
240                + " IS NULL AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL AND "
241                + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL";
242
243        final String ZERO_GROUP_MEMBERSHIPS = "COUNT(" + GroupsColumns.CONCRETE_ID + ")=0";
244
245        final String OUTER_RAW_CONTACTS = "outer_raw_contacts";
246        final String OUTER_RAW_CONTACTS_ID = OUTER_RAW_CONTACTS + "." + RawContacts._ID;
247
248        final String CONTACT_IS_VISIBLE =
249                "SELECT " +
250                    "MAX((SELECT (CASE WHEN " +
251                        "(CASE" +
252                            " WHEN " + RAW_CONTACT_IS_LOCAL +
253                            " THEN 1 " +
254                            " WHEN " + ZERO_GROUP_MEMBERSHIPS +
255                            " THEN " + Settings.UNGROUPED_VISIBLE +
256                            " ELSE MAX(" + Groups.GROUP_VISIBLE + ")" +
257                         "END)=1 THEN 1 ELSE 0 END)" +
258                " FROM " + Tables.RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS +
259                " WHERE " + RawContactsColumns.CONCRETE_ID + "=" + OUTER_RAW_CONTACTS_ID + "))" +
260                " FROM " + Tables.RAW_CONTACTS + " AS " + OUTER_RAW_CONTACTS +
261                " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
262                " GROUP BY " + RawContacts.CONTACT_ID;
263
264        final String GROUP_HAS_ACCOUNT_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND "
265                + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=? AND "
266                + Groups.DATA_SET + " IS NULL";
267
268        final String GROUP_HAS_ACCOUNT_AND_DATA_SET_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND "
269                + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=? AND "
270                + Groups.DATA_SET + "=?";
271
272        public static final String CONTACT_VISIBLE =
273            "EXISTS (SELECT _id FROM " + Tables.VISIBLE_CONTACTS
274                + " WHERE " + Tables.CONTACTS +"." + Contacts._ID
275                        + "=" + Tables.VISIBLE_CONTACTS +"." + Contacts._ID + ")";
276    }
277
278    public interface ContactsColumns {
279        public static final String LAST_STATUS_UPDATE_ID = "status_update_id";
280
281        public static final String CONCRETE_ID = Tables.CONTACTS + "." + BaseColumns._ID;
282
283        public static final String CONCRETE_PHOTO_FILE_ID = Tables.CONTACTS + "."
284                + Contacts.PHOTO_FILE_ID;
285        public static final String CONCRETE_TIMES_CONTACTED = Tables.CONTACTS + "."
286                + Contacts.TIMES_CONTACTED;
287        public static final String CONCRETE_LAST_TIME_CONTACTED = Tables.CONTACTS + "."
288                + Contacts.LAST_TIME_CONTACTED;
289        public static final String CONCRETE_STARRED = Tables.CONTACTS + "." + Contacts.STARRED;
290        public static final String CONCRETE_CUSTOM_RINGTONE = Tables.CONTACTS + "."
291                + Contacts.CUSTOM_RINGTONE;
292        public static final String CONCRETE_SEND_TO_VOICEMAIL = Tables.CONTACTS + "."
293                + Contacts.SEND_TO_VOICEMAIL;
294        public static final String CONCRETE_LOOKUP_KEY = Tables.CONTACTS + "."
295                + Contacts.LOOKUP_KEY;
296    }
297
298    public interface RawContactsColumns {
299        public static final String CONCRETE_ID =
300                Tables.RAW_CONTACTS + "." + BaseColumns._ID;
301        public static final String CONCRETE_ACCOUNT_NAME =
302                Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_NAME;
303        public static final String CONCRETE_ACCOUNT_TYPE =
304                Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE;
305        public static final String CONCRETE_DATA_SET =
306                Tables.RAW_CONTACTS + "." + RawContacts.DATA_SET;
307        public static final String CONCRETE_ACCOUNT_TYPE_AND_DATA_SET =
308                Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE_AND_DATA_SET;
309        public static final String CONCRETE_SOURCE_ID =
310                Tables.RAW_CONTACTS + "." + RawContacts.SOURCE_ID;
311        public static final String CONCRETE_VERSION =
312                Tables.RAW_CONTACTS + "." + RawContacts.VERSION;
313        public static final String CONCRETE_DIRTY =
314                Tables.RAW_CONTACTS + "." + RawContacts.DIRTY;
315        public static final String CONCRETE_DELETED =
316                Tables.RAW_CONTACTS + "." + RawContacts.DELETED;
317        public static final String CONCRETE_SYNC1 =
318                Tables.RAW_CONTACTS + "." + RawContacts.SYNC1;
319        public static final String CONCRETE_SYNC2 =
320                Tables.RAW_CONTACTS + "." + RawContacts.SYNC2;
321        public static final String CONCRETE_SYNC3 =
322                Tables.RAW_CONTACTS + "." + RawContacts.SYNC3;
323        public static final String CONCRETE_SYNC4 =
324                Tables.RAW_CONTACTS + "." + RawContacts.SYNC4;
325        public static final String CONCRETE_CUSTOM_RINGTONE =
326                Tables.RAW_CONTACTS + "." + RawContacts.CUSTOM_RINGTONE;
327        public static final String CONCRETE_SEND_TO_VOICEMAIL =
328                Tables.RAW_CONTACTS + "." + RawContacts.SEND_TO_VOICEMAIL;
329        public static final String CONCRETE_LAST_TIME_CONTACTED =
330                Tables.RAW_CONTACTS + "." + RawContacts.LAST_TIME_CONTACTED;
331        public static final String CONCRETE_TIMES_CONTACTED =
332                Tables.RAW_CONTACTS + "." + RawContacts.TIMES_CONTACTED;
333        public static final String CONCRETE_STARRED =
334                Tables.RAW_CONTACTS + "." + RawContacts.STARRED;
335
336        public static final String DISPLAY_NAME = RawContacts.DISPLAY_NAME_PRIMARY;
337        public static final String DISPLAY_NAME_SOURCE = RawContacts.DISPLAY_NAME_SOURCE;
338        public static final String AGGREGATION_NEEDED = "aggregation_needed";
339
340        public static final String CONCRETE_DISPLAY_NAME =
341                Tables.RAW_CONTACTS + "." + DISPLAY_NAME;
342        public static final String CONCRETE_CONTACT_ID =
343                Tables.RAW_CONTACTS + "." + RawContacts.CONTACT_ID;
344        public static final String CONCRETE_NAME_VERIFIED =
345                Tables.RAW_CONTACTS + "." + RawContacts.NAME_VERIFIED;
346    }
347
348    public interface DataColumns {
349        public static final String PACKAGE_ID = "package_id";
350        public static final String MIMETYPE_ID = "mimetype_id";
351
352        public static final String CONCRETE_ID = Tables.DATA + "." + BaseColumns._ID;
353        public static final String CONCRETE_MIMETYPE_ID = Tables.DATA + "." + MIMETYPE_ID;
354        public static final String CONCRETE_RAW_CONTACT_ID = Tables.DATA + "."
355                + Data.RAW_CONTACT_ID;
356        public static final String CONCRETE_GROUP_ID = Tables.DATA + "."
357                + GroupMembership.GROUP_ROW_ID;
358
359        public static final String CONCRETE_DATA1 = Tables.DATA + "." + Data.DATA1;
360        public static final String CONCRETE_DATA2 = Tables.DATA + "." + Data.DATA2;
361        public static final String CONCRETE_DATA3 = Tables.DATA + "." + Data.DATA3;
362        public static final String CONCRETE_DATA4 = Tables.DATA + "." + Data.DATA4;
363        public static final String CONCRETE_DATA5 = Tables.DATA + "." + Data.DATA5;
364        public static final String CONCRETE_DATA6 = Tables.DATA + "." + Data.DATA6;
365        public static final String CONCRETE_DATA7 = Tables.DATA + "." + Data.DATA7;
366        public static final String CONCRETE_DATA8 = Tables.DATA + "." + Data.DATA8;
367        public static final String CONCRETE_DATA9 = Tables.DATA + "." + Data.DATA9;
368        public static final String CONCRETE_DATA10 = Tables.DATA + "." + Data.DATA10;
369        public static final String CONCRETE_DATA11 = Tables.DATA + "." + Data.DATA11;
370        public static final String CONCRETE_DATA12 = Tables.DATA + "." + Data.DATA12;
371        public static final String CONCRETE_DATA13 = Tables.DATA + "." + Data.DATA13;
372        public static final String CONCRETE_DATA14 = Tables.DATA + "." + Data.DATA14;
373        public static final String CONCRETE_DATA15 = Tables.DATA + "." + Data.DATA15;
374        public static final String CONCRETE_IS_PRIMARY = Tables.DATA + "." + Data.IS_PRIMARY;
375        public static final String CONCRETE_PACKAGE_ID = Tables.DATA + "." + PACKAGE_ID;
376    }
377
378    // Used only for legacy API support
379    public interface ExtensionsColumns {
380        public static final String NAME = Data.DATA1;
381        public static final String VALUE = Data.DATA2;
382    }
383
384    public interface GroupMembershipColumns {
385        public static final String RAW_CONTACT_ID = Data.RAW_CONTACT_ID;
386        public static final String GROUP_ROW_ID = GroupMembership.GROUP_ROW_ID;
387    }
388
389    public interface PhoneColumns {
390        public static final String NORMALIZED_NUMBER = Data.DATA4;
391        public static final String CONCRETE_NORMALIZED_NUMBER = DataColumns.CONCRETE_DATA4;
392    }
393
394    public interface GroupsColumns {
395        public static final String PACKAGE_ID = "package_id";
396
397        public static final String CONCRETE_ID = Tables.GROUPS + "." + BaseColumns._ID;
398        public static final String CONCRETE_SOURCE_ID = Tables.GROUPS + "." + Groups.SOURCE_ID;
399        public static final String CONCRETE_ACCOUNT_NAME =
400                Tables.GROUPS + "." + Groups.ACCOUNT_NAME;
401        public static final String CONCRETE_ACCOUNT_TYPE =
402                Tables.GROUPS + "." + Groups.ACCOUNT_TYPE;
403        public static final String CONCRETE_DATA_SET = Tables.GROUPS + "." + Groups.DATA_SET;
404        public static final String CONCRETE_ACCOUNT_TYPE_AND_DATA_SET = Tables.GROUPS + "." +
405                Groups.ACCOUNT_TYPE_AND_DATA_SET;
406    }
407
408    public interface ActivitiesColumns {
409        public static final String PACKAGE_ID = "package_id";
410        public static final String MIMETYPE_ID = "mimetype_id";
411    }
412
413    public interface PhoneLookupColumns {
414        public static final String _ID = BaseColumns._ID;
415        public static final String DATA_ID = "data_id";
416        public static final String RAW_CONTACT_ID = "raw_contact_id";
417        public static final String NORMALIZED_NUMBER = "normalized_number";
418        public static final String MIN_MATCH = "min_match";
419    }
420
421    public interface NameLookupColumns {
422        public static final String RAW_CONTACT_ID = "raw_contact_id";
423        public static final String DATA_ID = "data_id";
424        public static final String NORMALIZED_NAME = "normalized_name";
425        public static final String NAME_TYPE = "name_type";
426    }
427
428    public final static class NameLookupType {
429        public static final int NAME_EXACT = 0;
430        public static final int NAME_VARIANT = 1;
431        public static final int NAME_COLLATION_KEY = 2;
432        public static final int NICKNAME = 3;
433        public static final int EMAIL_BASED_NICKNAME = 4;
434
435        // This is the highest name lookup type code plus one
436        public static final int TYPE_COUNT = 5;
437
438        public static boolean isBasedOnStructuredName(int nameLookupType) {
439            return nameLookupType == NameLookupType.NAME_EXACT
440                    || nameLookupType == NameLookupType.NAME_VARIANT
441                    || nameLookupType == NameLookupType.NAME_COLLATION_KEY;
442        }
443    }
444
445    public interface PackagesColumns {
446        public static final String _ID = BaseColumns._ID;
447        public static final String PACKAGE = "package";
448
449        public static final String CONCRETE_ID = Tables.PACKAGES + "." + _ID;
450    }
451
452    public interface MimetypesColumns {
453        public static final String _ID = BaseColumns._ID;
454        public static final String MIMETYPE = "mimetype";
455
456        public static final String CONCRETE_ID = Tables.MIMETYPES + "." + BaseColumns._ID;
457        public static final String CONCRETE_MIMETYPE = Tables.MIMETYPES + "." + MIMETYPE;
458    }
459
460    public interface AggregationExceptionColumns {
461        public static final String _ID = BaseColumns._ID;
462    }
463
464    public interface NicknameLookupColumns {
465        public static final String NAME = "name";
466        public static final String CLUSTER = "cluster";
467    }
468
469    public interface SettingsColumns {
470        public static final String CONCRETE_ACCOUNT_NAME = Tables.SETTINGS + "."
471                + Settings.ACCOUNT_NAME;
472        public static final String CONCRETE_ACCOUNT_TYPE = Tables.SETTINGS + "."
473                + Settings.ACCOUNT_TYPE;
474    }
475
476    public interface PresenceColumns {
477        String RAW_CONTACT_ID = "presence_raw_contact_id";
478        String CONTACT_ID = "presence_contact_id";
479    }
480
481    public interface AggregatedPresenceColumns {
482        String CONTACT_ID = "presence_contact_id";
483
484        String CONCRETE_CONTACT_ID = Tables.AGGREGATED_PRESENCE + "." + CONTACT_ID;
485    }
486
487    public interface StatusUpdatesColumns {
488        String DATA_ID = "status_update_data_id";
489
490        String CONCRETE_DATA_ID = Tables.STATUS_UPDATES + "." + DATA_ID;
491
492        String CONCRETE_PRESENCE = Tables.STATUS_UPDATES + "." + StatusUpdates.PRESENCE;
493        String CONCRETE_STATUS = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS;
494        String CONCRETE_STATUS_TIMESTAMP = Tables.STATUS_UPDATES + "."
495                + StatusUpdates.STATUS_TIMESTAMP;
496        String CONCRETE_STATUS_RES_PACKAGE = Tables.STATUS_UPDATES + "."
497                + StatusUpdates.STATUS_RES_PACKAGE;
498        String CONCRETE_STATUS_LABEL = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_LABEL;
499        String CONCRETE_STATUS_ICON = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_ICON;
500    }
501
502    public interface ContactsStatusUpdatesColumns {
503        String ALIAS = "contacts_" + Tables.STATUS_UPDATES;
504
505        String CONCRETE_DATA_ID = ALIAS + "." + StatusUpdatesColumns.DATA_ID;
506
507        String CONCRETE_PRESENCE = ALIAS + "." + StatusUpdates.PRESENCE;
508        String CONCRETE_STATUS = ALIAS + "." + StatusUpdates.STATUS;
509        String CONCRETE_STATUS_TIMESTAMP = ALIAS + "." + StatusUpdates.STATUS_TIMESTAMP;
510        String CONCRETE_STATUS_RES_PACKAGE = ALIAS + "." + StatusUpdates.STATUS_RES_PACKAGE;
511        String CONCRETE_STATUS_LABEL = ALIAS + "." + StatusUpdates.STATUS_LABEL;
512        String CONCRETE_STATUS_ICON = ALIAS + "." + StatusUpdates.STATUS_ICON;
513    }
514
515    public interface StreamItemsColumns {
516        final String CONCRETE_ID = Tables.STREAM_ITEMS + "." + BaseColumns._ID;
517        final String CONCRETE_RAW_CONTACT_ID =
518                Tables.STREAM_ITEMS + "." + StreamItems.RAW_CONTACT_ID;
519        final String CONCRETE_PACKAGE = Tables.STREAM_ITEMS + "." + StreamItems.RES_PACKAGE;
520        final String CONCRETE_ICON = Tables.STREAM_ITEMS + "." + StreamItems.RES_ICON;
521        final String CONCRETE_LABEL = Tables.STREAM_ITEMS + "." + StreamItems.RES_LABEL;
522        final String CONCRETE_TEXT = Tables.STREAM_ITEMS + "." + StreamItems.TEXT;
523        final String CONCRETE_TIMESTAMP = Tables.STREAM_ITEMS + "." + StreamItems.TIMESTAMP;
524        final String CONCRETE_COMMENTS = Tables.STREAM_ITEMS + "." + StreamItems.COMMENTS;
525        final String CONCRETE_SYNC1 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC1;
526        final String CONCRETE_SYNC2 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC2;
527        final String CONCRETE_SYNC3 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC3;
528        final String CONCRETE_SYNC4 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC4;
529    }
530
531    public interface StreamItemPhotosColumns {
532        final String CONCRETE_ID = Tables.STREAM_ITEM_PHOTOS + "." + BaseColumns._ID;
533        final String CONCRETE_STREAM_ITEM_ID = Tables.STREAM_ITEM_PHOTOS + "."
534                + StreamItemPhotos.STREAM_ITEM_ID;
535        final String CONCRETE_SORT_INDEX =
536                Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SORT_INDEX;
537        final String CONCRETE_PHOTO_FILE_ID = Tables.STREAM_ITEM_PHOTOS + "."
538                + StreamItemPhotos.PHOTO_FILE_ID;
539        final String CONCRETE_SYNC1 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC1;
540        final String CONCRETE_SYNC2 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC2;
541        final String CONCRETE_SYNC3 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC3;
542        final String CONCRETE_SYNC4 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC4;
543    }
544
545    public interface PhotoFilesColumns {
546        String CONCRETE_ID = Tables.PHOTO_FILES + "." + BaseColumns._ID;
547        String CONCRETE_HEIGHT = Tables.PHOTO_FILES + "." + PhotoFiles.HEIGHT;
548        String CONCRETE_WIDTH = Tables.PHOTO_FILES + "." + PhotoFiles.WIDTH;
549        String CONCRETE_FILESIZE = Tables.PHOTO_FILES + "." + PhotoFiles.FILESIZE;
550    }
551
552    public interface PropertiesColumns {
553        String PROPERTY_KEY = "property_key";
554        String PROPERTY_VALUE = "property_value";
555    }
556
557    public interface AccountsColumns {
558        String ACCOUNT_NAME = RawContacts.ACCOUNT_NAME;
559        String ACCOUNT_TYPE = RawContacts.ACCOUNT_TYPE;
560        String DATA_SET = RawContacts.DATA_SET;
561        String PROFILE_RAW_CONTACT_ID = "profile_raw_contact_id";
562    }
563
564    public static final class DirectoryColumns {
565        public static final String TYPE_RESOURCE_NAME = "typeResourceName";
566    }
567
568    public static final class SearchIndexColumns {
569        public static final String CONTACT_ID = "contact_id";
570        public static final String CONTENT = "content";
571        public static final String NAME = "name";
572        public static final String TOKENS = "tokens";
573    }
574
575    /**
576     * Private table for calculating per-contact-method ranking.
577     */
578    public static final class DataUsageStatColumns {
579        /** type: INTEGER (long) */
580        public static final String _ID = "stat_id";
581        public static final String CONCRETE_ID = Tables.DATA_USAGE_STAT + "." + _ID;
582
583        /** type: INTEGER (long) */
584        public static final String DATA_ID = "data_id";
585        public static final String CONCRETE_DATA_ID = Tables.DATA_USAGE_STAT + "." + DATA_ID;
586
587        /** type: INTEGER (long) */
588        public static final String LAST_TIME_USED = "last_time_used";
589        public static final String CONCRETE_LAST_TIME_USED =
590                Tables.DATA_USAGE_STAT + "." + LAST_TIME_USED;
591
592        /** type: INTEGER */
593        public static final String TIMES_USED = "times_used";
594        public static final String CONCRETE_TIMES_USED =
595                Tables.DATA_USAGE_STAT + "." + TIMES_USED;
596
597        /** type: INTEGER */
598        public static final String USAGE_TYPE_INT = "usage_type";
599        public static final String CONCRETE_USAGE_TYPE =
600                Tables.DATA_USAGE_STAT + "." + USAGE_TYPE_INT;
601
602        /**
603         * Integer values for USAGE_TYPE.
604         *
605         * @see ContactsContract.DataUsageFeedback#USAGE_TYPE
606         */
607        public static final int USAGE_TYPE_INT_CALL = 0;
608        public static final int USAGE_TYPE_INT_LONG_TEXT = 1;
609        public static final int USAGE_TYPE_INT_SHORT_TEXT = 2;
610    }
611
612    /** In-memory cache of previously found MIME-type mappings */
613    private final HashMap<String, Long> mMimetypeCache = new HashMap<String, Long>();
614    /** In-memory cache of previously found package name mappings */
615    private final HashMap<String, Long> mPackageCache = new HashMap<String, Long>();
616
617    private long mMimeTypeIdEmail;
618    private long mMimeTypeIdIm;
619    private long mMimeTypeIdSip;
620    private long mMimeTypeIdStructuredName;
621    private long mMimeTypeIdOrganization;
622    private long mMimeTypeIdNickname;
623    private long mMimeTypeIdPhone;
624
625    /** Compiled statements for querying and inserting mappings */
626    private SQLiteStatement mMimetypeQuery;
627    private SQLiteStatement mPackageQuery;
628    private SQLiteStatement mContactIdQuery;
629    private SQLiteStatement mAggregationModeQuery;
630    private SQLiteStatement mMimetypeInsert;
631    private SQLiteStatement mPackageInsert;
632    private SQLiteStatement mDataMimetypeQuery;
633    private SQLiteStatement mActivitiesMimetypeQuery;
634
635    /** Precompiled sql statement for setting a data record to the primary. */
636    private SQLiteStatement mSetPrimaryStatement;
637    /** Precompiled sql statement for setting a data record to the super primary. */
638    private SQLiteStatement mSetSuperPrimaryStatement;
639    /** Precompiled sql statement for clearing super primary of a single record. */
640    private SQLiteStatement mClearSuperPrimaryStatement;
641    /** Precompiled sql statement for updating a contact display name */
642    private SQLiteStatement mRawContactDisplayNameUpdate;
643
644    private SQLiteStatement mNameLookupInsert;
645    private SQLiteStatement mNameLookupDelete;
646    private SQLiteStatement mStatusUpdateAutoTimestamp;
647    private SQLiteStatement mStatusUpdateInsert;
648    private SQLiteStatement mStatusUpdateReplace;
649    private SQLiteStatement mStatusAttributionUpdate;
650    private SQLiteStatement mStatusUpdateDelete;
651    private SQLiteStatement mResetNameVerifiedForOtherRawContacts;
652    private SQLiteStatement mContactInDefaultDirectoryQuery;
653
654    private final Context mContext;
655    private final boolean mDatabaseOptimizationEnabled;
656    private final SyncStateContentProviderHelper mSyncState;
657    private final CountryMonitor mCountryMonitor;
658    private StringBuilder mSb = new StringBuilder();
659
660    private boolean mReopenDatabase = false;
661
662    private static ContactsDatabaseHelper sSingleton = null;
663
664    private boolean mUseStrictPhoneNumberComparison;
665
666    private String[] mSelectionArgs1 = new String[1];
667    private NameSplitter.Name mName = new NameSplitter.Name();
668    private CharArrayBuffer mCharArrayBuffer = new CharArrayBuffer(128);
669    private NameSplitter mNameSplitter;
670
671    public static synchronized ContactsDatabaseHelper getInstance(Context context) {
672        if (sSingleton == null) {
673            sSingleton = new ContactsDatabaseHelper(context, DATABASE_NAME, true);
674        }
675        return sSingleton;
676    }
677
678    /**
679     * Private constructor, callers except unit tests should obtain an instance through
680     * {@link #getInstance(android.content.Context)} instead.
681     */
682    ContactsDatabaseHelper(Context context) {
683        this(context, null, false);
684    }
685
686    private ContactsDatabaseHelper(
687            Context context, String databaseName, boolean optimizationEnabled) {
688        super(context, databaseName, null, DATABASE_VERSION);
689        mDatabaseOptimizationEnabled = optimizationEnabled;
690        Resources resources = context.getResources();
691
692        mContext = context;
693        mSyncState = new SyncStateContentProviderHelper();
694        mCountryMonitor = new CountryMonitor(context);
695        mUseStrictPhoneNumberComparison =
696                resources.getBoolean(
697                        com.android.internal.R.bool.config_use_strict_phone_number_comparation);
698    }
699
700    private void refreshDatabaseCaches(SQLiteDatabase db) {
701        mStatusUpdateDelete = null;
702        mStatusUpdateReplace = null;
703        mStatusUpdateInsert = null;
704        mStatusUpdateAutoTimestamp = null;
705        mStatusAttributionUpdate = null;
706        mResetNameVerifiedForOtherRawContacts = null;
707        mRawContactDisplayNameUpdate = null;
708        mSetPrimaryStatement = null;
709        mClearSuperPrimaryStatement = null;
710        mSetSuperPrimaryStatement = null;
711        mNameLookupInsert = null;
712        mNameLookupDelete = null;
713        mPackageQuery = null;
714        mPackageInsert = null;
715        mDataMimetypeQuery = null;
716        mActivitiesMimetypeQuery = null;
717        mContactIdQuery = null;
718        mAggregationModeQuery = null;
719        mContactInDefaultDirectoryQuery = null;
720
721        populateMimeTypeCache(db);
722    }
723
724    private void populateMimeTypeCache(SQLiteDatabase db) {
725        mMimetypeCache.clear();
726        mPackageCache.clear();
727
728        mMimetypeQuery = db.compileStatement(
729                "SELECT " + MimetypesColumns._ID +
730                " FROM " + Tables.MIMETYPES +
731                " WHERE " + MimetypesColumns.MIMETYPE + "=?");
732
733        mMimetypeInsert = db.compileStatement(
734                "INSERT INTO " + Tables.MIMETYPES + "("
735                        + MimetypesColumns.MIMETYPE +
736                ") VALUES (?)");
737
738        mMimeTypeIdEmail = getMimeTypeId(Email.CONTENT_ITEM_TYPE);
739        mMimeTypeIdIm = getMimeTypeId(Im.CONTENT_ITEM_TYPE);
740        mMimeTypeIdSip = getMimeTypeId(SipAddress.CONTENT_ITEM_TYPE);
741        mMimeTypeIdStructuredName = getMimeTypeId(StructuredName.CONTENT_ITEM_TYPE);
742        mMimeTypeIdOrganization = getMimeTypeId(Organization.CONTENT_ITEM_TYPE);
743        mMimeTypeIdNickname = getMimeTypeId(Nickname.CONTENT_ITEM_TYPE);
744        mMimeTypeIdPhone = getMimeTypeId(Phone.CONTENT_ITEM_TYPE);
745    }
746
747    @Override
748    public void onOpen(SQLiteDatabase db) {
749        refreshDatabaseCaches(db);
750
751        mSyncState.onDatabaseOpened(db);
752
753        db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";");
754        db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_PRESENCE + "." + Tables.PRESENCE + " ("+
755                StatusUpdates.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
756                StatusUpdates.PROTOCOL + " INTEGER NOT NULL," +
757                StatusUpdates.CUSTOM_PROTOCOL + " TEXT," +
758                StatusUpdates.IM_HANDLE + " TEXT," +
759                StatusUpdates.IM_ACCOUNT + " TEXT," +
760                PresenceColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
761                PresenceColumns.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
762                StatusUpdates.PRESENCE + " INTEGER," +
763                StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0," +
764                "UNIQUE(" + StatusUpdates.PROTOCOL + ", " + StatusUpdates.CUSTOM_PROTOCOL
765                    + ", " + StatusUpdates.IM_HANDLE + ", " + StatusUpdates.IM_ACCOUNT + ")" +
766        ");");
767
768        db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex" + " ON "
769                + Tables.PRESENCE + " (" + PresenceColumns.RAW_CONTACT_ID + ");");
770        db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex2" + " ON "
771                + Tables.PRESENCE + " (" + PresenceColumns.CONTACT_ID + ");");
772
773        db.execSQL("CREATE TABLE IF NOT EXISTS "
774                + DATABASE_PRESENCE + "." + Tables.AGGREGATED_PRESENCE + " ("+
775                AggregatedPresenceColumns.CONTACT_ID
776                        + " INTEGER PRIMARY KEY REFERENCES contacts(_id)," +
777                StatusUpdates.PRESENCE + " INTEGER," +
778                StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0" +
779        ");");
780
781
782        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_deleted"
783                + " BEFORE DELETE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
784                + " BEGIN "
785                + "   DELETE FROM " + Tables.AGGREGATED_PRESENCE
786                + "     WHERE " + AggregatedPresenceColumns.CONTACT_ID + " = " +
787                        "(SELECT " + PresenceColumns.CONTACT_ID +
788                        " FROM " + Tables.PRESENCE +
789                        " WHERE " + PresenceColumns.RAW_CONTACT_ID
790                                + "=OLD." + PresenceColumns.RAW_CONTACT_ID +
791                        " AND NOT EXISTS" +
792                                "(SELECT " + PresenceColumns.RAW_CONTACT_ID +
793                                " FROM " + Tables.PRESENCE +
794                                " WHERE " + PresenceColumns.CONTACT_ID
795                                        + "=OLD." + PresenceColumns.CONTACT_ID +
796                                " AND " + PresenceColumns.RAW_CONTACT_ID
797                                        + "!=OLD." + PresenceColumns.RAW_CONTACT_ID + "));"
798                + " END");
799
800        final String replaceAggregatePresenceSql =
801                "INSERT OR REPLACE INTO " + Tables.AGGREGATED_PRESENCE + "("
802                        + AggregatedPresenceColumns.CONTACT_ID + ", "
803                        + StatusUpdates.PRESENCE + ", "
804                        + StatusUpdates.CHAT_CAPABILITY + ")"
805                + " SELECT "
806                        + PresenceColumns.CONTACT_ID + ","
807                        + StatusUpdates.PRESENCE + ","
808                        + StatusUpdates.CHAT_CAPABILITY
809                + " FROM " + Tables.PRESENCE
810                + " WHERE "
811                    + " (ifnull(" + StatusUpdates.PRESENCE + ",0)  * 10 "
812                            + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))"
813                    + " = (SELECT "
814                        + "MAX (ifnull(" + StatusUpdates.PRESENCE + ",0)  * 10 "
815                                + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))"
816                        + " FROM " + Tables.PRESENCE
817                        + " WHERE " + PresenceColumns.CONTACT_ID
818                            + "=NEW." + PresenceColumns.CONTACT_ID
819                    + ")"
820                + " AND " + PresenceColumns.CONTACT_ID + "=NEW." + PresenceColumns.CONTACT_ID + ";";
821
822        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_inserted"
823                + " AFTER INSERT ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
824                + " BEGIN "
825                + replaceAggregatePresenceSql
826                + " END");
827
828        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_updated"
829                + " AFTER UPDATE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
830                + " BEGIN "
831                + replaceAggregatePresenceSql
832                + " END");
833    }
834
835    @Override
836    public void onCreate(SQLiteDatabase db) {
837        Log.i(TAG, "Bootstrapping database version: " + DATABASE_VERSION);
838
839        mSyncState.createDatabase(db);
840
841        // One row per group of contacts corresponding to the same person
842        db.execSQL("CREATE TABLE " + Tables.CONTACTS + " (" +
843                BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
844                Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
845                Contacts.PHOTO_ID + " INTEGER REFERENCES data(_id)," +
846                Contacts.PHOTO_FILE_ID + " INTEGER REFERENCES photo_files(_id)," +
847                Contacts.CUSTOM_RINGTONE + " TEXT," +
848                Contacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
849                Contacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
850                Contacts.LAST_TIME_CONTACTED + " INTEGER," +
851                Contacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
852                Contacts.HAS_PHONE_NUMBER + " INTEGER NOT NULL DEFAULT 0," +
853                Contacts.LOOKUP_KEY + " TEXT," +
854                ContactsColumns.LAST_STATUS_UPDATE_ID + " INTEGER REFERENCES data(_id)" +
855        ");");
856
857        db.execSQL("CREATE INDEX contacts_has_phone_index ON " + Tables.CONTACTS + " (" +
858                Contacts.HAS_PHONE_NUMBER +
859        ");");
860
861        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
862                Contacts.NAME_RAW_CONTACT_ID +
863        ");");
864
865        // Contacts table
866        db.execSQL("CREATE TABLE " + Tables.RAW_CONTACTS + " (" +
867                RawContacts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
868                RawContacts.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
869                RawContacts.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
870                RawContacts.DATA_SET + " STRING DEFAULT NULL, " +
871                RawContacts.SOURCE_ID + " TEXT," +
872                RawContacts.RAW_CONTACT_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," +
873                RawContacts.VERSION + " INTEGER NOT NULL DEFAULT 1," +
874                RawContacts.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
875                RawContacts.DELETED + " INTEGER NOT NULL DEFAULT 0," +
876                RawContacts.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
877                RawContacts.AGGREGATION_MODE + " INTEGER NOT NULL DEFAULT " +
878                        RawContacts.AGGREGATION_MODE_DEFAULT + "," +
879                RawContactsColumns.AGGREGATION_NEEDED + " INTEGER NOT NULL DEFAULT 1," +
880                RawContacts.CUSTOM_RINGTONE + " TEXT," +
881                RawContacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
882                RawContacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
883                RawContacts.LAST_TIME_CONTACTED + " INTEGER," +
884                RawContacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
885                RawContacts.DISPLAY_NAME_PRIMARY + " TEXT," +
886                RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT," +
887                RawContacts.DISPLAY_NAME_SOURCE + " INTEGER NOT NULL DEFAULT " +
888                        DisplayNameSources.UNDEFINED + "," +
889                RawContacts.PHONETIC_NAME + " TEXT," +
890                RawContacts.PHONETIC_NAME_STYLE + " TEXT," +
891                RawContacts.SORT_KEY_PRIMARY + " TEXT COLLATE " +
892                        ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," +
893                RawContacts.SORT_KEY_ALTERNATIVE + " TEXT COLLATE " +
894                        ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," +
895                RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0," +
896                RawContacts.SYNC1 + " TEXT, " +
897                RawContacts.SYNC2 + " TEXT, " +
898                RawContacts.SYNC3 + " TEXT, " +
899                RawContacts.SYNC4 + " TEXT " +
900        ");");
901
902        db.execSQL("CREATE INDEX raw_contacts_contact_id_index ON " + Tables.RAW_CONTACTS + " (" +
903                RawContacts.CONTACT_ID +
904        ");");
905
906        db.execSQL("CREATE INDEX raw_contacts_source_id_index ON " + Tables.RAW_CONTACTS + " (" +
907                RawContacts.SOURCE_ID + ", " +
908                RawContacts.ACCOUNT_TYPE + ", " +
909                RawContacts.ACCOUNT_NAME +
910        ");");
911
912        db.execSQL("CREATE INDEX raw_contacts_source_id_data_set_index ON " +
913                Tables.RAW_CONTACTS + " (" +
914                    RawContacts.SOURCE_ID + ", " +
915                    RawContacts.ACCOUNT_TYPE + ", " +
916                    RawContacts.ACCOUNT_NAME + ", " +
917                    RawContacts.DATA_SET +
918                ");");
919
920        db.execSQL("CREATE TABLE " + Tables.STREAM_ITEMS + " (" +
921                StreamItems._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
922                StreamItems.RAW_CONTACT_ID + " INTEGER NOT NULL, " +
923                StreamItems.RES_PACKAGE + " TEXT, " +
924                StreamItems.RES_ICON + " TEXT, " +
925                StreamItems.RES_LABEL + " TEXT, " +
926                StreamItems.TEXT + " TEXT, " +
927                StreamItems.TIMESTAMP + " INTEGER NOT NULL, " +
928                StreamItems.COMMENTS + " TEXT, " +
929                StreamItems.SYNC1 + " TEXT, " +
930                StreamItems.SYNC2 + " TEXT, " +
931                StreamItems.SYNC3 + " TEXT, " +
932                StreamItems.SYNC4 + " TEXT, " +
933                "FOREIGN KEY(" + StreamItems.RAW_CONTACT_ID + ") REFERENCES " +
934                        Tables.RAW_CONTACTS + "(" + RawContacts._ID + "));");
935
936        db.execSQL("CREATE TABLE " + Tables.STREAM_ITEM_PHOTOS + " (" +
937                StreamItemPhotos._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
938                StreamItemPhotos.STREAM_ITEM_ID + " INTEGER NOT NULL, " +
939                StreamItemPhotos.SORT_INDEX + " INTEGER, " +
940                StreamItemPhotos.PHOTO_FILE_ID + " INTEGER NOT NULL, " +
941                StreamItemPhotos.SYNC1 + " TEXT, " +
942                StreamItemPhotos.SYNC2 + " TEXT, " +
943                StreamItemPhotos.SYNC3 + " TEXT, " +
944                StreamItemPhotos.SYNC4 + " TEXT, " +
945                "FOREIGN KEY(" + StreamItemPhotos.STREAM_ITEM_ID + ") REFERENCES " +
946                        Tables.STREAM_ITEMS + "(" + StreamItems._ID + "));");
947
948        db.execSQL("CREATE TABLE " + Tables.PHOTO_FILES + " (" +
949                PhotoFiles._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
950                PhotoFiles.HEIGHT + " INTEGER NOT NULL, " +
951                PhotoFiles.WIDTH + " INTEGER NOT NULL, " +
952                PhotoFiles.FILESIZE + " INTEGER NOT NULL);");
953
954        // TODO readd the index and investigate a controlled use of it
955//        db.execSQL("CREATE INDEX raw_contacts_agg_index ON " + Tables.RAW_CONTACTS + " (" +
956//                RawContactsColumns.AGGREGATION_NEEDED +
957//        ");");
958
959        // Package name mapping table
960        db.execSQL("CREATE TABLE " + Tables.PACKAGES + " (" +
961                PackagesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
962                PackagesColumns.PACKAGE + " TEXT NOT NULL" +
963        ");");
964
965        // Mimetype mapping table
966        db.execSQL("CREATE TABLE " + Tables.MIMETYPES + " (" +
967                MimetypesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
968                MimetypesColumns.MIMETYPE + " TEXT NOT NULL" +
969        ");");
970
971        // Mimetype table requires an index on mime type
972        db.execSQL("CREATE UNIQUE INDEX mime_type ON " + Tables.MIMETYPES + " (" +
973                MimetypesColumns.MIMETYPE +
974        ");");
975
976        // Public generic data table
977        db.execSQL("CREATE TABLE " + Tables.DATA + " (" +
978                Data._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
979                DataColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
980                DataColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
981                Data.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
982                Data.IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," +
983                Data.IS_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
984                Data.IS_SUPER_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
985                Data.DATA_VERSION + " INTEGER NOT NULL DEFAULT 0," +
986                Data.DATA1 + " TEXT," +
987                Data.DATA2 + " TEXT," +
988                Data.DATA3 + " TEXT," +
989                Data.DATA4 + " TEXT," +
990                Data.DATA5 + " TEXT," +
991                Data.DATA6 + " TEXT," +
992                Data.DATA7 + " TEXT," +
993                Data.DATA8 + " TEXT," +
994                Data.DATA9 + " TEXT," +
995                Data.DATA10 + " TEXT," +
996                Data.DATA11 + " TEXT," +
997                Data.DATA12 + " TEXT," +
998                Data.DATA13 + " TEXT," +
999                Data.DATA14 + " TEXT," +
1000                Data.DATA15 + " TEXT," +
1001                Data.SYNC1 + " TEXT, " +
1002                Data.SYNC2 + " TEXT, " +
1003                Data.SYNC3 + " TEXT, " +
1004                Data.SYNC4 + " TEXT " +
1005        ");");
1006
1007        db.execSQL("CREATE INDEX data_raw_contact_id ON " + Tables.DATA + " (" +
1008                Data.RAW_CONTACT_ID +
1009        ");");
1010
1011        /**
1012         * For email lookup and similar queries.
1013         */
1014        db.execSQL("CREATE INDEX data_mimetype_data1_index ON " + Tables.DATA + " (" +
1015                DataColumns.MIMETYPE_ID + "," +
1016                Data.DATA1 +
1017        ");");
1018
1019        // Private phone numbers table used for lookup
1020        db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
1021                PhoneLookupColumns.DATA_ID
1022                        + " INTEGER REFERENCES data(_id) NOT NULL," +
1023                PhoneLookupColumns.RAW_CONTACT_ID
1024                        + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
1025                PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
1026                PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
1027        ");");
1028
1029        db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
1030                PhoneLookupColumns.NORMALIZED_NUMBER + "," +
1031                PhoneLookupColumns.RAW_CONTACT_ID + "," +
1032                PhoneLookupColumns.DATA_ID +
1033        ");");
1034
1035        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
1036                PhoneLookupColumns.MIN_MATCH + "," +
1037                PhoneLookupColumns.RAW_CONTACT_ID + "," +
1038                PhoneLookupColumns.DATA_ID +
1039        ");");
1040
1041        db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP +
1042                " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");");
1043
1044        // Private name/nickname table used for lookup
1045        db.execSQL("CREATE TABLE " + Tables.NAME_LOOKUP + " (" +
1046                NameLookupColumns.DATA_ID
1047                        + " INTEGER REFERENCES data(_id) NOT NULL," +
1048                NameLookupColumns.RAW_CONTACT_ID
1049                        + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
1050                NameLookupColumns.NORMALIZED_NAME + " TEXT NOT NULL," +
1051                NameLookupColumns.NAME_TYPE + " INTEGER NOT NULL," +
1052                "PRIMARY KEY ("
1053                        + NameLookupColumns.DATA_ID + ", "
1054                        + NameLookupColumns.NORMALIZED_NAME + ", "
1055                        + NameLookupColumns.NAME_TYPE + ")" +
1056        ");");
1057
1058        db.execSQL("CREATE INDEX name_lookup_raw_contact_id_index ON " + Tables.NAME_LOOKUP + " (" +
1059                NameLookupColumns.RAW_CONTACT_ID +
1060        ");");
1061
1062        db.execSQL("CREATE TABLE " + Tables.NICKNAME_LOOKUP + " (" +
1063                NicknameLookupColumns.NAME + " TEXT," +
1064                NicknameLookupColumns.CLUSTER + " TEXT" +
1065        ");");
1066
1067        db.execSQL("CREATE UNIQUE INDEX nickname_lookup_index ON " + Tables.NICKNAME_LOOKUP + " (" +
1068                NicknameLookupColumns.NAME + ", " +
1069                NicknameLookupColumns.CLUSTER +
1070        ");");
1071
1072        // Groups table
1073        db.execSQL("CREATE TABLE " + Tables.GROUPS + " (" +
1074                Groups._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1075                GroupsColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
1076                Groups.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
1077                Groups.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
1078                Groups.DATA_SET + " STRING DEFAULT NULL, " +
1079                Groups.SOURCE_ID + " TEXT," +
1080                Groups.VERSION + " INTEGER NOT NULL DEFAULT 1," +
1081                Groups.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
1082                Groups.TITLE + " TEXT," +
1083                Groups.TITLE_RES + " INTEGER," +
1084                Groups.NOTES + " TEXT," +
1085                Groups.SYSTEM_ID + " TEXT," +
1086                Groups.DELETED + " INTEGER NOT NULL DEFAULT 0," +
1087                Groups.GROUP_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
1088                Groups.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1," +
1089                Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0," +
1090                Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0," +
1091                Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," +
1092                Groups.SYNC1 + " TEXT, " +
1093                Groups.SYNC2 + " TEXT, " +
1094                Groups.SYNC3 + " TEXT, " +
1095                Groups.SYNC4 + " TEXT " +
1096        ");");
1097
1098        db.execSQL("CREATE INDEX groups_source_id_index ON " + Tables.GROUPS + " (" +
1099                Groups.SOURCE_ID + ", " +
1100                Groups.ACCOUNT_TYPE + ", " +
1101                Groups.ACCOUNT_NAME +
1102        ");");
1103
1104        db.execSQL("CREATE INDEX groups_source_id_data_set_index ON " + Tables.GROUPS + " (" +
1105                Groups.SOURCE_ID + ", " +
1106                Groups.ACCOUNT_TYPE + ", " +
1107                Groups.ACCOUNT_NAME + ", " +
1108                Groups.DATA_SET +
1109        ");");
1110
1111        db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.AGGREGATION_EXCEPTIONS + " (" +
1112                AggregationExceptionColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1113                AggregationExceptions.TYPE + " INTEGER NOT NULL, " +
1114                AggregationExceptions.RAW_CONTACT_ID1
1115                        + " INTEGER REFERENCES raw_contacts(_id), " +
1116                AggregationExceptions.RAW_CONTACT_ID2
1117                        + " INTEGER REFERENCES raw_contacts(_id)" +
1118        ");");
1119
1120        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index1 ON " +
1121                Tables.AGGREGATION_EXCEPTIONS + " (" +
1122                AggregationExceptions.RAW_CONTACT_ID1 + ", " +
1123                AggregationExceptions.RAW_CONTACT_ID2 +
1124        ");");
1125
1126        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index2 ON " +
1127                Tables.AGGREGATION_EXCEPTIONS + " (" +
1128                AggregationExceptions.RAW_CONTACT_ID2 + ", " +
1129                AggregationExceptions.RAW_CONTACT_ID1 +
1130        ");");
1131
1132        db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.SETTINGS + " (" +
1133                Settings.ACCOUNT_NAME + " STRING NOT NULL," +
1134                Settings.ACCOUNT_TYPE + " STRING NOT NULL," +
1135                Settings.UNGROUPED_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
1136                Settings.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1, " +
1137                "PRIMARY KEY (" + Settings.ACCOUNT_NAME + ", " +
1138                    Settings.ACCOUNT_TYPE + ") ON CONFLICT REPLACE" +
1139        ");");
1140
1141        db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" +
1142                Contacts._ID + " INTEGER PRIMARY KEY" +
1143        ");");
1144
1145        db.execSQL("CREATE TABLE " + Tables.DEFAULT_DIRECTORY + " (" +
1146                Contacts._ID + " INTEGER PRIMARY KEY" +
1147        ");");
1148
1149        // The table for recent calls is here so we can do table joins
1150        // on people, phones, and calls all in one place.
1151        db.execSQL("CREATE TABLE " + Tables.CALLS + " (" +
1152                Calls._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1153                Calls.NUMBER + " TEXT," +
1154                Calls.DATE + " INTEGER," +
1155                Calls.DURATION + " INTEGER," +
1156                Calls.TYPE + " INTEGER," +
1157                Calls.NEW + " INTEGER," +
1158                Calls.CACHED_NAME + " TEXT," +
1159                Calls.CACHED_NUMBER_TYPE + " INTEGER," +
1160                Calls.CACHED_NUMBER_LABEL + " TEXT," +
1161                Calls.COUNTRY_ISO + " TEXT," +
1162                Calls.VOICEMAIL_URI + " TEXT," +
1163                Calls.IS_READ + " INTEGER," +
1164                Calls.GEOCODED_LOCATION + " TEXT," +
1165                Voicemails._DATA + " TEXT," +
1166                Voicemails.HAS_CONTENT + " INTEGER," +
1167                Voicemails.MIME_TYPE + " TEXT," +
1168                Voicemails.SOURCE_DATA + " TEXT," +
1169                Voicemails.SOURCE_PACKAGE + " TEXT," +
1170                Voicemails.STATE + " INTEGER" +
1171        ");");
1172
1173        // Voicemail source status table.
1174        db.execSQL("CREATE TABLE " + Tables.VOICEMAIL_STATUS + " (" +
1175                VoicemailContract.Status._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1176                VoicemailContract.Status.SOURCE_PACKAGE + " TEXT UNIQUE NOT NULL," +
1177                VoicemailContract.Status.SETTINGS_URI + " TEXT," +
1178                VoicemailContract.Status.VOICEMAIL_ACCESS_URI + " TEXT," +
1179                VoicemailContract.Status.CONFIGURATION_STATE + " INTEGER," +
1180                VoicemailContract.Status.DATA_CHANNEL_STATE + " INTEGER," +
1181                VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE + " INTEGER" +
1182        ");");
1183
1184        // Activities table
1185        db.execSQL("CREATE TABLE " + Tables.ACTIVITIES + " (" +
1186                Activities._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1187                ActivitiesColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
1188                ActivitiesColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
1189                Activities.RAW_ID + " TEXT," +
1190                Activities.IN_REPLY_TO + " TEXT," +
1191                Activities.AUTHOR_CONTACT_ID +  " INTEGER REFERENCES raw_contacts(_id)," +
1192                Activities.TARGET_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
1193                Activities.PUBLISHED + " INTEGER NOT NULL," +
1194                Activities.THREAD_PUBLISHED + " INTEGER NOT NULL," +
1195                Activities.TITLE + " TEXT NOT NULL," +
1196                Activities.SUMMARY + " TEXT," +
1197                Activities.LINK + " TEXT, " +
1198                Activities.THUMBNAIL + " BLOB" +
1199        ");");
1200
1201        db.execSQL("CREATE TABLE " + Tables.STATUS_UPDATES + " (" +
1202                StatusUpdatesColumns.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
1203                StatusUpdates.STATUS + " TEXT," +
1204                StatusUpdates.STATUS_TIMESTAMP + " INTEGER," +
1205                StatusUpdates.STATUS_RES_PACKAGE + " TEXT, " +
1206                StatusUpdates.STATUS_LABEL + " INTEGER, " +
1207                StatusUpdates.STATUS_ICON + " INTEGER" +
1208        ");");
1209
1210        db.execSQL("CREATE TABLE " + Tables.PROPERTIES + " (" +
1211                PropertiesColumns.PROPERTY_KEY + " TEXT PRIMARY KEY, " +
1212                PropertiesColumns.PROPERTY_VALUE + " TEXT " +
1213        ");");
1214
1215        db.execSQL("CREATE TABLE " + Tables.ACCOUNTS + " (" +
1216                AccountsColumns.ACCOUNT_NAME + " TEXT, " +
1217                AccountsColumns.ACCOUNT_TYPE + " TEXT, " +
1218                AccountsColumns.DATA_SET + " TEXT, " +
1219                AccountsColumns.PROFILE_RAW_CONTACT_ID + " INTEGER" +
1220        ");");
1221
1222        db.execSQL("CREATE INDEX accounts_profile_raw_contact_id_index ON " +
1223                Tables.ACCOUNTS + " (" +
1224                AccountsColumns.PROFILE_RAW_CONTACT_ID +
1225        ");");
1226
1227        // Allow contacts without any account to be created for now.  Achieve that
1228        // by inserting a fake account with both type and name as NULL.
1229        db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL, NULL, NULL)");
1230
1231        createDirectoriesTable(db);
1232        createSearchIndexTable(db);
1233
1234        db.execSQL("CREATE TABLE " + Tables.DATA_USAGE_STAT + "(" +
1235                DataUsageStatColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
1236                DataUsageStatColumns.DATA_ID + " INTEGER NOT NULL, " +
1237                DataUsageStatColumns.USAGE_TYPE_INT + " INTEGER NOT NULL DEFAULT 0, " +
1238                DataUsageStatColumns.TIMES_USED + " INTEGER NOT NULL DEFAULT 0, " +
1239                DataUsageStatColumns.LAST_TIME_USED + " INTERGER NOT NULL DEFAULT 0, " +
1240                "FOREIGN KEY(" + DataUsageStatColumns.DATA_ID + ") REFERENCES "
1241                        + Tables.DATA + "(" + Data._ID + ")" +
1242        ");");
1243        db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " +
1244                Tables.DATA_USAGE_STAT + " (" +
1245                DataUsageStatColumns.DATA_ID + ", " +
1246                DataUsageStatColumns.USAGE_TYPE_INT +
1247        ");");
1248
1249        createContactsViews(db);
1250        createGroupsView(db);
1251        createContactsTriggers(db);
1252        createContactsIndexes(db);
1253
1254        loadNicknameLookupTable(db);
1255
1256        // Add the legacy API support views, etc
1257        LegacyApiSupport.createDatabase(db);
1258
1259        if (mDatabaseOptimizationEnabled) {
1260            // This will create a sqlite_stat1 table that is used for query optimization
1261            db.execSQL("ANALYZE;");
1262
1263            updateSqliteStats(db);
1264
1265            // We need to close and reopen the database connection so that the stats are
1266            // taken into account. Make a note of it and do the actual reopening in the
1267            // getWritableDatabase method.
1268            mReopenDatabase = true;
1269        }
1270
1271        ContentResolver.requestSync(null /* all accounts */,
1272                ContactsContract.AUTHORITY, new Bundle());
1273    }
1274
1275    private void createDirectoriesTable(SQLiteDatabase db) {
1276        db.execSQL("CREATE TABLE " + Tables.DIRECTORIES + "(" +
1277                Directory._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1278                Directory.PACKAGE_NAME + " TEXT NOT NULL," +
1279                Directory.DIRECTORY_AUTHORITY + " TEXT NOT NULL," +
1280                Directory.TYPE_RESOURCE_ID + " INTEGER," +
1281                DirectoryColumns.TYPE_RESOURCE_NAME + " TEXT," +
1282                Directory.ACCOUNT_TYPE + " TEXT," +
1283                Directory.ACCOUNT_NAME + " TEXT," +
1284                Directory.DISPLAY_NAME + " TEXT, " +
1285                Directory.EXPORT_SUPPORT + " INTEGER NOT NULL" +
1286                        " DEFAULT " + Directory.EXPORT_SUPPORT_NONE + "," +
1287                Directory.SHORTCUT_SUPPORT + " INTEGER NOT NULL" +
1288                        " DEFAULT " + Directory.SHORTCUT_SUPPORT_NONE + "," +
1289                Directory.PHOTO_SUPPORT + " INTEGER NOT NULL" +
1290                        " DEFAULT " + Directory.PHOTO_SUPPORT_NONE +
1291        ");");
1292
1293        // Trigger a full scan of directories in the system
1294        setProperty(db, ContactDirectoryManager.PROPERTY_DIRECTORY_SCAN_COMPLETE, "0");
1295    }
1296
1297    public void createSearchIndexTable(SQLiteDatabase db) {
1298        db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_INDEX);
1299        db.execSQL("CREATE VIRTUAL TABLE " + Tables.SEARCH_INDEX
1300                + " USING FTS4 ("
1301                    + SearchIndexColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id) NOT NULL,"
1302                    + SearchIndexColumns.CONTENT + " TEXT, "
1303                    + SearchIndexColumns.NAME + " TEXT, "
1304                    + SearchIndexColumns.TOKENS + " TEXT"
1305                + ")");
1306    }
1307
1308    private static void createContactsTriggers(SQLiteDatabase db) {
1309
1310        /*
1311         * Automatically delete Data rows when a raw contact is deleted.
1312         */
1313        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;");
1314        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted "
1315                + "   BEFORE DELETE ON " + Tables.RAW_CONTACTS
1316                + " BEGIN "
1317                + "   DELETE FROM " + Tables.DATA
1318                + "     WHERE " + Data.RAW_CONTACT_ID
1319                                + "=OLD." + RawContacts._ID + ";"
1320                + "   DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS
1321                + "     WHERE " + AggregationExceptions.RAW_CONTACT_ID1
1322                                + "=OLD." + RawContacts._ID
1323                + "        OR " + AggregationExceptions.RAW_CONTACT_ID2
1324                                + "=OLD." + RawContacts._ID + ";"
1325                + "   DELETE FROM " + Tables.VISIBLE_CONTACTS
1326                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1327                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1328                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1329                + "           )=1;"
1330                + "   DELETE FROM " + Tables.DEFAULT_DIRECTORY
1331                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1332                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1333                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1334                + "           )=1;"
1335                + "   DELETE FROM " + Tables.CONTACTS
1336                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1337                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1338                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1339                + "           )=1;"
1340                + " END");
1341
1342
1343        db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;");
1344        db.execSQL("DROP TRIGGER IF EXISTS raw_contacts_times_contacted;");
1345
1346        /*
1347         * Triggers that update {@link RawContacts#VERSION} when the contact is
1348         * marked for deletion or any time a data row is inserted, updated or
1349         * deleted.
1350         */
1351        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;");
1352        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted "
1353                + "   AFTER UPDATE ON " + Tables.RAW_CONTACTS
1354                + " BEGIN "
1355                + "   UPDATE " + Tables.RAW_CONTACTS
1356                + "     SET "
1357                +         RawContacts.VERSION + "=OLD." + RawContacts.VERSION + "+1 "
1358                + "     WHERE " + RawContacts._ID + "=OLD." + RawContacts._ID
1359                + "       AND NEW." + RawContacts.DELETED + "!= OLD." + RawContacts.DELETED + ";"
1360                + " END");
1361
1362        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_updated;");
1363        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_updated AFTER UPDATE ON " + Tables.DATA
1364                + " BEGIN "
1365                + "   UPDATE " + Tables.DATA
1366                + "     SET " + Data.DATA_VERSION + "=OLD." + Data.DATA_VERSION + "+1 "
1367                + "     WHERE " + Data._ID + "=OLD." + Data._ID + ";"
1368                + "   UPDATE " + Tables.RAW_CONTACTS
1369                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
1370                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
1371                + " END");
1372
1373        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_deleted;");
1374        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_deleted BEFORE DELETE ON " + Tables.DATA
1375                + " BEGIN "
1376                + "   UPDATE " + Tables.RAW_CONTACTS
1377                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
1378                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
1379                + "   DELETE FROM " + Tables.PHONE_LOOKUP
1380                + "     WHERE " + PhoneLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1381                + "   DELETE FROM " + Tables.STATUS_UPDATES
1382                + "     WHERE " + StatusUpdatesColumns.DATA_ID + "=OLD." + Data._ID + ";"
1383                + "   DELETE FROM " + Tables.NAME_LOOKUP
1384                + "     WHERE " + NameLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1385                + " END");
1386
1387
1388        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_updated1;");
1389        db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_updated1 "
1390                + "   AFTER UPDATE ON " + Tables.GROUPS
1391                + " BEGIN "
1392                + "   UPDATE " + Tables.GROUPS
1393                + "     SET "
1394                +         Groups.VERSION + "=OLD." + Groups.VERSION + "+1"
1395                + "     WHERE " + Groups._ID + "=OLD." + Groups._ID + ";"
1396                + " END");
1397
1398        // Update DEFAULT_FILTER table per AUTO_ADD column update.
1399        // See also upgradeToVersion411().
1400        final String insertContactsWithoutAccount = (
1401                " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
1402                "     SELECT " + RawContacts.CONTACT_ID +
1403                "     FROM " + Tables.RAW_CONTACTS +
1404                "     WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " +
1405                "     AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL; ");
1406        final String insertContactsWithAccountNoDefaultGroup = (
1407                " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
1408                "     SELECT " + RawContacts.CONTACT_ID +
1409                "         FROM " + Tables.RAW_CONTACTS +
1410                "     WHERE NOT EXISTS" +
1411                "         (SELECT " + Groups._ID +
1412                "             FROM " + Tables.GROUPS +
1413                "             WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = " +
1414                        GroupsColumns.CONCRETE_ACCOUNT_NAME +
1415                "             AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = " +
1416                        GroupsColumns.CONCRETE_ACCOUNT_TYPE +
1417                "             AND " + Groups.AUTO_ADD + " != 0" + ");");
1418        final String insertContactsWithAccountDefaultGroup = (
1419                " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
1420                "     SELECT " + RawContacts.CONTACT_ID +
1421                "         FROM " + Tables.RAW_CONTACTS +
1422                "     JOIN " + Tables.DATA +
1423                "           ON (" + RawContactsColumns.CONCRETE_ID + "=" +
1424                        Data.RAW_CONTACT_ID + ")" +
1425                "     WHERE " + DataColumns.MIMETYPE_ID + "=" +
1426                    "(SELECT " + MimetypesColumns._ID + " FROM " + Tables.MIMETYPES +
1427                        " WHERE " + MimetypesColumns.MIMETYPE +
1428                            "='" + GroupMembership.CONTENT_ITEM_TYPE + "')" +
1429                "     AND EXISTS" +
1430                "         (SELECT " + Groups._ID +
1431                "             FROM " + Tables.GROUPS +
1432                "                 WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = " +
1433                        GroupsColumns.CONCRETE_ACCOUNT_NAME +
1434                "                 AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = " +
1435                        GroupsColumns.CONCRETE_ACCOUNT_TYPE +
1436                "                 AND " + Groups.AUTO_ADD + " != 0" + ");");
1437
1438        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_auto_add_updated1;");
1439        db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_auto_add_updated1 "
1440                + "   AFTER UPDATE OF " + Groups.AUTO_ADD + " ON " + Tables.GROUPS
1441                + " BEGIN "
1442                + "   DELETE FROM " + Tables.DEFAULT_DIRECTORY + ";"
1443                    + insertContactsWithoutAccount
1444                    + insertContactsWithAccountNoDefaultGroup
1445                    + insertContactsWithAccountDefaultGroup
1446                + " END");
1447    }
1448
1449    private static void createContactsIndexes(SQLiteDatabase db) {
1450        db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
1451        db.execSQL("CREATE INDEX name_lookup_index ON " + Tables.NAME_LOOKUP + " (" +
1452                NameLookupColumns.NORMALIZED_NAME + "," +
1453                NameLookupColumns.NAME_TYPE + ", " +
1454                NameLookupColumns.RAW_CONTACT_ID + ", " +
1455                NameLookupColumns.DATA_ID +
1456        ");");
1457
1458        db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key1_index");
1459        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
1460                RawContacts.SORT_KEY_PRIMARY +
1461        ");");
1462
1463        db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key2_index");
1464        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
1465                RawContacts.SORT_KEY_ALTERNATIVE +
1466        ");");
1467    }
1468
1469    private static void createContactsViews(SQLiteDatabase db) {
1470        db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS + ";");
1471        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA + ";");
1472        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS + ";");
1473        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_ENTITIES + ";");
1474        db.execSQL("DROP VIEW IF EXISTS " + Views.ENTITIES + ";");
1475        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_USAGE_STAT + ";");
1476        db.execSQL("DROP VIEW IF EXISTS " + Views.STREAM_ITEMS + ";");
1477
1478        String dataColumns =
1479                Data.IS_PRIMARY + ", "
1480                + Data.IS_SUPER_PRIMARY + ", "
1481                + Data.DATA_VERSION + ", "
1482                + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + ","
1483                + MimetypesColumns.MIMETYPE + " AS " + Data.MIMETYPE + ", "
1484                + Data.IS_READ_ONLY + ", "
1485                + Data.DATA1 + ", "
1486                + Data.DATA2 + ", "
1487                + Data.DATA3 + ", "
1488                + Data.DATA4 + ", "
1489                + Data.DATA5 + ", "
1490                + Data.DATA6 + ", "
1491                + Data.DATA7 + ", "
1492                + Data.DATA8 + ", "
1493                + Data.DATA9 + ", "
1494                + Data.DATA10 + ", "
1495                + Data.DATA11 + ", "
1496                + Data.DATA12 + ", "
1497                + Data.DATA13 + ", "
1498                + Data.DATA14 + ", "
1499                + Data.DATA15 + ", "
1500                + Data.SYNC1 + ", "
1501                + Data.SYNC2 + ", "
1502                + Data.SYNC3 + ", "
1503                + Data.SYNC4;
1504
1505        String syncColumns =
1506                RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ","
1507                + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ","
1508                + RawContactsColumns.CONCRETE_DATA_SET + " AS " + RawContacts.DATA_SET + ","
1509                + "(CASE WHEN " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL THEN "
1510                        + RawContactsColumns.CONCRETE_ACCOUNT_TYPE
1511                        + " ELSE " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + "||'/'||"
1512                        + RawContactsColumns.CONCRETE_DATA_SET + " END) AS "
1513                        + RawContacts.ACCOUNT_TYPE_AND_DATA_SET + ","
1514                + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + ","
1515                + RawContactsColumns.CONCRETE_NAME_VERIFIED + " AS "
1516                        + RawContacts.NAME_VERIFIED + ","
1517                + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + ","
1518                + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + ","
1519                + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + ","
1520                + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + ","
1521                + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + ","
1522                + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4;
1523
1524        String baseContactColumns =
1525                Contacts.HAS_PHONE_NUMBER + ", "
1526                + Contacts.NAME_RAW_CONTACT_ID + ", "
1527                + Contacts.LOOKUP_KEY + ", "
1528                + Contacts.PHOTO_ID + ", "
1529                + Contacts.PHOTO_FILE_ID + ", "
1530                + Clauses.CONTACT_VISIBLE + " AS " + Contacts.IN_VISIBLE_GROUP + ", "
1531                + ContactsColumns.LAST_STATUS_UPDATE_ID;
1532
1533        String contactOptionColumns =
1534                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1535                        + " AS " + RawContacts.CUSTOM_RINGTONE + ","
1536                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1537                        + " AS " + RawContacts.SEND_TO_VOICEMAIL + ","
1538                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1539                        + " AS " + RawContacts.LAST_TIME_CONTACTED + ","
1540                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1541                        + " AS " + RawContacts.TIMES_CONTACTED + ","
1542                + ContactsColumns.CONCRETE_STARRED
1543                        + " AS " + RawContacts.STARRED;
1544
1545        String contactNameColumns =
1546                "name_raw_contact." + RawContacts.DISPLAY_NAME_SOURCE
1547                        + " AS " + Contacts.DISPLAY_NAME_SOURCE + ", "
1548                + "name_raw_contact." + RawContacts.DISPLAY_NAME_PRIMARY
1549                        + " AS " + Contacts.DISPLAY_NAME_PRIMARY + ", "
1550                + "name_raw_contact." + RawContacts.DISPLAY_NAME_ALTERNATIVE
1551                        + " AS " + Contacts.DISPLAY_NAME_ALTERNATIVE + ", "
1552                + "name_raw_contact." + RawContacts.PHONETIC_NAME
1553                        + " AS " + Contacts.PHONETIC_NAME + ", "
1554                + "name_raw_contact." + RawContacts.PHONETIC_NAME_STYLE
1555                        + " AS " + Contacts.PHONETIC_NAME_STYLE + ", "
1556                + "name_raw_contact." + RawContacts.SORT_KEY_PRIMARY
1557                        + " AS " + Contacts.SORT_KEY_PRIMARY + ", "
1558                + "name_raw_contact." + RawContacts.SORT_KEY_ALTERNATIVE
1559                        + " AS " + Contacts.SORT_KEY_ALTERNATIVE;
1560
1561        String dataSelect = "SELECT "
1562                + DataColumns.CONCRETE_ID + " AS " + Data._ID + ","
1563                + Data.RAW_CONTACT_ID + ", "
1564                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1565                + syncColumns + ", "
1566                + dataColumns + ", "
1567                + contactOptionColumns + ", "
1568                + contactNameColumns + ", "
1569                + baseContactColumns + ", "
1570                + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1571                        Contacts.PHOTO_URI) + ", "
1572                + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1573                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1574                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1575                    " WHERE " + DataColumns.CONCRETE_RAW_CONTACT_ID +
1576                    "=" + AccountsColumns.PROFILE_RAW_CONTACT_ID + ") AS " +
1577                    RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", "
1578                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1579                + " FROM " + Tables.DATA
1580                + " JOIN " + Tables.MIMETYPES + " ON ("
1581                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1582                + " JOIN " + Tables.RAW_CONTACTS + " ON ("
1583                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1584                + " JOIN " + Tables.CONTACTS + " ON ("
1585                +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
1586                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1587                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
1588                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1589                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1590                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1591                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1592                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1593                        + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1594
1595        db.execSQL("CREATE VIEW " + Views.DATA + " AS " + dataSelect);
1596
1597        String rawContactOptionColumns =
1598                RawContacts.CUSTOM_RINGTONE + ","
1599                + RawContacts.SEND_TO_VOICEMAIL + ","
1600                + RawContacts.LAST_TIME_CONTACTED + ","
1601                + RawContacts.TIMES_CONTACTED + ","
1602                + RawContacts.STARRED;
1603
1604        String rawContactsSelect = "SELECT "
1605                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ","
1606                + RawContacts.CONTACT_ID + ", "
1607                + RawContacts.AGGREGATION_MODE + ", "
1608                + RawContacts.RAW_CONTACT_IS_READ_ONLY + ", "
1609                + RawContacts.DELETED + ", "
1610                + RawContacts.DISPLAY_NAME_SOURCE  + ", "
1611                + RawContacts.DISPLAY_NAME_PRIMARY  + ", "
1612                + RawContacts.DISPLAY_NAME_ALTERNATIVE  + ", "
1613                + RawContacts.PHONETIC_NAME  + ", "
1614                + RawContacts.PHONETIC_NAME_STYLE  + ", "
1615                + RawContacts.SORT_KEY_PRIMARY  + ", "
1616                + RawContacts.SORT_KEY_ALTERNATIVE + ", "
1617                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1618                    " WHERE " + AccountsColumns.PROFILE_RAW_CONTACT_ID +
1619                    "=" + RawContactsColumns.CONCRETE_ID + ") AS " +
1620                    RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", "
1621                + rawContactOptionColumns + ", "
1622                + syncColumns
1623                + " FROM " + Tables.RAW_CONTACTS;
1624
1625        db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS + " AS " + rawContactsSelect);
1626
1627        String contactsColumns =
1628                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1629                        + " AS " + Contacts.CUSTOM_RINGTONE + ", "
1630                + contactNameColumns + ", "
1631                + baseContactColumns + ", "
1632                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1633                        + " AS " + Contacts.LAST_TIME_CONTACTED + ", "
1634                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1635                        + " AS " + Contacts.SEND_TO_VOICEMAIL + ", "
1636                + ContactsColumns.CONCRETE_STARRED
1637                        + " AS " + Contacts.STARRED + ", "
1638                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1639                        + " AS " + Contacts.TIMES_CONTACTED;
1640
1641        String contactsSelect = "SELECT "
1642                + ContactsColumns.CONCRETE_ID + " AS " + Contacts._ID + ","
1643                + contactsColumns + ", "
1644                + buildDisplayPhotoUriAlias(ContactsColumns.CONCRETE_ID, Contacts.PHOTO_URI) + ", "
1645                + buildThumbnailPhotoUriAlias(ContactsColumns.CONCRETE_ID,
1646                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1647                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1648                    " JOIN " + Tables.RAW_CONTACTS + " ON " + RawContactsColumns.CONCRETE_ID + "=" +
1649                    AccountsColumns.PROFILE_RAW_CONTACT_ID +
1650                    " WHERE " + RawContactsColumns.CONCRETE_CONTACT_ID +
1651                    "=" + ContactsColumns.CONCRETE_ID + ") AS " +
1652                    Contacts.IS_USER_PROFILE
1653                + " FROM " + Tables.CONTACTS
1654                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1655                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")";
1656
1657        db.execSQL("CREATE VIEW " + Views.CONTACTS + " AS " + contactsSelect);
1658
1659        String rawEntitiesSelect = "SELECT "
1660                + RawContacts.CONTACT_ID + ", "
1661                + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
1662                + dataColumns + ", "
1663                + syncColumns + ", "
1664                + Data.SYNC1 + ", "
1665                + Data.SYNC2 + ", "
1666                + Data.SYNC3 + ", "
1667                + Data.SYNC4 + ", "
1668                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ", "
1669                + DataColumns.CONCRETE_ID + " AS " + RawContacts.Entity.DATA_ID + ","
1670                + RawContactsColumns.CONCRETE_STARRED + " AS " + RawContacts.STARRED + ","
1671                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1672                    " WHERE " + RawContactsColumns.CONCRETE_ID +
1673                    "=" + AccountsColumns.PROFILE_RAW_CONTACT_ID + ") AS " +
1674                    RawContacts.RAW_CONTACT_IS_USER_PROFILE + ","
1675                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1676                + " FROM " + Tables.RAW_CONTACTS
1677                + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
1678                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1679                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1680                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1681                + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
1682                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1683                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1684                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1685                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1686                + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1687
1688        db.execSQL("CREATE VIEW " + Views.RAW_ENTITIES + " AS "
1689                + rawEntitiesSelect);
1690
1691        String entitiesSelect = "SELECT "
1692                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + Contacts._ID + ", "
1693                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1694                + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
1695                + dataColumns + ", "
1696                + syncColumns + ", "
1697                + contactsColumns + ", "
1698                + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1699                        Contacts.PHOTO_URI) + ", "
1700                + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1701                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1702                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1703                    " JOIN " + Tables.RAW_CONTACTS + " ON " + RawContactsColumns.CONCRETE_ID + "=" +
1704                    AccountsColumns.PROFILE_RAW_CONTACT_ID +
1705                    " WHERE " + RawContactsColumns.CONCRETE_CONTACT_ID +
1706                    "=" + ContactsColumns.CONCRETE_ID + ") AS " +
1707                    Contacts.IS_USER_PROFILE + ", "
1708                + Data.SYNC1 + ", "
1709                + Data.SYNC2 + ", "
1710                + Data.SYNC3 + ", "
1711                + Data.SYNC4 + ", "
1712                + RawContactsColumns.CONCRETE_ID + " AS " + Contacts.Entity.RAW_CONTACT_ID + ", "
1713                + DataColumns.CONCRETE_ID + " AS " + Contacts.Entity.DATA_ID + ","
1714                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1715                + " FROM " + Tables.RAW_CONTACTS
1716                + " JOIN " + Tables.CONTACTS + " ON ("
1717                +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
1718                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1719                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
1720                + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
1721                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1722                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1723                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1724                + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
1725                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1726                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1727                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1728                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1729                + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1730
1731        db.execSQL("CREATE VIEW " + Views.ENTITIES + " AS "
1732                + entitiesSelect);
1733
1734        String dataUsageStatSelect = "SELECT "
1735                + DataUsageStatColumns.CONCRETE_ID + " AS " + DataUsageStatColumns._ID + ", "
1736                + DataUsageStatColumns.DATA_ID + ", "
1737                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1738                + MimetypesColumns.CONCRETE_MIMETYPE + " AS " + Data.MIMETYPE + ", "
1739                + DataUsageStatColumns.USAGE_TYPE_INT + ", "
1740                + DataUsageStatColumns.TIMES_USED + ", "
1741                + DataUsageStatColumns.LAST_TIME_USED
1742                + " FROM " + Tables.DATA_USAGE_STAT
1743                + " JOIN " + Tables.DATA + " ON ("
1744                +   DataColumns.CONCRETE_ID + "=" + DataUsageStatColumns.CONCRETE_DATA_ID + ")"
1745                + " JOIN " + Tables.RAW_CONTACTS + " ON ("
1746                +   RawContactsColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_RAW_CONTACT_ID
1747                    + " )"
1748                + " JOIN " + Tables.MIMETYPES + " ON ("
1749                +   MimetypesColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_MIMETYPE_ID + ")";
1750
1751        db.execSQL("CREATE VIEW " + Views.DATA_USAGE_STAT + " AS " + dataUsageStatSelect);
1752
1753        String streamItemSelect = "SELECT " +
1754                StreamItemsColumns.CONCRETE_ID + ", " +
1755                ContactsColumns.CONCRETE_ID + " AS " + StreamItems.CONTACT_ID + ", " +
1756                RawContactsColumns.CONCRETE_ACCOUNT_NAME + ", " +
1757                RawContactsColumns.CONCRETE_ACCOUNT_TYPE + ", " +
1758                RawContactsColumns.CONCRETE_DATA_SET + ", " +
1759                StreamItemsColumns.CONCRETE_RAW_CONTACT_ID +
1760                        " as " + StreamItems.RAW_CONTACT_ID + ", " +
1761                RawContactsColumns.CONCRETE_SOURCE_ID +
1762                        " as " + StreamItems.RAW_CONTACT_SOURCE_ID + ", " +
1763                StreamItemsColumns.CONCRETE_PACKAGE + ", " +
1764                StreamItemsColumns.CONCRETE_ICON + ", " +
1765                StreamItemsColumns.CONCRETE_LABEL + ", " +
1766                StreamItemsColumns.CONCRETE_TEXT + ", " +
1767                StreamItemsColumns.CONCRETE_TIMESTAMP + ", " +
1768                StreamItemsColumns.CONCRETE_COMMENTS + ", " +
1769                StreamItemsColumns.CONCRETE_SYNC1 + ", " +
1770                StreamItemsColumns.CONCRETE_SYNC2 + ", " +
1771                StreamItemsColumns.CONCRETE_SYNC3 + ", " +
1772                StreamItemsColumns.CONCRETE_SYNC4 +
1773                " FROM " + Tables.STREAM_ITEMS
1774                + " JOIN " + Tables.RAW_CONTACTS + " ON ("
1775                + StreamItemsColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID
1776                + ") JOIN " + Tables.CONTACTS + " ON ("
1777                + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")";
1778
1779        db.execSQL("CREATE VIEW " + Views.STREAM_ITEMS + " AS " + streamItemSelect);
1780    }
1781
1782    private static String buildDisplayPhotoUriAlias(String contactIdColumn, String alias) {
1783        return "(CASE WHEN " + Contacts.PHOTO_FILE_ID + " IS NULL THEN (CASE WHEN "
1784                + Contacts.PHOTO_ID + " IS NULL"
1785                + " OR " + Contacts.PHOTO_ID + "=0"
1786                + " THEN NULL"
1787                + " ELSE '" + Contacts.CONTENT_URI + "/'||"
1788                        + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'"
1789                + " END) ELSE '" + DisplayPhoto.CONTENT_URI + "/'||"
1790                        + Contacts.PHOTO_FILE_ID + " END)"
1791                + " AS " + alias;
1792    }
1793
1794    private static String buildThumbnailPhotoUriAlias(String contactIdColumn, String alias) {
1795        return "(CASE WHEN "
1796                + Contacts.PHOTO_ID + " IS NULL"
1797                + " OR " + Contacts.PHOTO_ID + "=0"
1798                + " THEN NULL"
1799                + " ELSE '" + Contacts.CONTENT_URI + "/'||"
1800                        + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'"
1801                + " END)"
1802                + " AS " + alias;
1803    }
1804
1805    private static void createGroupsView(SQLiteDatabase db) {
1806        db.execSQL("DROP VIEW IF EXISTS " + Views.GROUPS + ";");
1807        String groupsColumns =
1808                Groups.ACCOUNT_NAME + ","
1809                + Groups.ACCOUNT_TYPE + ","
1810                + Groups.DATA_SET + ","
1811                + "(CASE WHEN " + Groups.DATA_SET + " IS NULL THEN " + Groups.ACCOUNT_TYPE
1812                    + " ELSE " + Groups.ACCOUNT_TYPE + "||" + Groups.DATA_SET + " END) AS "
1813                    + Groups.ACCOUNT_TYPE_AND_DATA_SET + ","
1814                + Groups.SOURCE_ID + ","
1815                + Groups.VERSION + ","
1816                + Groups.DIRTY + ","
1817                + Groups.TITLE + ","
1818                + Groups.TITLE_RES + ","
1819                + Groups.NOTES + ","
1820                + Groups.SYSTEM_ID + ","
1821                + Groups.DELETED + ","
1822                + Groups.GROUP_VISIBLE + ","
1823                + Groups.SHOULD_SYNC + ","
1824                + Groups.AUTO_ADD + ","
1825                + Groups.FAVORITES + ","
1826                + Groups.GROUP_IS_READ_ONLY + ","
1827                + Groups.SYNC1 + ","
1828                + Groups.SYNC2 + ","
1829                + Groups.SYNC3 + ","
1830                + Groups.SYNC4 + ","
1831                + PackagesColumns.PACKAGE + " AS " + Groups.RES_PACKAGE;
1832
1833        String groupsSelect = "SELECT "
1834                + GroupsColumns.CONCRETE_ID + " AS " + Groups._ID + ","
1835                + groupsColumns
1836                + " FROM " + Tables.GROUPS_JOIN_PACKAGES;
1837
1838        db.execSQL("CREATE VIEW " + Views.GROUPS + " AS " + groupsSelect);
1839    }
1840
1841    @Override
1842    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1843        if (oldVersion < 99) {
1844            Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion
1845                    + ", data will be lost!");
1846
1847            db.execSQL("DROP TABLE IF EXISTS " + Tables.CONTACTS + ";");
1848            db.execSQL("DROP TABLE IF EXISTS " + Tables.RAW_CONTACTS + ";");
1849            db.execSQL("DROP TABLE IF EXISTS " + Tables.PACKAGES + ";");
1850            db.execSQL("DROP TABLE IF EXISTS " + Tables.MIMETYPES + ";");
1851            db.execSQL("DROP TABLE IF EXISTS " + Tables.DATA + ";");
1852            db.execSQL("DROP TABLE IF EXISTS " + Tables.PHONE_LOOKUP + ";");
1853            db.execSQL("DROP TABLE IF EXISTS " + Tables.NAME_LOOKUP + ";");
1854            db.execSQL("DROP TABLE IF EXISTS " + Tables.NICKNAME_LOOKUP + ";");
1855            db.execSQL("DROP TABLE IF EXISTS " + Tables.GROUPS + ";");
1856            db.execSQL("DROP TABLE IF EXISTS " + Tables.ACTIVITIES + ";");
1857            db.execSQL("DROP TABLE IF EXISTS " + Tables.CALLS + ";");
1858            db.execSQL("DROP TABLE IF EXISTS " + Tables.SETTINGS + ";");
1859            db.execSQL("DROP TABLE IF EXISTS " + Tables.STATUS_UPDATES + ";");
1860
1861            // TODO: we should not be dropping agg_exceptions and contact_options. In case that
1862            // table's schema changes, we should try to preserve the data, because it was entered
1863            // by the user and has never been synched to the server.
1864            db.execSQL("DROP TABLE IF EXISTS " + Tables.AGGREGATION_EXCEPTIONS + ";");
1865
1866            onCreate(db);
1867            return;
1868        }
1869
1870        Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion);
1871
1872        boolean upgradeViewsAndTriggers = false;
1873        boolean upgradeNameLookup = false;
1874        boolean upgradeLegacyApiSupport = false;
1875        boolean upgradeSearchIndex = false;
1876
1877        if (oldVersion == 99) {
1878            upgradeViewsAndTriggers = true;
1879            oldVersion++;
1880        }
1881
1882        if (oldVersion == 100) {
1883            db.execSQL("CREATE INDEX IF NOT EXISTS mimetypes_mimetype_index ON "
1884                    + Tables.MIMETYPES + " ("
1885                            + MimetypesColumns.MIMETYPE + ","
1886                            + MimetypesColumns._ID + ");");
1887            updateIndexStats(db, Tables.MIMETYPES,
1888                    "mimetypes_mimetype_index", "50 1 1");
1889
1890            upgradeViewsAndTriggers = true;
1891            oldVersion++;
1892        }
1893
1894        if (oldVersion == 101) {
1895            upgradeViewsAndTriggers = true;
1896            oldVersion++;
1897        }
1898
1899        if (oldVersion == 102) {
1900            upgradeViewsAndTriggers = true;
1901            oldVersion++;
1902        }
1903
1904        if (oldVersion == 103) {
1905            upgradeViewsAndTriggers = true;
1906            oldVersion++;
1907        }
1908
1909        if (oldVersion == 104 || oldVersion == 201) {
1910            LegacyApiSupport.createSettingsTable(db);
1911            upgradeViewsAndTriggers = true;
1912            oldVersion++;
1913        }
1914
1915        if (oldVersion == 105) {
1916            upgradeToVersion202(db);
1917            upgradeNameLookup = true;
1918            oldVersion = 202;
1919        }
1920
1921        if (oldVersion == 202) {
1922            upgradeToVersion203(db);
1923            upgradeViewsAndTriggers = true;
1924            oldVersion++;
1925        }
1926
1927        if (oldVersion == 203) {
1928            upgradeViewsAndTriggers = true;
1929            oldVersion++;
1930        }
1931
1932        if (oldVersion == 204) {
1933            upgradeToVersion205(db);
1934            upgradeViewsAndTriggers = true;
1935            oldVersion++;
1936        }
1937
1938        if (oldVersion == 205) {
1939            upgrateToVersion206(db);
1940            upgradeViewsAndTriggers = true;
1941            oldVersion++;
1942        }
1943
1944        if (oldVersion == 206) {
1945            upgradeToVersion300(db);
1946            oldVersion = 300;
1947        }
1948
1949        if (oldVersion == 300) {
1950            upgradeViewsAndTriggers = true;
1951            oldVersion = 301;
1952        }
1953
1954        if (oldVersion == 301) {
1955            upgradeViewsAndTriggers = true;
1956            oldVersion = 302;
1957        }
1958
1959        if (oldVersion == 302) {
1960            upgradeEmailToVersion303(db);
1961            upgradeNicknameToVersion303(db);
1962            oldVersion = 303;
1963        }
1964
1965        if (oldVersion == 303) {
1966            upgradeToVersion304(db);
1967            oldVersion = 304;
1968        }
1969
1970        if (oldVersion == 304) {
1971            upgradeNameLookup = true;
1972            oldVersion = 305;
1973        }
1974
1975        if (oldVersion == 305) {
1976            upgradeToVersion306(db);
1977            oldVersion = 306;
1978        }
1979
1980        if (oldVersion == 306) {
1981            upgradeToVersion307(db);
1982            oldVersion = 307;
1983        }
1984
1985        if (oldVersion == 307) {
1986            upgradeToVersion308(db);
1987            oldVersion = 308;
1988        }
1989
1990        // Gingerbread upgrades
1991        if (oldVersion < 350) {
1992            upgradeViewsAndTriggers = true;
1993            oldVersion = 351;
1994        }
1995
1996        if (oldVersion == 351) {
1997            upgradeNameLookup = true;
1998            oldVersion = 352;
1999        }
2000
2001        if (oldVersion == 352) {
2002            upgradeToVersion353(db);
2003            oldVersion = 353;
2004        }
2005
2006        // Honeycomb upgrades
2007        if (oldVersion < 400) {
2008            upgradeViewsAndTriggers = true;
2009            upgradeToVersion400(db);
2010            oldVersion = 400;
2011        }
2012
2013        if (oldVersion == 400) {
2014            upgradeViewsAndTriggers = true;
2015            upgradeToVersion401(db);
2016            oldVersion = 401;
2017        }
2018
2019        if (oldVersion == 401) {
2020            upgradeToVersion402(db);
2021            oldVersion = 402;
2022        }
2023
2024        if (oldVersion == 402) {
2025            upgradeViewsAndTriggers = true;
2026            upgradeToVersion403(db);
2027            oldVersion = 403;
2028        }
2029
2030        if (oldVersion == 403) {
2031            upgradeViewsAndTriggers = true;
2032            oldVersion = 404;
2033        }
2034
2035        if (oldVersion == 404) {
2036            upgradeViewsAndTriggers = true;
2037            upgradeToVersion405(db);
2038            oldVersion = 405;
2039        }
2040
2041        if (oldVersion == 405) {
2042            upgradeViewsAndTriggers = true;
2043            upgradeToVersion406(db);
2044            oldVersion = 406;
2045        }
2046
2047        if (oldVersion == 406) {
2048            upgradeViewsAndTriggers = true;
2049            oldVersion = 407;
2050        }
2051
2052        if (oldVersion == 407) {
2053            // Obsolete
2054            oldVersion = 408;
2055        }
2056
2057        if (oldVersion == 408) {
2058            upgradeViewsAndTriggers = true;
2059            upgradeToVersion409(db);
2060            oldVersion = 409;
2061        }
2062
2063        if (oldVersion == 409) {
2064            upgradeViewsAndTriggers = true;
2065            oldVersion = 410;
2066        }
2067
2068        if (oldVersion == 410) {
2069            upgradeToVersion411(db);
2070            oldVersion = 411;
2071        }
2072
2073        if (oldVersion == 411) {
2074            // Same upgrade as 353, only on Honeycomb devices
2075            upgradeToVersion353(db);
2076            oldVersion = 412;
2077        }
2078
2079        if (oldVersion == 412) {
2080            upgradeToVersion413(db);
2081            oldVersion = 413;
2082        }
2083
2084        if (oldVersion == 413) {
2085            upgradeNameLookup = true;
2086            oldVersion = 414;
2087        }
2088
2089        if (oldVersion == 414) {
2090            upgradeToVersion415(db);
2091            upgradeViewsAndTriggers = true;
2092            oldVersion = 415;
2093        }
2094
2095        if (oldVersion == 415) {
2096            upgradeToVersion416(db);
2097            oldVersion = 416;
2098        }
2099
2100        if (oldVersion == 416) {
2101            upgradeLegacyApiSupport = true;
2102            oldVersion = 417;
2103        }
2104
2105        // Honeycomb-MR1 upgrades
2106        if (oldVersion < 500) {
2107            upgradeSearchIndex = true;
2108        }
2109
2110        if (oldVersion < 501) {
2111            upgradeSearchIndex = true;
2112            upgradeToVersion501(db);
2113            oldVersion = 501;
2114        }
2115
2116        if (oldVersion < 502) {
2117            upgradeSearchIndex = true;
2118            upgradeToVersion502(db);
2119            oldVersion = 502;
2120        }
2121
2122        if (oldVersion < 503) {
2123            upgradeSearchIndex = true;
2124            oldVersion = 503;
2125        }
2126
2127        if (oldVersion < 504) {
2128            upgradeToVersion504(db);
2129            oldVersion = 504;
2130        }
2131
2132        if (oldVersion < 600) {
2133            upgradeToVersion600(db);
2134            upgradeViewsAndTriggers = true;
2135            oldVersion = 600;
2136        }
2137
2138        if (oldVersion < 601) {
2139            upgradeToVersion601(db);
2140            oldVersion = 601;
2141        }
2142
2143        if (oldVersion < 602) {
2144            upgradeToVersion602(db);
2145            oldVersion = 602;
2146        }
2147
2148        if (oldVersion < 603) {
2149            upgradeViewsAndTriggers = true;
2150            oldVersion = 603;
2151        }
2152
2153        if (oldVersion < 604) {
2154            upgradeToVersion604(db);
2155            oldVersion = 604;
2156        }
2157
2158        if (oldVersion < 605) {
2159            upgradeViewsAndTriggers = true;
2160            upgradeToVersion605(db);
2161            oldVersion = 605;
2162        }
2163
2164        if (oldVersion < 606) {
2165            upgradeViewsAndTriggers = true;
2166            upgradeLegacyApiSupport = true;
2167            upgradeToVersion606(db);
2168            oldVersion = 606;
2169        }
2170
2171        if (oldVersion < 607) {
2172            upgradeViewsAndTriggers = true;
2173            upgradeToVersion607(db);
2174            oldVersion = 607;
2175        }
2176
2177        if (oldVersion < 608) {
2178            upgradeViewsAndTriggers = true;
2179            upgradeToVersion608(db);
2180            oldVersion = 608;
2181        }
2182
2183        if (oldVersion < 609) {
2184            upgradeToVersion609(db);
2185            oldVersion = 609;
2186        }
2187
2188        if (oldVersion < 610) {
2189            upgradeToVersion610(db);
2190            oldVersion = 610;
2191        }
2192
2193        if (oldVersion < 611) {
2194            upgradeViewsAndTriggers = true;
2195            upgradeToVersion611(db);
2196            oldVersion = 611;
2197        }
2198
2199        if (oldVersion < 612) {
2200            upgradeViewsAndTriggers = true;
2201            upgradeToVersion612(db);
2202            oldVersion = 612;
2203        }
2204
2205        if (oldVersion < 613) {
2206            upgradeToVersion613(db);
2207            oldVersion = 613;
2208        }
2209
2210        if (oldVersion < 614) {
2211            // this creates the view "view_stream_items"
2212            upgradeViewsAndTriggers = true;
2213            oldVersion = 614;
2214        }
2215
2216        if (upgradeViewsAndTriggers) {
2217            createContactsViews(db);
2218            createGroupsView(db);
2219            createContactsTriggers(db);
2220            createContactsIndexes(db);
2221            updateSqliteStats(db);
2222            upgradeLegacyApiSupport = true;
2223            mReopenDatabase = true;
2224        }
2225
2226        if (upgradeLegacyApiSupport) {
2227            LegacyApiSupport.createViews(db);
2228        }
2229
2230        if (upgradeNameLookup) {
2231            rebuildNameLookup(db);
2232        }
2233
2234        if (upgradeSearchIndex) {
2235            createSearchIndexTable(db);
2236            setProperty(db, SearchIndexManager.PROPERTY_SEARCH_INDEX_VERSION, "0");
2237        }
2238
2239        if (oldVersion != newVersion) {
2240            throw new IllegalStateException(
2241                    "error upgrading the database to version " + newVersion);
2242        }
2243    }
2244
2245    private void upgradeToVersion202(SQLiteDatabase db) {
2246        db.execSQL(
2247                "ALTER TABLE " + Tables.PHONE_LOOKUP +
2248                " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;");
2249
2250        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
2251                PhoneLookupColumns.MIN_MATCH + "," +
2252                PhoneLookupColumns.RAW_CONTACT_ID + "," +
2253                PhoneLookupColumns.DATA_ID +
2254        ");");
2255
2256        updateIndexStats(db, Tables.PHONE_LOOKUP,
2257                "phone_lookup_min_match_index", "10000 2 2 1");
2258
2259        SQLiteStatement update = db.compileStatement(
2260                "UPDATE " + Tables.PHONE_LOOKUP +
2261                " SET " + PhoneLookupColumns.MIN_MATCH + "=?" +
2262                " WHERE " + PhoneLookupColumns.DATA_ID + "=?");
2263
2264        // Populate the new column
2265        Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA +
2266                " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")",
2267                new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null);
2268        try {
2269            while (c.moveToNext()) {
2270                long dataId = c.getLong(0);
2271                String number = c.getString(1);
2272                if (!TextUtils.isEmpty(number)) {
2273                    update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number));
2274                    update.bindLong(2, dataId);
2275                    update.execute();
2276                }
2277            }
2278        } finally {
2279            c.close();
2280        }
2281    }
2282
2283    private void upgradeToVersion203(SQLiteDatabase db) {
2284        // Garbage-collect first. A bug in Eclair was sometimes leaving
2285        // raw_contacts in the database that no longer had contacts associated
2286        // with them.  To avoid failures during this database upgrade, drop
2287        // the orphaned raw_contacts.
2288        db.execSQL(
2289                "DELETE FROM raw_contacts" +
2290                " WHERE contact_id NOT NULL" +
2291                " AND contact_id NOT IN (SELECT _id FROM contacts)");
2292
2293        db.execSQL(
2294                "ALTER TABLE " + Tables.CONTACTS +
2295                " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)");
2296        db.execSQL(
2297                "ALTER TABLE " + Tables.RAW_CONTACTS +
2298                " ADD contact_in_visible_group INTEGER NOT NULL DEFAULT 0");
2299
2300        // For each Contact, find the RawContact that contributed the display name
2301        db.execSQL(
2302                "UPDATE " + Tables.CONTACTS +
2303                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
2304                        " SELECT " + RawContacts._ID +
2305                        " FROM " + Tables.RAW_CONTACTS +
2306                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
2307                        " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" +
2308                                Tables.CONTACTS + "." + Contacts.DISPLAY_NAME +
2309                        " ORDER BY " + RawContacts._ID +
2310                        " LIMIT 1)"
2311        );
2312
2313        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
2314                Contacts.NAME_RAW_CONTACT_ID +
2315        ");");
2316
2317        // If for some unknown reason we missed some names, let's make sure there are
2318        // no contacts without a name, picking a raw contact "at random".
2319        db.execSQL(
2320                "UPDATE " + Tables.CONTACTS +
2321                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
2322                        " SELECT " + RawContacts._ID +
2323                        " FROM " + Tables.RAW_CONTACTS +
2324                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
2325                        " ORDER BY " + RawContacts._ID +
2326                        " LIMIT 1)" +
2327                " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL"
2328        );
2329
2330        // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use.
2331        db.execSQL(
2332                "UPDATE " + Tables.CONTACTS +
2333                " SET " + Contacts.DISPLAY_NAME + "=NULL"
2334        );
2335
2336        // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow
2337        // indexing on (display_name, in_visible_group)
2338        db.execSQL(
2339                "UPDATE " + Tables.RAW_CONTACTS +
2340                " SET contact_in_visible_group=(" +
2341                        "SELECT " + Contacts.IN_VISIBLE_GROUP +
2342                        " FROM " + Tables.CONTACTS +
2343                        " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" +
2344                " WHERE " + RawContacts.CONTACT_ID + " NOT NULL"
2345        );
2346
2347        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
2348                "contact_in_visible_group" + "," +
2349                RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" +
2350        ");");
2351
2352        db.execSQL("DROP INDEX contacts_visible_index");
2353        db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
2354                Contacts.IN_VISIBLE_GROUP +
2355        ");");
2356    }
2357
2358    private void upgradeToVersion205(SQLiteDatabase db) {
2359        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2360                + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;");
2361        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2362                + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;");
2363        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2364                + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;");
2365        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2366                + " ADD " + RawContacts.SORT_KEY_PRIMARY
2367                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
2368        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2369                + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE
2370                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
2371
2372        final Locale locale = Locale.getDefault();
2373
2374        NameSplitter splitter = createNameSplitter();
2375
2376        SQLiteStatement rawContactUpdate = db.compileStatement(
2377                "UPDATE " + Tables.RAW_CONTACTS +
2378                " SET " +
2379                        RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
2380                        RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
2381                        RawContacts.PHONETIC_NAME + "=?," +
2382                        RawContacts.PHONETIC_NAME_STYLE + "=?," +
2383                        RawContacts.SORT_KEY_PRIMARY + "=?," +
2384                        RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
2385                " WHERE " + RawContacts._ID + "=?");
2386
2387        upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter);
2388        upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter);
2389
2390        db.execSQL("DROP INDEX raw_contact_sort_key1_index");
2391        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
2392                "contact_in_visible_group" + "," +
2393                RawContacts.SORT_KEY_PRIMARY +
2394        ");");
2395
2396        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
2397                "contact_in_visible_group" + "," +
2398                RawContacts.SORT_KEY_ALTERNATIVE +
2399        ");");
2400    }
2401
2402    private interface StructName205Query {
2403        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
2404
2405        String COLUMNS[] = {
2406                DataColumns.CONCRETE_ID,
2407                Data.RAW_CONTACT_ID,
2408                RawContacts.DISPLAY_NAME_SOURCE,
2409                RawContacts.DISPLAY_NAME_PRIMARY,
2410                StructuredName.PREFIX,
2411                StructuredName.GIVEN_NAME,
2412                StructuredName.MIDDLE_NAME,
2413                StructuredName.FAMILY_NAME,
2414                StructuredName.SUFFIX,
2415                StructuredName.PHONETIC_FAMILY_NAME,
2416                StructuredName.PHONETIC_MIDDLE_NAME,
2417                StructuredName.PHONETIC_GIVEN_NAME,
2418        };
2419
2420        int ID = 0;
2421        int RAW_CONTACT_ID = 1;
2422        int DISPLAY_NAME_SOURCE = 2;
2423        int DISPLAY_NAME = 3;
2424        int PREFIX = 4;
2425        int GIVEN_NAME = 5;
2426        int MIDDLE_NAME = 6;
2427        int FAMILY_NAME = 7;
2428        int SUFFIX = 8;
2429        int PHONETIC_FAMILY_NAME = 9;
2430        int PHONETIC_MIDDLE_NAME = 10;
2431        int PHONETIC_GIVEN_NAME = 11;
2432    }
2433
2434    private void upgradeStructuredNamesToVersion205(SQLiteDatabase db,
2435            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2436
2437        // Process structured names to detect the style of the full name and phonetic name
2438
2439        long mMimeType;
2440        try {
2441            mMimeType = DatabaseUtils.longForQuery(db,
2442                    "SELECT " + MimetypesColumns._ID +
2443                    " FROM " + Tables.MIMETYPES +
2444                    " WHERE " + MimetypesColumns.MIMETYPE
2445                            + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null);
2446        } catch (SQLiteDoneException e) {
2447            // No structured names in the database
2448            return;
2449        }
2450
2451        SQLiteStatement structuredNameUpdate = db.compileStatement(
2452                "UPDATE " + Tables.DATA +
2453                " SET " +
2454                        StructuredName.FULL_NAME_STYLE + "=?," +
2455                        StructuredName.DISPLAY_NAME + "=?," +
2456                        StructuredName.PHONETIC_NAME_STYLE + "=?" +
2457                " WHERE " + Data._ID + "=?");
2458
2459        NameSplitter.Name name = new NameSplitter.Name();
2460        StringBuilder sb = new StringBuilder();
2461        Cursor cursor = db.query(StructName205Query.TABLE,
2462                StructName205Query.COLUMNS,
2463                DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null);
2464        try {
2465            while (cursor.moveToNext()) {
2466                long dataId = cursor.getLong(StructName205Query.ID);
2467                long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID);
2468                int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE);
2469                String displayName = cursor.getString(StructName205Query.DISPLAY_NAME);
2470
2471                name.clear();
2472                name.prefix = cursor.getString(StructName205Query.PREFIX);
2473                name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME);
2474                name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME);
2475                name.familyName = cursor.getString(StructName205Query.FAMILY_NAME);
2476                name.suffix = cursor.getString(StructName205Query.SUFFIX);
2477                name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME);
2478                name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME);
2479                name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME);
2480
2481                upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name,
2482                        structuredNameUpdate, rawContactUpdate, splitter, sb);
2483            }
2484        } finally {
2485            cursor.close();
2486        }
2487    }
2488
2489    private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource,
2490            String currentDisplayName, NameSplitter.Name name,
2491            SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate,
2492            NameSplitter splitter, StringBuilder sb) {
2493
2494        splitter.guessNameStyle(name);
2495        int unadjustedFullNameStyle = name.fullNameStyle;
2496        name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle);
2497        String displayName = splitter.join(name, true, true);
2498
2499        // Don't update database with the adjusted fullNameStyle as it is locale
2500        // related
2501        structuredNameUpdate.bindLong(1, unadjustedFullNameStyle);
2502        DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName);
2503        structuredNameUpdate.bindLong(3, name.phoneticNameStyle);
2504        structuredNameUpdate.bindLong(4, dataId);
2505        structuredNameUpdate.execute();
2506
2507        if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) {
2508            String displayNameAlternative = splitter.join(name, false, false);
2509            String phoneticName = splitter.joinPhoneticName(name);
2510            String sortKey = null;
2511            String sortKeyAlternative = null;
2512
2513            if (phoneticName != null) {
2514                sortKey = sortKeyAlternative = phoneticName;
2515            } else if (name.fullNameStyle == FullNameStyle.CHINESE ||
2516                    name.fullNameStyle == FullNameStyle.CJK) {
2517                sortKey = sortKeyAlternative = ContactLocaleUtils.getIntance()
2518                        .getSortKey(displayName, name.fullNameStyle);
2519            }
2520
2521            if (sortKey == null) {
2522                sortKey = displayName;
2523                sortKeyAlternative = displayNameAlternative;
2524            }
2525
2526            updateRawContact205(rawContactUpdate, rawContactId, displayName,
2527                    displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey,
2528                    sortKeyAlternative);
2529        }
2530    }
2531
2532    private interface Organization205Query {
2533        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
2534
2535        String COLUMNS[] = {
2536                DataColumns.CONCRETE_ID,
2537                Data.RAW_CONTACT_ID,
2538                Organization.COMPANY,
2539                Organization.PHONETIC_NAME,
2540        };
2541
2542        int ID = 0;
2543        int RAW_CONTACT_ID = 1;
2544        int COMPANY = 2;
2545        int PHONETIC_NAME = 3;
2546    }
2547
2548    private void upgradeOrganizationsToVersion205(SQLiteDatabase db,
2549            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2550        final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE);
2551
2552        SQLiteStatement organizationUpdate = db.compileStatement(
2553                "UPDATE " + Tables.DATA +
2554                " SET " +
2555                        Organization.PHONETIC_NAME_STYLE + "=?" +
2556                " WHERE " + Data._ID + "=?");
2557
2558        Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS,
2559                DataColumns.MIMETYPE_ID + "=" + mimeType + " AND "
2560                        + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION,
2561                null, null, null, null);
2562        try {
2563            while (cursor.moveToNext()) {
2564                long dataId = cursor.getLong(Organization205Query.ID);
2565                long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID);
2566                String company = cursor.getString(Organization205Query.COMPANY);
2567                String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME);
2568
2569                int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName);
2570
2571                organizationUpdate.bindLong(1, phoneticNameStyle);
2572                organizationUpdate.bindLong(2, dataId);
2573                organizationUpdate.execute();
2574
2575                String sortKey = null;
2576                if (phoneticName == null && company != null) {
2577                    int nameStyle = splitter.guessFullNameStyle(company);
2578                    nameStyle = splitter.getAdjustedFullNameStyle(nameStyle);
2579                    if (nameStyle == FullNameStyle.CHINESE ||
2580                            nameStyle == FullNameStyle.CJK ) {
2581                        sortKey = ContactLocaleUtils.getIntance()
2582                                .getSortKey(company, nameStyle);
2583                    }
2584                }
2585
2586                if (sortKey == null) {
2587                    sortKey = company;
2588                }
2589
2590                updateRawContact205(rawContactUpdate, rawContactId, company,
2591                        company, phoneticNameStyle, phoneticName, sortKey, sortKey);
2592            }
2593        } finally {
2594            cursor.close();
2595        }
2596    }
2597
2598    private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId,
2599            String displayName, String displayNameAlternative, int phoneticNameStyle,
2600            String phoneticName, String sortKeyPrimary, String sortKeyAlternative) {
2601        bindString(rawContactUpdate, 1, displayName);
2602        bindString(rawContactUpdate, 2, displayNameAlternative);
2603        bindString(rawContactUpdate, 3, phoneticName);
2604        rawContactUpdate.bindLong(4, phoneticNameStyle);
2605        bindString(rawContactUpdate, 5, sortKeyPrimary);
2606        bindString(rawContactUpdate, 6, sortKeyAlternative);
2607        rawContactUpdate.bindLong(7, rawContactId);
2608        rawContactUpdate.execute();
2609    }
2610
2611    private void upgrateToVersion206(SQLiteDatabase db) {
2612        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2613                + " ADD " + RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0;");
2614    }
2615
2616    /**
2617     * Fix for the bug where name lookup records for organizations would get removed by
2618     * unrelated updates of the data rows.
2619     */
2620    private void upgradeToVersion300(SQLiteDatabase db) {
2621        // No longer needed
2622    }
2623
2624    private static final class Upgrade303Query {
2625        public static final String TABLE = Tables.DATA;
2626
2627        public static final String SELECTION =
2628                DataColumns.MIMETYPE_ID + "=?" +
2629                    " AND " + Data._ID + " NOT IN " +
2630                    "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" +
2631                    " AND " + Data.DATA1 + " NOT NULL";
2632
2633        public static final String COLUMNS[] = {
2634                Data._ID,
2635                Data.RAW_CONTACT_ID,
2636                Data.DATA1,
2637        };
2638
2639        public static final int ID = 0;
2640        public static final int RAW_CONTACT_ID = 1;
2641        public static final int DATA1 = 2;
2642    }
2643
2644    /**
2645     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2646     * emails during the sync.  We need to restore the lost name lookup rows.
2647     */
2648    private void upgradeEmailToVersion303(SQLiteDatabase db) {
2649        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2650        if (mimeTypeId == -1) {
2651            return;
2652        }
2653
2654        ContentValues values = new ContentValues();
2655
2656        // Find all data rows with the mime type "email" that are missing name lookup
2657        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2658                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2659                null, null, null);
2660        try {
2661            while (cursor.moveToNext()) {
2662                long dataId = cursor.getLong(Upgrade303Query.ID);
2663                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2664                String value = cursor.getString(Upgrade303Query.DATA1);
2665                value = extractHandleFromEmailAddress(value);
2666
2667                if (value != null) {
2668                    values.put(NameLookupColumns.DATA_ID, dataId);
2669                    values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2670                    values.put(NameLookupColumns.NAME_TYPE, NameLookupType.EMAIL_BASED_NICKNAME);
2671                    values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2672                    db.insert(Tables.NAME_LOOKUP, null, values);
2673                }
2674            }
2675        } finally {
2676            cursor.close();
2677        }
2678    }
2679
2680    /**
2681     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2682     * nicknames during the sync.  We need to restore the lost name lookup rows.
2683     */
2684    private void upgradeNicknameToVersion303(SQLiteDatabase db) {
2685        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
2686        if (mimeTypeId == -1) {
2687            return;
2688        }
2689
2690        ContentValues values = new ContentValues();
2691
2692        // Find all data rows with the mime type "nickname" that are missing name lookup
2693        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2694                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2695                null, null, null);
2696        try {
2697            while (cursor.moveToNext()) {
2698                long dataId = cursor.getLong(Upgrade303Query.ID);
2699                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2700                String value = cursor.getString(Upgrade303Query.DATA1);
2701
2702                values.put(NameLookupColumns.DATA_ID, dataId);
2703                values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2704                values.put(NameLookupColumns.NAME_TYPE, NameLookupType.NICKNAME);
2705                values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2706                db.insert(Tables.NAME_LOOKUP, null, values);
2707            }
2708        } finally {
2709            cursor.close();
2710        }
2711    }
2712
2713    private void upgradeToVersion304(SQLiteDatabase db) {
2714        // Mimetype table requires an index on mime type
2715        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" +
2716                MimetypesColumns.MIMETYPE +
2717        ");");
2718    }
2719
2720    private void upgradeToVersion306(SQLiteDatabase db) {
2721        // Fix invalid lookup that was used for Exchange contacts (it was not escaped)
2722        // It happened when a new contact was created AND synchronized
2723        final StringBuilder lookupKeyBuilder = new StringBuilder();
2724        final SQLiteStatement updateStatement = db.compileStatement(
2725                "UPDATE contacts " +
2726                "SET lookup=? " +
2727                "WHERE _id=?");
2728        final Cursor contactIdCursor = db.rawQuery(
2729                "SELECT DISTINCT contact_id " +
2730                "FROM raw_contacts " +
2731                "WHERE deleted=0 AND account_type='com.android.exchange'",
2732                null);
2733        try {
2734            while (contactIdCursor.moveToNext()) {
2735                final long contactId = contactIdCursor.getLong(0);
2736                lookupKeyBuilder.setLength(0);
2737                final Cursor c = db.rawQuery(
2738                        "SELECT account_type, account_name, _id, sourceid, display_name " +
2739                        "FROM raw_contacts " +
2740                        "WHERE contact_id=? " +
2741                        "ORDER BY _id",
2742                        new String[] { String.valueOf(contactId) });
2743                try {
2744                    while (c.moveToNext()) {
2745                        ContactLookupKey.appendToLookupKey(lookupKeyBuilder,
2746                                c.getString(0),
2747                                c.getString(1),
2748                                c.getLong(2),
2749                                c.getString(3),
2750                                c.getString(4));
2751                    }
2752                } finally {
2753                    c.close();
2754                }
2755
2756                if (lookupKeyBuilder.length() == 0) {
2757                    updateStatement.bindNull(1);
2758                } else {
2759                    updateStatement.bindString(1, Uri.encode(lookupKeyBuilder.toString()));
2760                }
2761                updateStatement.bindLong(2, contactId);
2762
2763                updateStatement.execute();
2764            }
2765        } finally {
2766            updateStatement.close();
2767            contactIdCursor.close();
2768        }
2769    }
2770
2771    private void upgradeToVersion307(SQLiteDatabase db) {
2772        db.execSQL("CREATE TABLE properties (" +
2773                "property_key TEXT PRIMARY_KEY, " +
2774                "property_value TEXT" +
2775        ");");
2776    }
2777
2778    private void upgradeToVersion308(SQLiteDatabase db) {
2779        db.execSQL("CREATE TABLE accounts (" +
2780                "account_name TEXT, " +
2781                "account_type TEXT " +
2782        ");");
2783
2784        db.execSQL("INSERT INTO accounts " +
2785                "SELECT DISTINCT account_name, account_type FROM raw_contacts");
2786    }
2787
2788    private void upgradeToVersion400(SQLiteDatabase db) {
2789        db.execSQL("ALTER TABLE " + Tables.GROUPS
2790                + " ADD " + Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0;");
2791        db.execSQL("ALTER TABLE " + Tables.GROUPS
2792                + " ADD " + Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0;");
2793    }
2794
2795    private void upgradeToVersion353(SQLiteDatabase db) {
2796        db.execSQL("DELETE FROM contacts " +
2797                "WHERE NOT EXISTS (SELECT 1 FROM raw_contacts WHERE contact_id=contacts._id)");
2798    }
2799
2800    private void rebuildNameLookup(SQLiteDatabase db) {
2801        db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2802        insertNameLookup(db);
2803        createContactsIndexes(db);
2804    }
2805
2806    /**
2807     * Regenerates all locale-sensitive data: nickname_lookup, name_lookup and sort keys.
2808     */
2809    public void setLocale(ContactsProvider2 provider, Locale locale) {
2810        Log.i(TAG, "Switching to locale " + locale);
2811
2812        long start = SystemClock.uptimeMillis();
2813        SQLiteDatabase db = getWritableDatabase();
2814        db.setLocale(locale);
2815        db.beginTransaction();
2816        try {
2817            db.execSQL("DROP INDEX raw_contact_sort_key1_index");
2818            db.execSQL("DROP INDEX raw_contact_sort_key2_index");
2819            db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2820
2821            loadNicknameLookupTable(db);
2822            insertNameLookup(db);
2823            rebuildSortKeys(db, provider);
2824            createContactsIndexes(db);
2825            db.setTransactionSuccessful();
2826        } finally {
2827            db.endTransaction();
2828        }
2829
2830        Log.i(TAG, "Locale change completed in " + (SystemClock.uptimeMillis() - start) + "ms");
2831    }
2832
2833    /**
2834     * Regenerates sort keys for all contacts.
2835     */
2836    private void rebuildSortKeys(SQLiteDatabase db, ContactsProvider2 provider) {
2837        Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID},
2838                null, null, null, null, null);
2839        try {
2840            while (cursor.moveToNext()) {
2841                long rawContactId = cursor.getLong(0);
2842                updateRawContactDisplayName(db, rawContactId);
2843            }
2844        } finally {
2845            cursor.close();
2846        }
2847    }
2848
2849    private void insertNameLookup(SQLiteDatabase db) {
2850        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP);
2851
2852        SQLiteStatement nameLookupInsert = db.compileStatement(
2853                "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
2854                        + NameLookupColumns.RAW_CONTACT_ID + ","
2855                        + NameLookupColumns.DATA_ID + ","
2856                        + NameLookupColumns.NAME_TYPE + ","
2857                        + NameLookupColumns.NORMALIZED_NAME +
2858                ") VALUES (?,?,?,?)");
2859
2860        try {
2861            insertStructuredNameLookup(db, nameLookupInsert);
2862            insertEmailLookup(db, nameLookupInsert);
2863            insertNicknameLookup(db, nameLookupInsert);
2864        } finally {
2865            nameLookupInsert.close();
2866        }
2867    }
2868
2869    private static final class StructuredNameQuery {
2870        public static final String TABLE = Tables.DATA;
2871
2872        public static final String SELECTION =
2873                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2874
2875        public static final String COLUMNS[] = {
2876                StructuredName._ID,
2877                StructuredName.RAW_CONTACT_ID,
2878                StructuredName.DISPLAY_NAME,
2879        };
2880
2881        public static final int ID = 0;
2882        public static final int RAW_CONTACT_ID = 1;
2883        public static final int DISPLAY_NAME = 2;
2884    }
2885
2886    private class StructuredNameLookupBuilder extends NameLookupBuilder {
2887
2888        private final SQLiteStatement mNameLookupInsert;
2889        private final CommonNicknameCache mCommonNicknameCache;
2890
2891        public StructuredNameLookupBuilder(NameSplitter splitter,
2892                CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) {
2893            super(splitter);
2894            this.mCommonNicknameCache = commonNicknameCache;
2895            this.mNameLookupInsert = nameLookupInsert;
2896        }
2897
2898        @Override
2899        protected void insertNameLookup(long rawContactId, long dataId, int lookupType,
2900                String name) {
2901            if (!TextUtils.isEmpty(name)) {
2902                ContactsDatabaseHelper.this.insertNormalizedNameLookup(mNameLookupInsert,
2903                        rawContactId, dataId, lookupType, name);
2904            }
2905        }
2906
2907        @Override
2908        protected String[] getCommonNicknameClusters(String normalizedName) {
2909            return mCommonNicknameCache.getCommonNicknameClusters(normalizedName);
2910        }
2911    }
2912
2913    /**
2914     * Inserts name lookup rows for all structured names in the database.
2915     */
2916    private void insertStructuredNameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2917        NameSplitter nameSplitter = createNameSplitter();
2918        NameLookupBuilder nameLookupBuilder = new StructuredNameLookupBuilder(nameSplitter,
2919                new CommonNicknameCache(db), nameLookupInsert);
2920        final long mimeTypeId = lookupMimeTypeId(db, StructuredName.CONTENT_ITEM_TYPE);
2921        Cursor cursor = db.query(StructuredNameQuery.TABLE, StructuredNameQuery.COLUMNS,
2922                StructuredNameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2923                null, null, null);
2924        try {
2925            while (cursor.moveToNext()) {
2926                long dataId = cursor.getLong(StructuredNameQuery.ID);
2927                long rawContactId = cursor.getLong(StructuredNameQuery.RAW_CONTACT_ID);
2928                String name = cursor.getString(StructuredNameQuery.DISPLAY_NAME);
2929                int fullNameStyle = nameSplitter.guessFullNameStyle(name);
2930                fullNameStyle = nameSplitter.getAdjustedFullNameStyle(fullNameStyle);
2931                nameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle);
2932            }
2933        } finally {
2934            cursor.close();
2935        }
2936    }
2937
2938    private static final class OrganizationQuery {
2939        public static final String TABLE = Tables.DATA;
2940
2941        public static final String SELECTION =
2942                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2943
2944        public static final String COLUMNS[] = {
2945                Organization._ID,
2946                Organization.RAW_CONTACT_ID,
2947                Organization.COMPANY,
2948                Organization.TITLE,
2949        };
2950
2951        public static final int ID = 0;
2952        public static final int RAW_CONTACT_ID = 1;
2953        public static final int COMPANY = 2;
2954        public static final int TITLE = 3;
2955    }
2956
2957    private static final class EmailQuery {
2958        public static final String TABLE = Tables.DATA;
2959
2960        public static final String SELECTION =
2961                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2962
2963        public static final String COLUMNS[] = {
2964                Email._ID,
2965                Email.RAW_CONTACT_ID,
2966                Email.ADDRESS,
2967        };
2968
2969        public static final int ID = 0;
2970        public static final int RAW_CONTACT_ID = 1;
2971        public static final int ADDRESS = 2;
2972    }
2973
2974    /**
2975     * Inserts name lookup rows for all email addresses in the database.
2976     */
2977    private void insertEmailLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2978        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2979        Cursor cursor = db.query(EmailQuery.TABLE, EmailQuery.COLUMNS,
2980                EmailQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2981                null, null, null);
2982        try {
2983            while (cursor.moveToNext()) {
2984                long dataId = cursor.getLong(EmailQuery.ID);
2985                long rawContactId = cursor.getLong(EmailQuery.RAW_CONTACT_ID);
2986                String address = cursor.getString(EmailQuery.ADDRESS);
2987                address = extractHandleFromEmailAddress(address);
2988                insertNameLookup(nameLookupInsert, rawContactId, dataId,
2989                        NameLookupType.EMAIL_BASED_NICKNAME, address);
2990            }
2991        } finally {
2992            cursor.close();
2993        }
2994    }
2995
2996    private static final class NicknameQuery {
2997        public static final String TABLE = Tables.DATA;
2998
2999        public static final String SELECTION =
3000                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
3001
3002        public static final String COLUMNS[] = {
3003                Nickname._ID,
3004                Nickname.RAW_CONTACT_ID,
3005                Nickname.NAME,
3006        };
3007
3008        public static final int ID = 0;
3009        public static final int RAW_CONTACT_ID = 1;
3010        public static final int NAME = 2;
3011    }
3012
3013    /**
3014     * Inserts name lookup rows for all nicknames in the database.
3015     */
3016    private void insertNicknameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
3017        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
3018        Cursor cursor = db.query(NicknameQuery.TABLE, NicknameQuery.COLUMNS,
3019                NicknameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
3020                null, null, null);
3021        try {
3022            while (cursor.moveToNext()) {
3023                long dataId = cursor.getLong(NicknameQuery.ID);
3024                long rawContactId = cursor.getLong(NicknameQuery.RAW_CONTACT_ID);
3025                String nickname = cursor.getString(NicknameQuery.NAME);
3026                insertNameLookup(nameLookupInsert, rawContactId, dataId,
3027                        NameLookupType.NICKNAME, nickname);
3028            }
3029        } finally {
3030            cursor.close();
3031        }
3032    }
3033
3034    /**
3035     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
3036     */
3037    public void insertNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
3038            int lookupType, String name) {
3039        if (TextUtils.isEmpty(name)) {
3040            return;
3041        }
3042
3043        String normalized = NameNormalizer.normalize(name);
3044        if (TextUtils.isEmpty(normalized)) {
3045            return;
3046        }
3047
3048        insertNormalizedNameLookup(stmt, rawContactId, dataId, lookupType, normalized);
3049    }
3050
3051    private void insertNormalizedNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
3052            int lookupType, String normalizedName) {
3053        stmt.bindLong(1, rawContactId);
3054        stmt.bindLong(2, dataId);
3055        stmt.bindLong(3, lookupType);
3056        stmt.bindString(4, normalizedName);
3057        stmt.executeInsert();
3058    }
3059
3060    /**
3061     * Changing the VISIBLE bit from a field on both RawContacts and Contacts to a separate table.
3062     */
3063    private void upgradeToVersion401(SQLiteDatabase db) {
3064        db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" +
3065                Contacts._ID + " INTEGER PRIMARY KEY" +
3066        ");");
3067        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
3068                " SELECT " + Contacts._ID +
3069                " FROM " + Tables.CONTACTS +
3070                " WHERE " + Contacts.IN_VISIBLE_GROUP + "!=0");
3071        db.execSQL("DROP INDEX contacts_visible_index");
3072    }
3073
3074    /**
3075     * Introducing a new table: directories.
3076     */
3077    private void upgradeToVersion402(SQLiteDatabase db) {
3078        createDirectoriesTable(db);
3079    }
3080
3081    private void upgradeToVersion403(SQLiteDatabase db) {
3082        db.execSQL("DROP TABLE IF EXISTS directories;");
3083        createDirectoriesTable(db);
3084
3085        db.execSQL("ALTER TABLE raw_contacts"
3086                + " ADD raw_contact_is_read_only INTEGER NOT NULL DEFAULT 0;");
3087
3088        db.execSQL("ALTER TABLE data"
3089                + " ADD is_read_only INTEGER NOT NULL DEFAULT 0;");
3090    }
3091
3092    private void upgradeToVersion405(SQLiteDatabase db) {
3093        db.execSQL("DROP TABLE IF EXISTS phone_lookup;");
3094        // Private phone numbers table used for lookup
3095        db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
3096                PhoneLookupColumns.DATA_ID
3097                + " INTEGER REFERENCES data(_id) NOT NULL," +
3098                PhoneLookupColumns.RAW_CONTACT_ID
3099                + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
3100                PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
3101                PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
3102        ");");
3103
3104        db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
3105                PhoneLookupColumns.NORMALIZED_NUMBER + "," +
3106                PhoneLookupColumns.RAW_CONTACT_ID + "," +
3107                PhoneLookupColumns.DATA_ID +
3108        ");");
3109
3110        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
3111                PhoneLookupColumns.MIN_MATCH + "," +
3112                PhoneLookupColumns.RAW_CONTACT_ID + "," +
3113                PhoneLookupColumns.DATA_ID +
3114        ");");
3115
3116        final long mimeTypeId = lookupMimeTypeId(db, Phone.CONTENT_ITEM_TYPE);
3117        if (mimeTypeId == -1) {
3118            return;
3119        }
3120
3121        Cursor cursor = db.rawQuery(
3122                    "SELECT _id, " + Phone.RAW_CONTACT_ID + ", " + Phone.NUMBER +
3123                    " FROM " + Tables.DATA +
3124                    " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimeTypeId
3125                            + " AND " + Phone.NUMBER + " NOT NULL", null);
3126
3127        ContentValues phoneValues = new ContentValues();
3128        try {
3129            while (cursor.moveToNext()) {
3130                long dataID = cursor.getLong(0);
3131                long rawContactID = cursor.getLong(1);
3132                String number = cursor.getString(2);
3133                String normalizedNumber = PhoneNumberUtils.normalizeNumber(number);
3134                if (!TextUtils.isEmpty(normalizedNumber)) {
3135                    phoneValues.clear();
3136                    phoneValues.put(PhoneLookupColumns.RAW_CONTACT_ID, rawContactID);
3137                    phoneValues.put(PhoneLookupColumns.DATA_ID, dataID);
3138                    phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, normalizedNumber);
3139                    phoneValues.put(PhoneLookupColumns.MIN_MATCH,
3140                            PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber));
3141                    db.insert(Tables.PHONE_LOOKUP, null, phoneValues);
3142                }
3143            }
3144        } finally {
3145            cursor.close();
3146        }
3147    }
3148
3149    private void upgradeToVersion406(SQLiteDatabase db) {
3150        db.execSQL("ALTER TABLE calls ADD countryiso TEXT;");
3151    }
3152
3153    private void upgradeToVersion409(SQLiteDatabase db) {
3154        db.execSQL("DROP TABLE IF EXISTS directories;");
3155        createDirectoriesTable(db);
3156    }
3157
3158    /**
3159     * Adding DEFAULT_DIRECTORY table.
3160     * DEFAULT_DIRECTORY should contain every contact which should be shown to users in default.
3161     * - if a contact doesn't belong to any account (local contact), it should be in
3162     *   default_directory
3163     * - if a contact belongs to an account that doesn't have a "default" group, it should be in
3164     *   default_directory
3165     * - if a contact belongs to an account that has a "default" group (like Google directory,
3166     *   which has "My contacts" group as default), it should be in default_directory.
3167     *
3168     * This logic assumes that accounts with the "default" group should have at least one
3169     * group with AUTO_ADD (implying it is the default group) flag in the groups table.
3170     */
3171    private void upgradeToVersion411(SQLiteDatabase db) {
3172        db.execSQL("DROP TABLE IF EXISTS " + Tables.DEFAULT_DIRECTORY);
3173        db.execSQL("CREATE TABLE default_directory (_id INTEGER PRIMARY KEY);");
3174
3175        // Process contacts without an account
3176        db.execSQL("INSERT OR IGNORE INTO default_directory " +
3177                " SELECT contact_id " +
3178                " FROM raw_contacts " +
3179                " WHERE raw_contacts.account_name IS NULL " +
3180                "   AND raw_contacts.account_type IS NULL ");
3181
3182        // Process accounts that don't have a default group (e.g. Exchange).
3183        db.execSQL("INSERT OR IGNORE INTO default_directory " +
3184                " SELECT contact_id " +
3185                " FROM raw_contacts " +
3186                " WHERE NOT EXISTS" +
3187                " (SELECT _id " +
3188                "  FROM groups " +
3189                "  WHERE raw_contacts.account_name = groups.account_name" +
3190                "    AND raw_contacts.account_type = groups.account_type" +
3191                "    AND groups.auto_add != 0)");
3192
3193        final long mimetype = lookupMimeTypeId(db, GroupMembership.CONTENT_ITEM_TYPE);
3194
3195        // Process accounts that do have a default group (e.g. Google)
3196        db.execSQL("INSERT OR IGNORE INTO default_directory " +
3197                " SELECT contact_id " +
3198                " FROM raw_contacts " +
3199                " JOIN data " +
3200                "   ON (raw_contacts._id=raw_contact_id)" +
3201                " WHERE mimetype_id=" + mimetype +
3202                " AND EXISTS" +
3203                " (SELECT _id" +
3204                "  FROM groups" +
3205                "  WHERE raw_contacts.account_name = groups.account_name" +
3206                "    AND raw_contacts.account_type = groups.account_type" +
3207                "    AND groups.auto_add != 0)");
3208    }
3209
3210    private void upgradeToVersion413(SQLiteDatabase db) {
3211        db.execSQL("DROP TABLE IF EXISTS directories;");
3212        createDirectoriesTable(db);
3213    }
3214
3215    private void upgradeToVersion415(SQLiteDatabase db) {
3216        db.execSQL(
3217                "ALTER TABLE " + Tables.GROUPS +
3218                " ADD " + Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0");
3219        db.execSQL(
3220                "UPDATE " + Tables.GROUPS +
3221                "   SET " + Groups.GROUP_IS_READ_ONLY + "=1" +
3222                " WHERE " + Groups.SYSTEM_ID + " NOT NULL");
3223    }
3224
3225    private void upgradeToVersion416(SQLiteDatabase db) {
3226        db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP +
3227                " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");");
3228    }
3229
3230    private void upgradeToVersion501(SQLiteDatabase db) {
3231        // Remove organization rows from the name lookup, we now use search index for that
3232        db.execSQL("DELETE FROM name_lookup WHERE name_type=5");
3233    }
3234
3235    private void upgradeToVersion502(SQLiteDatabase db) {
3236        // Remove Chinese and Korean name lookup - this data is now in the search index
3237        db.execSQL("DELETE FROM name_lookup WHERE name_type IN (6, 7)");
3238    }
3239
3240    private void upgradeToVersion504(SQLiteDatabase db) {
3241        populateMimeTypeCache(db);
3242
3243        // Find all names with prefixes and recreate display name
3244        Cursor cursor = db.rawQuery(
3245                "SELECT " + StructuredName.RAW_CONTACT_ID +
3246                " FROM " + Tables.DATA +
3247                " WHERE " + DataColumns.MIMETYPE_ID + "=?"
3248                        + " AND " + StructuredName.PREFIX + " NOT NULL",
3249                new String[]{ String.valueOf(mMimeTypeIdStructuredName) });
3250
3251        try {
3252            while(cursor.moveToNext()) {
3253                long rawContactId = cursor.getLong(0);
3254                updateRawContactDisplayName(db, rawContactId);
3255            }
3256
3257        } finally {
3258            cursor.close();
3259        }
3260    }
3261
3262    private void upgradeToVersion600(SQLiteDatabase db) {
3263        // Add a column to the Accounts table to track which raw contact ID (if any) represents that
3264        // account's contribution to the user's profile Contact.
3265        db.execSQL("ALTER TABLE accounts" +
3266                " ADD profile_raw_contact_id INTEGER");
3267        db.execSQL("CREATE INDEX accounts_profile_raw_contact_id_index ON accounts" +
3268                " (profile_raw_contact_id);");
3269    }
3270
3271    private void upgradeToVersion601(SQLiteDatabase db) {
3272        db.execSQL("CREATE TABLE data_usage_stat(" +
3273                "stat_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3274                "data_id INTEGER NOT NULL, " +
3275                "usage_type INTEGER NOT NULL DEFAULT 0, " +
3276                "times_used INTEGER NOT NULL DEFAULT 0, " +
3277                "last_time_used INTERGER NOT NULL DEFAULT 0, " +
3278                "FOREIGN KEY(data_id) REFERENCES data(_id));");
3279        db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " +
3280                "data_usage_stat (data_id, usage_type)");
3281    }
3282
3283    private void upgradeToVersion602(SQLiteDatabase db) {
3284        db.execSQL("ALTER TABLE calls ADD voicemail_uri TEXT;");
3285        db.execSQL("ALTER TABLE calls ADD _data TEXT;");
3286        db.execSQL("ALTER TABLE calls ADD has_content INTEGER;");
3287        db.execSQL("ALTER TABLE calls ADD mime_type TEXT;");
3288        db.execSQL("ALTER TABLE calls ADD source_data TEXT;");
3289        db.execSQL("ALTER TABLE calls ADD source_package TEXT;");
3290        db.execSQL("ALTER TABLE calls ADD state INTEGER;");
3291    }
3292
3293    private void upgradeToVersion604(SQLiteDatabase db) {
3294        db.execSQL("CREATE TABLE voicemail_status (" +
3295                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
3296                "source_package TEXT UNIQUE NOT NULL," +
3297                "settings_uri TEXT," +
3298                "voicemail_access_uri TEXT," +
3299                "configuration_state INTEGER," +
3300                "data_channel_state INTEGER," +
3301                "notification_channel_state INTEGER" +
3302        ");");
3303    }
3304
3305    private void upgradeToVersion605(SQLiteDatabase db) {
3306        // This version used to create the stream item and stream item photos tables, but a newer
3307        // version of those tables is created in version 609 below.  So omitting the creation in
3308        // this upgrade step to avoid a create->drop->create.
3309    }
3310
3311    private void upgradeToVersion606(SQLiteDatabase db) {
3312        db.execSQL("DROP VIEW IF EXISTS view_contacts_restricted;");
3313        db.execSQL("DROP VIEW IF EXISTS view_data_restricted;");
3314        db.execSQL("DROP VIEW IF EXISTS view_raw_contacts_restricted;");
3315        db.execSQL("DROP VIEW IF EXISTS view_raw_entities_restricted;");
3316        db.execSQL("DROP VIEW IF EXISTS view_entities_restricted;");
3317        db.execSQL("DROP VIEW IF EXISTS view_data_usage_stat_restricted;");
3318        db.execSQL("DROP INDEX IF EXISTS contacts_restricted_index");
3319
3320        // We should remove the restricted columns here as well, but unfortunately SQLite doesn't
3321        // provide ALTER TABLE DROP COLUMN. As they have DEFAULT 0, we can keep but ignore them
3322    }
3323
3324    private void upgradeToVersion607(SQLiteDatabase db) {
3325        // We added "action" and "action_uri" to groups here, but realized this was not a smart
3326        // move. This upgrade step has been removed (all dogfood phones that executed this step
3327        // will have those columns, but that shouldn't hurt. Unfortunately, SQLite makes it hard
3328        // to remove columns)
3329    }
3330
3331    private void upgradeToVersion608(SQLiteDatabase db) {
3332        db.execSQL("ALTER TABLE contacts ADD photo_file_id INTEGER REFERENCES photo_files(_id);");
3333
3334        db.execSQL("CREATE TABLE photo_files(" +
3335                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3336                "height INTEGER NOT NULL, " +
3337                "width INTEGER NOT NULL, " +
3338                "filesize INTEGER NOT NULL);");
3339    }
3340
3341    private void upgradeToVersion609(SQLiteDatabase db) {
3342        // This version used to create the stream item and stream item photos tables, but a newer
3343        // version of those tables is created in version 613 below.  So omitting the creation in
3344        // this upgrade step to avoid a create->drop->create.
3345    }
3346
3347    private void upgradeToVersion610(SQLiteDatabase db) {
3348        db.execSQL("ALTER TABLE calls ADD is_read INTEGER;");
3349    }
3350
3351    private void upgradeToVersion611(SQLiteDatabase db) {
3352        db.execSQL("ALTER TABLE raw_contacts ADD data_set TEXT DEFAULT NULL;");
3353        db.execSQL("ALTER TABLE groups ADD data_set TEXT DEFAULT NULL;");
3354        db.execSQL("ALTER TABLE accounts ADD data_set TEXT DEFAULT NULL;");
3355
3356        db.execSQL("CREATE INDEX raw_contacts_source_id_data_set_index ON raw_contacts " +
3357                "(sourceid, account_type, account_name, data_set);");
3358
3359        db.execSQL("CREATE INDEX groups_source_id_data_set_index ON groups " +
3360                "(sourceid, account_type, account_name, data_set);");
3361    }
3362
3363    private void upgradeToVersion612(SQLiteDatabase db) {
3364        db.execSQL("ALTER TABLE calls ADD geocoded_location TEXT DEFAULT NULL;");
3365        // Old calls will not have a geocoded location; new calls will get it when inserted.
3366    }
3367
3368    private void upgradeToVersion613(SQLiteDatabase db) {
3369        // The stream item and stream item photos APIs were not in-use by anyone in the time
3370        // between their initial creation (in v609) and this update.  So we're just dropping
3371        // and re-creating them to get appropriate columns.  The delta is as follows:
3372        // - In stream_items, package_id was replaced by res_package.
3373        // - In stream_item_photos, picture was replaced by photo_file_id.
3374        // - Instead of resource ids for icon and label, we use resource name strings now
3375        // - Added sync columns
3376        // - Removed action and action_uri
3377        // - Text and comments are now nullable
3378
3379        db.execSQL("DROP TABLE IF EXISTS stream_items");
3380        db.execSQL("DROP TABLE IF EXISTS stream_item_photos");
3381
3382        db.execSQL("CREATE TABLE stream_items(" +
3383                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3384                "raw_contact_id INTEGER NOT NULL, " +
3385                "res_package TEXT, " +
3386                "icon TEXT, " +
3387                "label TEXT, " +
3388                "text TEXT, " +
3389                "timestamp INTEGER NOT NULL, " +
3390                "comments TEXT, " +
3391                "stream_item_sync1 TEXT, " +
3392                "stream_item_sync2 TEXT, " +
3393                "stream_item_sync3 TEXT, " +
3394                "stream_item_sync4 TEXT, " +
3395                "FOREIGN KEY(raw_contact_id) REFERENCES raw_contacts(_id));");
3396
3397        db.execSQL("CREATE TABLE stream_item_photos(" +
3398                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3399                "stream_item_id INTEGER NOT NULL, " +
3400                "sort_index INTEGER, " +
3401                "photo_file_id INTEGER NOT NULL, " +
3402                "stream_item_photo_sync1 TEXT, " +
3403                "stream_item_photo_sync2 TEXT, " +
3404                "stream_item_photo_sync3 TEXT, " +
3405                "stream_item_photo_sync4 TEXT, " +
3406                "FOREIGN KEY(stream_item_id) REFERENCES stream_items(_id));");
3407    }
3408
3409    public String extractHandleFromEmailAddress(String email) {
3410        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
3411        if (tokens.length == 0) {
3412            return null;
3413        }
3414
3415        String address = tokens[0].getAddress();
3416        int at = address.indexOf('@');
3417        if (at != -1) {
3418            return address.substring(0, at);
3419        }
3420        return null;
3421    }
3422
3423    public String extractAddressFromEmailAddress(String email) {
3424        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
3425        if (tokens.length == 0) {
3426            return null;
3427        }
3428
3429        return tokens[0].getAddress().trim();
3430    }
3431
3432    private static long lookupMimeTypeId(SQLiteDatabase db, String mimeType) {
3433        try {
3434            return DatabaseUtils.longForQuery(db,
3435                    "SELECT " + MimetypesColumns._ID +
3436                    " FROM " + Tables.MIMETYPES +
3437                    " WHERE " + MimetypesColumns.MIMETYPE
3438                            + "='" + mimeType + "'", null);
3439        } catch (SQLiteDoneException e) {
3440            // No rows of this type in the database
3441            return -1;
3442        }
3443    }
3444
3445    private void bindString(SQLiteStatement stmt, int index, String value) {
3446        if (value == null) {
3447            stmt.bindNull(index);
3448        } else {
3449            stmt.bindString(index, value);
3450        }
3451    }
3452
3453    private void bindLong(SQLiteStatement stmt, int index, Number value) {
3454        if (value == null) {
3455            stmt.bindNull(index);
3456        } else {
3457            stmt.bindLong(index, value.longValue());
3458        }
3459    }
3460
3461    /**
3462     * Adds index stats into the SQLite database to force it to always use the lookup indexes.
3463     */
3464    private void updateSqliteStats(SQLiteDatabase db) {
3465
3466        // Specific stats strings are based on an actual large database after running ANALYZE
3467        try {
3468            updateIndexStats(db, Tables.CONTACTS,
3469                    "contacts_has_phone_index", "10000 500");
3470
3471            updateIndexStats(db, Tables.RAW_CONTACTS,
3472                    "raw_contacts_source_id_index", "10000 1 1 1");
3473            updateIndexStats(db, Tables.RAW_CONTACTS,
3474                    "raw_contacts_contact_id_index", "10000 2");
3475
3476            updateIndexStats(db, Tables.NAME_LOOKUP,
3477                    "name_lookup_raw_contact_id_index", "10000 3");
3478            updateIndexStats(db, Tables.NAME_LOOKUP,
3479                    "name_lookup_index", "10000 3 2 2 1");
3480            updateIndexStats(db, Tables.NAME_LOOKUP,
3481                    "sqlite_autoindex_name_lookup_1", "10000 3 2 1");
3482
3483            updateIndexStats(db, Tables.PHONE_LOOKUP,
3484                    "phone_lookup_index", "10000 2 2 1");
3485            updateIndexStats(db, Tables.PHONE_LOOKUP,
3486                    "phone_lookup_min_match_index", "10000 2 2 1");
3487
3488            updateIndexStats(db, Tables.DATA,
3489                    "data_mimetype_data1_index", "60000 5000 2");
3490            updateIndexStats(db, Tables.DATA,
3491                    "data_raw_contact_id", "60000 10");
3492
3493            updateIndexStats(db, Tables.GROUPS,
3494                    "groups_source_id_index", "50 1 1 1");
3495
3496            updateIndexStats(db, Tables.NICKNAME_LOOKUP,
3497                    "sqlite_autoindex_name_lookup_1", "500 2 1");
3498
3499        } catch (SQLException e) {
3500            Log.e(TAG, "Could not update index stats", e);
3501        }
3502    }
3503
3504    /**
3505     * Stores statistics for a given index.
3506     *
3507     * @param stats has the following structure: the first index is the expected size of
3508     * the table.  The following integer(s) are the expected number of records selected with the
3509     * index.  There should be one integer per indexed column.
3510     */
3511    private void updateIndexStats(SQLiteDatabase db, String table, String index,
3512            String stats) {
3513        db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl='" + table + "' AND idx='" + index + "';");
3514        db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat)"
3515                + " VALUES ('" + table + "','" + index + "','" + stats + "');");
3516    }
3517
3518    @Override
3519    public synchronized SQLiteDatabase getWritableDatabase() {
3520        SQLiteDatabase db = super.getWritableDatabase();
3521        if (mReopenDatabase) {
3522            mReopenDatabase = false;
3523            close();
3524            db = super.getWritableDatabase();
3525        }
3526        return db;
3527    }
3528
3529    /**
3530     * Wipes all data except mime type and package lookup tables.
3531     */
3532    public void wipeData() {
3533        SQLiteDatabase db = getWritableDatabase();
3534
3535        db.execSQL("DELETE FROM " + Tables.ACCOUNTS + ";");
3536        db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL, NULL, NULL)");
3537
3538        db.execSQL("DELETE FROM " + Tables.CONTACTS + ";");
3539        db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";");
3540        db.execSQL("DELETE FROM " + Tables.STREAM_ITEMS + ";");
3541        db.execSQL("DELETE FROM " + Tables.STREAM_ITEM_PHOTOS + ";");
3542        db.execSQL("DELETE FROM " + Tables.PHOTO_FILES + ";");
3543        db.execSQL("DELETE FROM " + Tables.DATA + ";");
3544        db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";");
3545        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";");
3546        db.execSQL("DELETE FROM " + Tables.GROUPS + ";");
3547        db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";");
3548        db.execSQL("DELETE FROM " + Tables.SETTINGS + ";");
3549        db.execSQL("DELETE FROM " + Tables.ACTIVITIES + ";");
3550        db.execSQL("DELETE FROM " + Tables.CALLS + ";");
3551        db.execSQL("DELETE FROM " + Tables.DIRECTORIES + ";");
3552        db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + ";");
3553
3554        // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP
3555    }
3556
3557    public NameSplitter createNameSplitter() {
3558        mNameSplitter = new NameSplitter(
3559                mContext.getString(com.android.internal.R.string.common_name_prefixes),
3560                mContext.getString(com.android.internal.R.string.common_last_name_prefixes),
3561                mContext.getString(com.android.internal.R.string.common_name_suffixes),
3562                mContext.getString(com.android.internal.R.string.common_name_conjunctions),
3563                Locale.getDefault());
3564        return mNameSplitter;
3565    }
3566
3567    /**
3568     * Return the {@link ApplicationInfo#uid} for the given package name.
3569     */
3570    public static int getUidForPackageName(PackageManager pm, String packageName) {
3571        try {
3572            ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */);
3573            return clientInfo.uid;
3574        } catch (NameNotFoundException e) {
3575            throw new RuntimeException(e);
3576        }
3577    }
3578
3579    /**
3580     * Perform an internal string-to-integer lookup using the compiled
3581     * {@link SQLiteStatement} provided, using the in-memory cache to speed up
3582     * lookups. If a mapping isn't found in cache or database, it will be
3583     * created. All new, uncached answers are added to the cache automatically.
3584     *
3585     * @param query Compiled statement used to query for the mapping.
3586     * @param insert Compiled statement used to insert a new mapping when no
3587     *            existing one is found in cache or from query.
3588     * @param value Value to find mapping for.
3589     * @param cache In-memory cache of previous answers.
3590     * @return An unique integer mapping for the given value.
3591     */
3592    private long getCachedId(SQLiteStatement query, SQLiteStatement insert,
3593            String value, HashMap<String, Long> cache) {
3594        // Try an in-memory cache lookup
3595        if (cache.containsKey(value)) {
3596            return cache.get(value);
3597        }
3598
3599        synchronized (query) {
3600            long id = -1;
3601            try {
3602                // Try searching database for mapping
3603                DatabaseUtils.bindObjectToProgram(query, 1, value);
3604                id = query.simpleQueryForLong();
3605            } catch (SQLiteDoneException e) {
3606                // Nothing found, so try inserting new mapping
3607                DatabaseUtils.bindObjectToProgram(insert, 1, value);
3608                id = insert.executeInsert();
3609            }
3610            if (id != -1) {
3611                // Cache and return the new answer
3612                cache.put(value, id);
3613                return id;
3614            } else {
3615                // Otherwise throw if no mapping found or created
3616                throw new IllegalStateException("Couldn't find or create internal "
3617                        + "lookup table entry for value " + value);
3618            }
3619        }
3620    }
3621
3622    /**
3623     * Convert a package name into an integer, using {@link Tables#PACKAGES} for
3624     * lookups and possible allocation of new IDs as needed.
3625     */
3626    public long getPackageId(String packageName) {
3627        if (mPackageQuery == null) {
3628            mPackageQuery = getWritableDatabase().compileStatement(
3629                    "SELECT " + PackagesColumns._ID +
3630                    " FROM " + Tables.PACKAGES +
3631                    " WHERE " + PackagesColumns.PACKAGE + "=?");
3632
3633        }
3634        if (mPackageInsert == null) {
3635            mPackageInsert = getWritableDatabase().compileStatement(
3636                    "INSERT INTO " + Tables.PACKAGES + "("
3637                            + PackagesColumns.PACKAGE +
3638                    ") VALUES (?)");
3639        }
3640        return getCachedId(mPackageQuery, mPackageInsert, packageName, mPackageCache);
3641    }
3642
3643    /**
3644     * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for
3645     * lookups and possible allocation of new IDs as needed.
3646     */
3647    public long getMimeTypeId(String mimetype) {
3648        return getCachedId(mMimetypeQuery, mMimetypeInsert, mimetype, mMimetypeCache);
3649    }
3650
3651    public long getMimeTypeIdForStructuredName() {
3652        return mMimeTypeIdStructuredName;
3653    }
3654
3655    public long getMimeTypeIdForOrganization() {
3656        return mMimeTypeIdOrganization;
3657    }
3658
3659    public long getMimeTypeIdForIm() {
3660        return mMimeTypeIdIm;
3661    }
3662
3663    public long getMimeTypeIdForEmail() {
3664        return mMimeTypeIdEmail;
3665    }
3666
3667    public long getMimeTypeIdForSip() {
3668        return mMimeTypeIdSip;
3669    }
3670
3671    public int getDisplayNameSourceForMimeTypeId(int mimeTypeId) {
3672        if (mimeTypeId == mMimeTypeIdStructuredName) {
3673            return DisplayNameSources.STRUCTURED_NAME;
3674        } else if (mimeTypeId == mMimeTypeIdEmail) {
3675            return DisplayNameSources.EMAIL;
3676        } else if (mimeTypeId == mMimeTypeIdPhone) {
3677            return DisplayNameSources.PHONE;
3678        } else if (mimeTypeId == mMimeTypeIdOrganization) {
3679            return DisplayNameSources.ORGANIZATION;
3680        } else if (mimeTypeId == mMimeTypeIdNickname) {
3681            return DisplayNameSources.NICKNAME;
3682        } else {
3683            return DisplayNameSources.UNDEFINED;
3684        }
3685    }
3686
3687    /**
3688     * Find the mimetype for the given {@link Data#_ID}.
3689     */
3690    public String getDataMimeType(long dataId) {
3691        if (mDataMimetypeQuery == null) {
3692            mDataMimetypeQuery = getWritableDatabase().compileStatement(
3693                    "SELECT " + MimetypesColumns.MIMETYPE +
3694                    " FROM " + Tables.DATA_JOIN_MIMETYPES +
3695                    " WHERE " + Tables.DATA + "." + Data._ID + "=?");
3696        }
3697        try {
3698            // Try database query to find mimetype
3699            DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId);
3700            String mimetype = mDataMimetypeQuery.simpleQueryForString();
3701            return mimetype;
3702        } catch (SQLiteDoneException e) {
3703            // No valid mapping found, so return null
3704            return null;
3705        }
3706    }
3707
3708    /**
3709     * Find the mime-type for the given {@link Activities#_ID}.
3710     */
3711    public String getActivityMimeType(long activityId) {
3712        if (mActivitiesMimetypeQuery == null) {
3713            mActivitiesMimetypeQuery = getWritableDatabase().compileStatement(
3714                    "SELECT " + MimetypesColumns.MIMETYPE +
3715                    " FROM " + Tables.ACTIVITIES_JOIN_MIMETYPES +
3716                    " WHERE " + Tables.ACTIVITIES + "." + Activities._ID + "=?");
3717        }
3718        try {
3719            // Try database query to find mimetype
3720            DatabaseUtils.bindObjectToProgram(mActivitiesMimetypeQuery, 1, activityId);
3721            String mimetype = mActivitiesMimetypeQuery.simpleQueryForString();
3722            return mimetype;
3723        } catch (SQLiteDoneException e) {
3724            // No valid mapping found, so return null
3725            return null;
3726        }
3727    }
3728
3729    /**
3730     * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts.
3731     */
3732    public void updateAllVisible() {
3733        updateCustomContactVisibility(getWritableDatabase(), "");
3734    }
3735
3736    /**
3737     * Updates contact visibility and return true iff the visibility was actually changed.
3738     */
3739    public boolean updateContactVisibleOnlyIfChanged(TransactionContext txContext, long contactId) {
3740        return updateContactVisible(txContext, contactId, true);
3741    }
3742
3743    /**
3744     * Update {@link Contacts#IN_VISIBLE_GROUP} and
3745     * {@link Tables#DEFAULT_DIRECTORY} for a specific contact.
3746     */
3747    public void updateContactVisible(TransactionContext txContext, long contactId) {
3748        updateContactVisible(txContext, contactId, false);
3749    }
3750
3751    public boolean updateContactVisible(
3752            TransactionContext txContext, long contactId, boolean onlyIfChanged) {
3753        SQLiteDatabase db = getWritableDatabase();
3754        updateCustomContactVisibility(db, " AND " + Contacts._ID + "=" + contactId);
3755
3756        String contactIdAsString = String.valueOf(contactId);
3757        long mimetype = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3758
3759        // The contact will be included in the default directory if contains
3760        // a raw contact that is in any group or in an account that
3761        // does not have any AUTO_ADD groups.
3762        boolean newVisibility = DatabaseUtils.longForQuery(db,
3763                "SELECT EXISTS (" +
3764                    "SELECT " + RawContacts.CONTACT_ID +
3765                    " FROM " + Tables.RAW_CONTACTS +
3766                    " JOIN " + Tables.DATA +
3767                    "   ON (" + RawContactsColumns.CONCRETE_ID + "="
3768                            + Data.RAW_CONTACT_ID + ")" +
3769                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3770                    "   AND " + DataColumns.MIMETYPE_ID + "=?" +
3771                ") OR EXISTS (" +
3772                    "SELECT " + RawContacts._ID +
3773                    " FROM " + Tables.RAW_CONTACTS +
3774                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3775                    "   AND NOT EXISTS" +
3776                        " (SELECT " + Groups._ID +
3777                        "  FROM " + Tables.GROUPS +
3778                        "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
3779                                + GroupsColumns.CONCRETE_ACCOUNT_NAME +
3780                        "  AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
3781                                + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
3782                        "  AND (" + RawContactsColumns.CONCRETE_DATA_SET + " = "
3783                                + GroupsColumns.CONCRETE_DATA_SET
3784                                + " OR " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL AND "
3785                                + GroupsColumns.CONCRETE_DATA_SET + " IS NULL)" +
3786                        "  AND " + Groups.AUTO_ADD + " != 0" +
3787                        ")" +
3788                ") OR EXISTS (" +
3789                    "SELECT " + RawContacts._ID +
3790                    " FROM " + Tables.RAW_CONTACTS +
3791                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3792                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " +
3793                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL" +
3794                    "   AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL" +
3795                ")",
3796                new String[] {
3797                    contactIdAsString,
3798                    String.valueOf(mimetype),
3799                    contactIdAsString,
3800                    contactIdAsString
3801                }) != 0;
3802
3803        if (onlyIfChanged) {
3804            boolean oldVisibility = isContactInDefaultDirectory(db, contactId);
3805            if (oldVisibility == newVisibility) {
3806                return false;
3807            }
3808        }
3809
3810        if (newVisibility) {
3811            db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " VALUES(?)",
3812                    new String[] { contactIdAsString });
3813            txContext.invalidateSearchIndexForContact(contactId);
3814        } else {
3815            db.execSQL("DELETE FROM " + Tables.DEFAULT_DIRECTORY +
3816                        " WHERE " + Contacts._ID + "=?",
3817                    new String[] { contactIdAsString });
3818            db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX +
3819                        " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
3820                    new String[] { contactIdAsString });
3821        }
3822        return true;
3823    }
3824
3825    public boolean isContactInDefaultDirectory(SQLiteDatabase db, long contactId) {
3826        if (mContactInDefaultDirectoryQuery == null) {
3827            mContactInDefaultDirectoryQuery = db.compileStatement(
3828                    "SELECT EXISTS (" +
3829                            "SELECT 1 FROM " + Tables.DEFAULT_DIRECTORY +
3830                            " WHERE " + Contacts._ID + "=?)");
3831        }
3832        mContactInDefaultDirectoryQuery.bindLong(1, contactId);
3833        return mContactInDefaultDirectoryQuery.simpleQueryForLong() != 0;
3834    }
3835
3836    private void updateCustomContactVisibility(SQLiteDatabase db, String selection) {
3837        final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3838        String[] selectionArgs = new String[]{String.valueOf(groupMembershipMimetypeId)};
3839
3840        // First delete what needs to be deleted, then insert what needs to be added.
3841        // Since flash writes are very expensive, this approach is much better than
3842        // delete-all-insert-all.
3843        db.execSQL("DELETE FROM " + Tables.VISIBLE_CONTACTS +
3844                   " WHERE " + "_id NOT IN" +
3845                        "(SELECT " + Contacts._ID +
3846                        " FROM " + Tables.CONTACTS +
3847                        " WHERE (" + Clauses.CONTACT_IS_VISIBLE + ")=1) " + selection,
3848                selectionArgs);
3849
3850        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
3851                   " SELECT " + Contacts._ID +
3852                   " FROM " + Tables.CONTACTS +
3853                   " WHERE " + Contacts._ID +
3854                   " NOT IN " + Tables.VISIBLE_CONTACTS +
3855                           " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=1 " + selection,
3856                selectionArgs);
3857    }
3858
3859    /**
3860     * Returns contact ID for the given contact or zero if it is NULL.
3861     */
3862    public long getContactId(long rawContactId) {
3863        if (mContactIdQuery == null) {
3864            mContactIdQuery = getWritableDatabase().compileStatement(
3865                    "SELECT " + RawContacts.CONTACT_ID +
3866                    " FROM " + Tables.RAW_CONTACTS +
3867                    " WHERE " + RawContacts._ID + "=?");
3868        }
3869        try {
3870            DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId);
3871            return mContactIdQuery.simpleQueryForLong();
3872        } catch (SQLiteDoneException e) {
3873            // No valid mapping found, so return 0
3874            return 0;
3875        }
3876    }
3877
3878    public int getAggregationMode(long rawContactId) {
3879        if (mAggregationModeQuery == null) {
3880            mAggregationModeQuery = getWritableDatabase().compileStatement(
3881                    "SELECT " + RawContacts.AGGREGATION_MODE +
3882                    " FROM " + Tables.RAW_CONTACTS +
3883                    " WHERE " + RawContacts._ID + "=?");
3884        }
3885        try {
3886            DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId);
3887            return (int)mAggregationModeQuery.simpleQueryForLong();
3888        } catch (SQLiteDoneException e) {
3889            // No valid row found, so return "disabled"
3890            return RawContacts.AGGREGATION_MODE_DISABLED;
3891        }
3892    }
3893
3894    public void buildPhoneLookupAndContactQuery(
3895            SQLiteQueryBuilder qb, String normalizedNumber, String numberE164) {
3896        String minMatch = PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber);
3897        StringBuilder sb = new StringBuilder();
3898        appendPhoneLookupTables(sb, minMatch, true);
3899        qb.setTables(sb.toString());
3900
3901        sb = new StringBuilder();
3902        appendPhoneLookupSelection(sb, normalizedNumber, numberE164);
3903        qb.appendWhere(sb.toString());
3904    }
3905
3906    public String buildPhoneLookupAsNestedQuery(String number) {
3907        StringBuilder sb = new StringBuilder();
3908        final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
3909        sb.append("(SELECT DISTINCT raw_contact_id" + " FROM ");
3910        appendPhoneLookupTables(sb, minMatch, false);
3911        sb.append(" WHERE ");
3912        appendPhoneLookupSelection(sb, number, null);
3913        sb.append(")");
3914        return sb.toString();
3915    }
3916
3917    private void appendPhoneLookupTables(StringBuilder sb, final String minMatch,
3918            boolean joinContacts) {
3919        sb.append(Tables.RAW_CONTACTS);
3920        if (joinContacts) {
3921            sb.append(" JOIN " + Views.CONTACTS + " contacts_view"
3922                    + " ON (contacts_view._id = raw_contacts.contact_id)");
3923        }
3924        sb.append(", (SELECT data_id, normalized_number, length(normalized_number) as len "
3925                + " FROM phone_lookup " + " WHERE (" + Tables.PHONE_LOOKUP + "."
3926                + PhoneLookupColumns.MIN_MATCH + " = '");
3927        sb.append(minMatch);
3928        sb.append("')) AS lookup, " + Tables.DATA);
3929    }
3930
3931    private void appendPhoneLookupSelection(StringBuilder sb, String number, String numberE164) {
3932        sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id");
3933        boolean hasNumberE164 = !TextUtils.isEmpty(numberE164);
3934        boolean hasNumber = !TextUtils.isEmpty(number);
3935        if (hasNumberE164 || hasNumber) {
3936            sb.append(" AND ( ");
3937            if (hasNumberE164) {
3938                sb.append(" lookup.normalized_number = ");
3939                DatabaseUtils.appendEscapedSQLString(sb, numberE164);
3940            }
3941            if (hasNumberE164 && hasNumber) {
3942                sb.append(" OR ");
3943            }
3944            if (hasNumber) {
3945                int numberLen = number.length();
3946                sb.append(" lookup.len <= ");
3947                sb.append(numberLen);
3948                sb.append(" AND substr(");
3949                DatabaseUtils.appendEscapedSQLString(sb, number);
3950                sb.append(',');
3951                sb.append(numberLen);
3952                sb.append(" - lookup.len + 1) = lookup.normalized_number");
3953            }
3954            sb.append(')');
3955        }
3956    }
3957
3958    public String getUseStrictPhoneNumberComparisonParameter() {
3959        return mUseStrictPhoneNumberComparison ? "1" : "0";
3960    }
3961
3962    /**
3963     * Loads common nickname mappings into the database.
3964     */
3965    private void loadNicknameLookupTable(SQLiteDatabase db) {
3966        db.execSQL("DELETE FROM " + Tables.NICKNAME_LOOKUP);
3967
3968        String[] strings = mContext.getResources().getStringArray(
3969                com.android.internal.R.array.common_nicknames);
3970        if (strings == null || strings.length == 0) {
3971            return;
3972        }
3973
3974        SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO "
3975                + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + ","
3976                + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)");
3977
3978        try {
3979            for (int clusterId = 0; clusterId < strings.length; clusterId++) {
3980                String[] names = strings[clusterId].split(",");
3981                for (int j = 0; j < names.length; j++) {
3982                    String name = NameNormalizer.normalize(names[j]);
3983                    try {
3984                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name);
3985                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2,
3986                                String.valueOf(clusterId));
3987                        nicknameLookupInsert.executeInsert();
3988                    } catch (SQLiteException e) {
3989
3990                        // Print the exception and keep going - this is not a fatal error
3991                        Log.e(TAG, "Cannot insert nickname: " + names[j], e);
3992                    }
3993                }
3994            }
3995        } finally {
3996            nicknameLookupInsert.close();
3997        }
3998    }
3999
4000    public static void copyStringValue(ContentValues toValues, String toKey,
4001            ContentValues fromValues, String fromKey) {
4002        if (fromValues.containsKey(fromKey)) {
4003            toValues.put(toKey, fromValues.getAsString(fromKey));
4004        }
4005    }
4006
4007    public static void copyLongValue(ContentValues toValues, String toKey,
4008            ContentValues fromValues, String fromKey) {
4009        if (fromValues.containsKey(fromKey)) {
4010            long longValue;
4011            Object value = fromValues.get(fromKey);
4012            if (value instanceof Boolean) {
4013                if ((Boolean)value) {
4014                    longValue = 1;
4015                } else {
4016                    longValue = 0;
4017                }
4018            } else if (value instanceof String) {
4019                longValue = Long.parseLong((String)value);
4020            } else {
4021                longValue = ((Number)value).longValue();
4022            }
4023            toValues.put(toKey, longValue);
4024        }
4025    }
4026
4027    public SyncStateContentProviderHelper getSyncState() {
4028        return mSyncState;
4029    }
4030
4031    /**
4032     * Delete the aggregate contact if it has no constituent raw contacts other
4033     * than the supplied one.
4034     */
4035    public void removeContactIfSingleton(long rawContactId) {
4036        SQLiteDatabase db = getWritableDatabase();
4037
4038        // Obtain contact ID from the supplied raw contact ID
4039        String contactIdFromRawContactId = "(SELECT " + RawContacts.CONTACT_ID + " FROM "
4040                + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=" + rawContactId + ")";
4041
4042        // Find other raw contacts in the same aggregate contact
4043        String otherRawContacts = "(SELECT contacts1." + RawContacts._ID + " FROM "
4044                + Tables.RAW_CONTACTS + " contacts1 JOIN " + Tables.RAW_CONTACTS + " contacts2 ON ("
4045                + "contacts1." + RawContacts.CONTACT_ID + "=contacts2." + RawContacts.CONTACT_ID
4046                + ") WHERE contacts1." + RawContacts._ID + "!=" + rawContactId + ""
4047                + " AND contacts2." + RawContacts._ID + "=" + rawContactId + ")";
4048
4049        db.execSQL("DELETE FROM " + Tables.CONTACTS
4050                + " WHERE " + Contacts._ID + "=" + contactIdFromRawContactId
4051                + " AND NOT EXISTS " + otherRawContacts + ";");
4052    }
4053
4054    /**
4055     * Returns the value from the {@link Tables#PROPERTIES} table.
4056     */
4057    public String getProperty(String key, String defaultValue) {
4058        Cursor cursor = getReadableDatabase().query(Tables.PROPERTIES,
4059                new String[]{PropertiesColumns.PROPERTY_VALUE},
4060                PropertiesColumns.PROPERTY_KEY + "=?",
4061                new String[]{key}, null, null, null);
4062        String value = null;
4063        try {
4064            if (cursor.moveToFirst()) {
4065                value = cursor.getString(0);
4066            }
4067        } finally {
4068            cursor.close();
4069        }
4070
4071        return value != null ? value : defaultValue;
4072    }
4073
4074    /**
4075     * Stores a key-value pair in the {@link Tables#PROPERTIES} table.
4076     */
4077    public void setProperty(String key, String value) {
4078        setProperty(getWritableDatabase(), key, value);
4079    }
4080
4081    private void setProperty(SQLiteDatabase db, String key, String value) {
4082        ContentValues values = new ContentValues();
4083        values.put(PropertiesColumns.PROPERTY_KEY, key);
4084        values.put(PropertiesColumns.PROPERTY_VALUE, value);
4085        db.replace(Tables.PROPERTIES, null, values);
4086    }
4087
4088    /**
4089     * Test if any of the columns appear in the given projection.
4090     */
4091    public boolean isInProjection(String[] projection, String... columns) {
4092        if (projection == null) {
4093            return true;
4094        }
4095
4096        // Optimized for a single-column test
4097        if (columns.length == 1) {
4098            String column = columns[0];
4099            for (String test : projection) {
4100                if (column.equals(test)) {
4101                    return true;
4102                }
4103            }
4104        } else {
4105            for (String test : projection) {
4106                for (String column : columns) {
4107                    if (column.equals(test)) {
4108                        return true;
4109                    }
4110                }
4111            }
4112        }
4113        return false;
4114    }
4115
4116    /**
4117     * Returns a detailed exception message for the supplied URI.  It includes the calling
4118     * user and calling package(s).
4119     */
4120    public String exceptionMessage(Uri uri) {
4121        return exceptionMessage(null, uri);
4122    }
4123
4124    /**
4125     * Returns a detailed exception message for the supplied URI.  It includes the calling
4126     * user and calling package(s).
4127     */
4128    public String exceptionMessage(String message, Uri uri) {
4129        StringBuilder sb = new StringBuilder();
4130        if (message != null) {
4131            sb.append(message).append("; ");
4132        }
4133        sb.append("URI: ").append(uri);
4134        final PackageManager pm = mContext.getPackageManager();
4135        int callingUid = Binder.getCallingUid();
4136        sb.append(", calling user: ");
4137        String userName = pm.getNameForUid(callingUid);
4138        if (userName != null) {
4139            sb.append(userName);
4140        } else {
4141            sb.append(callingUid);
4142        }
4143
4144        final String[] callerPackages = pm.getPackagesForUid(callingUid);
4145        if (callerPackages != null && callerPackages.length > 0) {
4146            if (callerPackages.length == 1) {
4147                sb.append(", calling package:");
4148                sb.append(callerPackages[0]);
4149            } else {
4150                sb.append(", calling package is one of: [");
4151                for (int i = 0; i < callerPackages.length; i++) {
4152                    if (i != 0) {
4153                        sb.append(", ");
4154                    }
4155                    sb.append(callerPackages[i]);
4156                }
4157                sb.append("]");
4158            }
4159        }
4160
4161        return sb.toString();
4162    }
4163
4164    protected String getCountryIso() {
4165        CountryDetector detector =
4166            (CountryDetector) mContext.getSystemService(Context.COUNTRY_DETECTOR);
4167        return detector.detectCountry().getCountryIso();
4168    }
4169
4170    public void deleteStatusUpdate(long dataId) {
4171        if (mStatusUpdateDelete == null) {
4172            mStatusUpdateDelete = getWritableDatabase().compileStatement(
4173                    "DELETE FROM " + Tables.STATUS_UPDATES +
4174                    " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
4175        }
4176        mStatusUpdateDelete.bindLong(1, dataId);
4177        mStatusUpdateDelete.execute();
4178    }
4179
4180    public void replaceStatusUpdate(Long dataId, long timestamp, String status, String resPackage,
4181            Integer iconResource, Integer labelResource) {
4182        if (mStatusUpdateReplace == null) {
4183            mStatusUpdateReplace = getWritableDatabase().compileStatement(
4184                    "INSERT OR REPLACE INTO " + Tables.STATUS_UPDATES + "("
4185                            + StatusUpdatesColumns.DATA_ID + ", "
4186                            + StatusUpdates.STATUS_TIMESTAMP + ","
4187                            + StatusUpdates.STATUS + ","
4188                            + StatusUpdates.STATUS_RES_PACKAGE + ","
4189                            + StatusUpdates.STATUS_ICON + ","
4190                            + StatusUpdates.STATUS_LABEL + ")" +
4191                    " VALUES (?,?,?,?,?,?)");
4192        }
4193        mStatusUpdateReplace.bindLong(1, dataId);
4194        mStatusUpdateReplace.bindLong(2, timestamp);
4195        bindString(mStatusUpdateReplace, 3, status);
4196        bindString(mStatusUpdateReplace, 4, resPackage);
4197        bindLong(mStatusUpdateReplace, 5, iconResource);
4198        bindLong(mStatusUpdateReplace, 6, labelResource);
4199        mStatusUpdateReplace.execute();
4200    }
4201
4202    public void insertStatusUpdate(Long dataId, String status, String resPackage,
4203            Integer iconResource, Integer labelResource) {
4204        if (mStatusUpdateInsert == null) {
4205            mStatusUpdateInsert = getWritableDatabase().compileStatement(
4206                    "INSERT INTO " + Tables.STATUS_UPDATES + "("
4207                            + StatusUpdatesColumns.DATA_ID + ", "
4208                            + StatusUpdates.STATUS + ","
4209                            + StatusUpdates.STATUS_RES_PACKAGE + ","
4210                            + StatusUpdates.STATUS_ICON + ","
4211                            + StatusUpdates.STATUS_LABEL + ")" +
4212                    " VALUES (?,?,?,?,?)");
4213        }
4214        try {
4215            mStatusUpdateInsert.bindLong(1, dataId);
4216            bindString(mStatusUpdateInsert, 2, status);
4217            bindString(mStatusUpdateInsert, 3, resPackage);
4218            bindLong(mStatusUpdateInsert, 4, iconResource);
4219            bindLong(mStatusUpdateInsert, 5, labelResource);
4220            mStatusUpdateInsert.executeInsert();
4221        } catch (SQLiteConstraintException e) {
4222            // The row already exists - update it
4223            if (mStatusUpdateAutoTimestamp == null) {
4224                mStatusUpdateAutoTimestamp = getWritableDatabase().compileStatement(
4225                        "UPDATE " + Tables.STATUS_UPDATES +
4226                        " SET " + StatusUpdates.STATUS_TIMESTAMP + "=?,"
4227                                + StatusUpdates.STATUS + "=?" +
4228                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"
4229                                + " AND " + StatusUpdates.STATUS + "!=?");
4230            }
4231
4232            long timestamp = System.currentTimeMillis();
4233            mStatusUpdateAutoTimestamp.bindLong(1, timestamp);
4234            bindString(mStatusUpdateAutoTimestamp, 2, status);
4235            mStatusUpdateAutoTimestamp.bindLong(3, dataId);
4236            bindString(mStatusUpdateAutoTimestamp, 4, status);
4237            mStatusUpdateAutoTimestamp.execute();
4238
4239            if (mStatusAttributionUpdate == null) {
4240                mStatusAttributionUpdate = getWritableDatabase().compileStatement(
4241                        "UPDATE " + Tables.STATUS_UPDATES +
4242                        " SET " + StatusUpdates.STATUS_RES_PACKAGE + "=?,"
4243                                + StatusUpdates.STATUS_ICON + "=?,"
4244                                + StatusUpdates.STATUS_LABEL + "=?" +
4245                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
4246            }
4247            bindString(mStatusAttributionUpdate, 1, resPackage);
4248            bindLong(mStatusAttributionUpdate, 2, iconResource);
4249            bindLong(mStatusAttributionUpdate, 3, labelResource);
4250            mStatusAttributionUpdate.bindLong(4, dataId);
4251            mStatusAttributionUpdate.execute();
4252        }
4253    }
4254
4255    /**
4256     * Resets the {@link RawContacts#NAME_VERIFIED} flag to 0 on all other raw
4257     * contacts in the same aggregate
4258     */
4259    public void resetNameVerifiedForOtherRawContacts(long rawContactId) {
4260        if (mResetNameVerifiedForOtherRawContacts == null) {
4261            mResetNameVerifiedForOtherRawContacts = getWritableDatabase().compileStatement(
4262                    "UPDATE " + Tables.RAW_CONTACTS +
4263                    " SET " + RawContacts.NAME_VERIFIED + "=0" +
4264                    " WHERE " + RawContacts.CONTACT_ID + "=(" +
4265                            "SELECT " + RawContacts.CONTACT_ID +
4266                            " FROM " + Tables.RAW_CONTACTS +
4267                            " WHERE " + RawContacts._ID + "=?)" +
4268                    " AND " + RawContacts._ID + "!=?");
4269        }
4270        mResetNameVerifiedForOtherRawContacts.bindLong(1, rawContactId);
4271        mResetNameVerifiedForOtherRawContacts.bindLong(2, rawContactId);
4272        mResetNameVerifiedForOtherRawContacts.execute();
4273    }
4274
4275    private interface RawContactNameQuery {
4276        public static final String RAW_SQL =
4277                "SELECT "
4278                        + DataColumns.MIMETYPE_ID + ","
4279                        + Data.IS_PRIMARY + ","
4280                        + Data.DATA1 + ","
4281                        + Data.DATA2 + ","
4282                        + Data.DATA3 + ","
4283                        + Data.DATA4 + ","
4284                        + Data.DATA5 + ","
4285                        + Data.DATA6 + ","
4286                        + Data.DATA7 + ","
4287                        + Data.DATA8 + ","
4288                        + Data.DATA9 + ","
4289                        + Data.DATA10 + ","
4290                        + Data.DATA11 +
4291                " FROM " + Tables.DATA +
4292                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
4293                        " AND (" + Data.DATA1 + " NOT NULL OR " +
4294                                Organization.TITLE + " NOT NULL)";
4295
4296        public static final int MIMETYPE = 0;
4297        public static final int IS_PRIMARY = 1;
4298        public static final int DATA1 = 2;
4299        public static final int GIVEN_NAME = 3;                         // data2
4300        public static final int FAMILY_NAME = 4;                        // data3
4301        public static final int PREFIX = 5;                             // data4
4302        public static final int TITLE = 5;                              // data4
4303        public static final int MIDDLE_NAME = 6;                        // data5
4304        public static final int SUFFIX = 7;                             // data6
4305        public static final int PHONETIC_GIVEN_NAME = 8;                // data7
4306        public static final int PHONETIC_MIDDLE_NAME = 9;               // data8
4307        public static final int ORGANIZATION_PHONETIC_NAME = 9;         // data8
4308        public static final int PHONETIC_FAMILY_NAME = 10;              // data9
4309        public static final int FULL_NAME_STYLE = 11;                   // data10
4310        public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11;  // data10
4311        public static final int PHONETIC_NAME_STYLE = 12;               // data11
4312    }
4313
4314    /**
4315     * Updates a raw contact display name based on data rows, e.g. structured name,
4316     * organization, email etc.
4317     */
4318    public void updateRawContactDisplayName(SQLiteDatabase db, long rawContactId) {
4319        if (mNameSplitter == null) {
4320            createNameSplitter();
4321        }
4322
4323        int bestDisplayNameSource = DisplayNameSources.UNDEFINED;
4324        NameSplitter.Name bestName = null;
4325        String bestDisplayName = null;
4326        String bestPhoneticName = null;
4327        int bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4328
4329        mSelectionArgs1[0] = String.valueOf(rawContactId);
4330        Cursor c = db.rawQuery(RawContactNameQuery.RAW_SQL, mSelectionArgs1);
4331        try {
4332            while (c.moveToNext()) {
4333                int mimeType = c.getInt(RawContactNameQuery.MIMETYPE);
4334                int source = getDisplayNameSourceForMimeTypeId(mimeType);
4335                if (source < bestDisplayNameSource || source == DisplayNameSources.UNDEFINED) {
4336                    continue;
4337                }
4338
4339                if (source == bestDisplayNameSource
4340                        && c.getInt(RawContactNameQuery.IS_PRIMARY) == 0) {
4341                    continue;
4342                }
4343
4344                if (mimeType == getMimeTypeIdForStructuredName()) {
4345                    NameSplitter.Name name;
4346                    if (bestName != null) {
4347                        name = new NameSplitter.Name();
4348                    } else {
4349                        name = mName;
4350                        name.clear();
4351                    }
4352                    name.prefix = c.getString(RawContactNameQuery.PREFIX);
4353                    name.givenNames = c.getString(RawContactNameQuery.GIVEN_NAME);
4354                    name.middleName = c.getString(RawContactNameQuery.MIDDLE_NAME);
4355                    name.familyName = c.getString(RawContactNameQuery.FAMILY_NAME);
4356                    name.suffix = c.getString(RawContactNameQuery.SUFFIX);
4357                    name.fullNameStyle = c.isNull(RawContactNameQuery.FULL_NAME_STYLE)
4358                            ? FullNameStyle.UNDEFINED
4359                            : c.getInt(RawContactNameQuery.FULL_NAME_STYLE);
4360                    name.phoneticFamilyName = c.getString(RawContactNameQuery.PHONETIC_FAMILY_NAME);
4361                    name.phoneticMiddleName = c.getString(RawContactNameQuery.PHONETIC_MIDDLE_NAME);
4362                    name.phoneticGivenName = c.getString(RawContactNameQuery.PHONETIC_GIVEN_NAME);
4363                    name.phoneticNameStyle = c.isNull(RawContactNameQuery.PHONETIC_NAME_STYLE)
4364                            ? PhoneticNameStyle.UNDEFINED
4365                            : c.getInt(RawContactNameQuery.PHONETIC_NAME_STYLE);
4366                    if (!name.isEmpty()) {
4367                        bestDisplayNameSource = source;
4368                        bestName = name;
4369                    }
4370                } else if (mimeType == getMimeTypeIdForOrganization()) {
4371                    mCharArrayBuffer.sizeCopied = 0;
4372                    c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer);
4373                    if (mCharArrayBuffer.sizeCopied != 0) {
4374                        bestDisplayNameSource = source;
4375                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
4376                                mCharArrayBuffer.sizeCopied);
4377                        bestPhoneticName = c.getString(
4378                                RawContactNameQuery.ORGANIZATION_PHONETIC_NAME);
4379                        bestPhoneticNameStyle =
4380                                c.isNull(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE)
4381                                   ? PhoneticNameStyle.UNDEFINED
4382                                   : c.getInt(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE);
4383                    } else {
4384                        c.copyStringToBuffer(RawContactNameQuery.TITLE, mCharArrayBuffer);
4385                        if (mCharArrayBuffer.sizeCopied != 0) {
4386                            bestDisplayNameSource = source;
4387                            bestDisplayName = new String(mCharArrayBuffer.data, 0,
4388                                    mCharArrayBuffer.sizeCopied);
4389                            bestPhoneticName = null;
4390                            bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4391                        }
4392                    }
4393                } else {
4394                    // Display name is at DATA1 in all other types.
4395                    // This is ensured in the constructor.
4396
4397                    mCharArrayBuffer.sizeCopied = 0;
4398                    c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer);
4399                    if (mCharArrayBuffer.sizeCopied != 0) {
4400                        bestDisplayNameSource = source;
4401                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
4402                                mCharArrayBuffer.sizeCopied);
4403                        bestPhoneticName = null;
4404                        bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4405                    }
4406                }
4407            }
4408
4409        } finally {
4410            c.close();
4411        }
4412
4413        String displayNamePrimary;
4414        String displayNameAlternative;
4415        String sortNamePrimary;
4416        String sortNameAlternative;
4417        String sortKeyPrimary = null;
4418        String sortKeyAlternative = null;
4419        int displayNameStyle = FullNameStyle.UNDEFINED;
4420
4421        if (bestDisplayNameSource == DisplayNameSources.STRUCTURED_NAME) {
4422            displayNameStyle = bestName.fullNameStyle;
4423            if (displayNameStyle == FullNameStyle.CJK
4424                    || displayNameStyle == FullNameStyle.UNDEFINED) {
4425                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
4426                bestName.fullNameStyle = displayNameStyle;
4427            }
4428
4429            displayNamePrimary = mNameSplitter.join(bestName, true, true);
4430            displayNameAlternative = mNameSplitter.join(bestName, false, true);
4431
4432            if (TextUtils.isEmpty(bestName.prefix)) {
4433                sortNamePrimary = displayNamePrimary;
4434                sortNameAlternative = displayNameAlternative;
4435            } else {
4436                sortNamePrimary = mNameSplitter.join(bestName, true, false);
4437                sortNameAlternative = mNameSplitter.join(bestName, false, false);
4438            }
4439
4440            bestPhoneticName = mNameSplitter.joinPhoneticName(bestName);
4441            bestPhoneticNameStyle = bestName.phoneticNameStyle;
4442        } else {
4443            displayNamePrimary = displayNameAlternative = bestDisplayName;
4444            sortNamePrimary = sortNameAlternative = bestDisplayName;
4445        }
4446
4447        if (bestPhoneticName != null) {
4448            sortKeyPrimary = sortKeyAlternative = bestPhoneticName;
4449            if (bestPhoneticNameStyle == PhoneticNameStyle.UNDEFINED) {
4450                bestPhoneticNameStyle = mNameSplitter.guessPhoneticNameStyle(bestPhoneticName);
4451            }
4452        } else {
4453            if (displayNameStyle == FullNameStyle.UNDEFINED) {
4454                displayNameStyle = mNameSplitter.guessFullNameStyle(bestDisplayName);
4455                if (displayNameStyle == FullNameStyle.UNDEFINED
4456                        || displayNameStyle == FullNameStyle.CJK) {
4457                    displayNameStyle = mNameSplitter.getAdjustedNameStyleBasedOnPhoneticNameStyle(
4458                            displayNameStyle, bestPhoneticNameStyle);
4459                }
4460                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
4461            }
4462            if (displayNameStyle == FullNameStyle.CHINESE ||
4463                    displayNameStyle == FullNameStyle.CJK) {
4464                sortKeyPrimary = sortKeyAlternative =
4465                        ContactLocaleUtils.getIntance().getSortKey(
4466                                sortNamePrimary, displayNameStyle);
4467            }
4468        }
4469
4470        if (sortKeyPrimary == null) {
4471            sortKeyPrimary = sortNamePrimary;
4472            sortKeyAlternative = sortNameAlternative;
4473        }
4474
4475        if (mRawContactDisplayNameUpdate == null) {
4476            mRawContactDisplayNameUpdate = db.compileStatement(
4477                    "UPDATE " + Tables.RAW_CONTACTS +
4478                    " SET " +
4479                            RawContacts.DISPLAY_NAME_SOURCE + "=?," +
4480                            RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
4481                            RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
4482                            RawContacts.PHONETIC_NAME + "=?," +
4483                            RawContacts.PHONETIC_NAME_STYLE + "=?," +
4484                            RawContacts.SORT_KEY_PRIMARY + "=?," +
4485                            RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
4486                    " WHERE " + RawContacts._ID + "=?");
4487        }
4488
4489        mRawContactDisplayNameUpdate.bindLong(1, bestDisplayNameSource);
4490        bindString(mRawContactDisplayNameUpdate, 2, displayNamePrimary);
4491        bindString(mRawContactDisplayNameUpdate, 3, displayNameAlternative);
4492        bindString(mRawContactDisplayNameUpdate, 4, bestPhoneticName);
4493        mRawContactDisplayNameUpdate.bindLong(5, bestPhoneticNameStyle);
4494        bindString(mRawContactDisplayNameUpdate, 6, sortKeyPrimary);
4495        bindString(mRawContactDisplayNameUpdate, 7, sortKeyAlternative);
4496        mRawContactDisplayNameUpdate.bindLong(8, rawContactId);
4497        mRawContactDisplayNameUpdate.execute();
4498    }
4499
4500    /*
4501     * Sets the given dataId record in the "data" table to primary, and resets all data records of
4502     * the same mimetype and under the same contact to not be primary.
4503     *
4504     * @param dataId the id of the data record to be set to primary. Pass -1 to clear the primary
4505     * flag of all data items of this raw contacts
4506     */
4507    public void setIsPrimary(long rawContactId, long dataId, long mimeTypeId) {
4508        if (mSetPrimaryStatement == null) {
4509            mSetPrimaryStatement = getWritableDatabase().compileStatement(
4510                    "UPDATE " + Tables.DATA +
4511                    " SET " + Data.IS_PRIMARY + "=(_id=?)" +
4512                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4513                    "   AND " + Data.RAW_CONTACT_ID + "=?");
4514        }
4515        mSetPrimaryStatement.bindLong(1, dataId);
4516        mSetPrimaryStatement.bindLong(2, mimeTypeId);
4517        mSetPrimaryStatement.bindLong(3, rawContactId);
4518        mSetPrimaryStatement.execute();
4519    }
4520
4521    /*
4522     * Clears the super primary of all data items of the given raw contact. does not touch
4523     * other raw contacts of the same joined aggregate
4524     */
4525    public void clearSuperPrimary(long rawContactId, long mimeTypeId) {
4526        if (mClearSuperPrimaryStatement == null) {
4527            mClearSuperPrimaryStatement = getWritableDatabase().compileStatement(
4528                    "UPDATE " + Tables.DATA +
4529                    " SET " + Data.IS_SUPER_PRIMARY + "=0" +
4530                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4531                    "   AND " + Data.RAW_CONTACT_ID + "=?");
4532        }
4533        mClearSuperPrimaryStatement.bindLong(1, mimeTypeId);
4534        mClearSuperPrimaryStatement.bindLong(2, rawContactId);
4535        mClearSuperPrimaryStatement.execute();
4536    }
4537
4538    /*
4539     * Sets the given dataId record in the "data" table to "super primary", and resets all data
4540     * records of the same mimetype and under the same aggregate to not be "super primary".
4541     *
4542     * @param dataId the id of the data record to be set to primary.
4543     */
4544    public void setIsSuperPrimary(long rawContactId, long dataId, long mimeTypeId) {
4545        if (mSetSuperPrimaryStatement == null) {
4546            mSetSuperPrimaryStatement = getWritableDatabase().compileStatement(
4547                    "UPDATE " + Tables.DATA +
4548                    " SET " + Data.IS_SUPER_PRIMARY + "=(" + Data._ID + "=?)" +
4549                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4550                    "   AND " + Data.RAW_CONTACT_ID + " IN (" +
4551                            "SELECT " + RawContacts._ID +
4552                            " FROM " + Tables.RAW_CONTACTS +
4553                            " WHERE " + RawContacts.CONTACT_ID + " =(" +
4554                                    "SELECT " + RawContacts.CONTACT_ID +
4555                                    " FROM " + Tables.RAW_CONTACTS +
4556                                    " WHERE " + RawContacts._ID + "=?))");
4557        }
4558        mSetSuperPrimaryStatement.bindLong(1, dataId);
4559        mSetSuperPrimaryStatement.bindLong(2, mimeTypeId);
4560        mSetSuperPrimaryStatement.bindLong(3, rawContactId);
4561        mSetSuperPrimaryStatement.execute();
4562    }
4563
4564    /**
4565     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
4566     */
4567    public void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) {
4568        if (TextUtils.isEmpty(name)) {
4569            return;
4570        }
4571
4572        if (mNameLookupInsert == null) {
4573            mNameLookupInsert = getWritableDatabase().compileStatement(
4574                    "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
4575                            + NameLookupColumns.RAW_CONTACT_ID + ","
4576                            + NameLookupColumns.DATA_ID + ","
4577                            + NameLookupColumns.NAME_TYPE + ","
4578                            + NameLookupColumns.NORMALIZED_NAME
4579                    + ") VALUES (?,?,?,?)");
4580        }
4581        mNameLookupInsert.bindLong(1, rawContactId);
4582        mNameLookupInsert.bindLong(2, dataId);
4583        mNameLookupInsert.bindLong(3, lookupType);
4584        bindString(mNameLookupInsert, 4, name);
4585        mNameLookupInsert.executeInsert();
4586    }
4587
4588    /**
4589     * Deletes all {@link Tables#NAME_LOOKUP} table rows associated with the specified data element.
4590     */
4591    public void deleteNameLookup(long dataId) {
4592        if (mNameLookupDelete == null) {
4593            mNameLookupDelete = getWritableDatabase().compileStatement(
4594                    "DELETE FROM " + Tables.NAME_LOOKUP +
4595                    " WHERE " + NameLookupColumns.DATA_ID + "=?");
4596        }
4597        mNameLookupDelete.bindLong(1, dataId);
4598        mNameLookupDelete.execute();
4599    }
4600
4601    public String insertNameLookupForEmail(long rawContactId, long dataId, String email) {
4602        if (TextUtils.isEmpty(email)) {
4603            return null;
4604        }
4605
4606        String address = extractHandleFromEmailAddress(email);
4607        if (address == null) {
4608            return null;
4609        }
4610
4611        insertNameLookup(rawContactId, dataId,
4612                NameLookupType.EMAIL_BASED_NICKNAME, NameNormalizer.normalize(address));
4613        return address;
4614    }
4615
4616    /**
4617     * Normalizes the nickname and inserts it in the name lookup table.
4618     */
4619    public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) {
4620        if (TextUtils.isEmpty(nickname)) {
4621            return;
4622        }
4623
4624        insertNameLookup(rawContactId, dataId,
4625                NameLookupType.NICKNAME, NameNormalizer.normalize(nickname));
4626    }
4627
4628    public void insertNameLookupForPhoneticName(long rawContactId, long dataId, String familyName,
4629            String middleName, String givenName) {
4630        mSb.setLength(0);
4631        if (familyName != null) {
4632            mSb.append(familyName.trim());
4633        }
4634        if (middleName != null) {
4635            mSb.append(middleName.trim());
4636        }
4637        if (givenName != null) {
4638            mSb.append(givenName.trim());
4639        }
4640
4641        if (mSb.length() > 0) {
4642            insertNameLookup(rawContactId, dataId, NameLookupType.NAME_COLLATION_KEY,
4643                    NameNormalizer.normalize(mSb.toString()));
4644        }
4645    }
4646
4647    /**
4648     * Performs a query and returns true if any Data item of the raw contact with the given
4649     * id and mimetype is marked as super-primary
4650     */
4651    public boolean rawContactHasSuperPrimary(long rawContactId, long mimeTypeId) {
4652        final Cursor existsCursor = getReadableDatabase().rawQuery(
4653                "SELECT EXISTS(SELECT 1 FROM " + Tables.DATA +
4654                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
4655                " AND " + DataColumns.MIMETYPE_ID + "=?" +
4656                " AND " + Data.IS_SUPER_PRIMARY + "<>0)",
4657                new String[] { String.valueOf(rawContactId), String.valueOf(mimeTypeId) });
4658        try {
4659            if (!existsCursor.moveToFirst()) throw new IllegalStateException();
4660            return existsCursor.getInt(0) != 0;
4661        } finally {
4662            existsCursor.close();
4663        }
4664    }
4665
4666    public String getCurrentCountryIso() {
4667        return mCountryMonitor.getCountryIso();
4668    }
4669
4670    /* package */ String querySearchIndexContentForTest(long contactId) {
4671        return DatabaseUtils.stringForQuery(getReadableDatabase(),
4672                "SELECT " + SearchIndexColumns.CONTENT +
4673                " FROM " + Tables.SEARCH_INDEX +
4674                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
4675                new String[] { String.valueOf(contactId) });
4676    }
4677
4678    /* package */ String querySearchIndexTokensForTest(long contactId) {
4679        return DatabaseUtils.stringForQuery(getReadableDatabase(),
4680                "SELECT " + SearchIndexColumns.TOKENS +
4681                " FROM " + Tables.SEARCH_INDEX +
4682                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
4683                new String[] { String.valueOf(contactId) });
4684    }
4685}
4686