ContactsDatabaseHelper.java revision 9b002837367674b7403769f52dc50ab4dbecef71
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            setProperty(db, SearchIndexManager.PROPERTY_SEARCH_INDEX_VERSION, "0");
2236        }
2237
2238        if (oldVersion != newVersion) {
2239            throw new IllegalStateException(
2240                    "error upgrading the database to version " + newVersion);
2241        }
2242    }
2243
2244    private void upgradeToVersion202(SQLiteDatabase db) {
2245        db.execSQL(
2246                "ALTER TABLE " + Tables.PHONE_LOOKUP +
2247                " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;");
2248
2249        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
2250                PhoneLookupColumns.MIN_MATCH + "," +
2251                PhoneLookupColumns.RAW_CONTACT_ID + "," +
2252                PhoneLookupColumns.DATA_ID +
2253        ");");
2254
2255        updateIndexStats(db, Tables.PHONE_LOOKUP,
2256                "phone_lookup_min_match_index", "10000 2 2 1");
2257
2258        SQLiteStatement update = db.compileStatement(
2259                "UPDATE " + Tables.PHONE_LOOKUP +
2260                " SET " + PhoneLookupColumns.MIN_MATCH + "=?" +
2261                " WHERE " + PhoneLookupColumns.DATA_ID + "=?");
2262
2263        // Populate the new column
2264        Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA +
2265                " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")",
2266                new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null);
2267        try {
2268            while (c.moveToNext()) {
2269                long dataId = c.getLong(0);
2270                String number = c.getString(1);
2271                if (!TextUtils.isEmpty(number)) {
2272                    update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number));
2273                    update.bindLong(2, dataId);
2274                    update.execute();
2275                }
2276            }
2277        } finally {
2278            c.close();
2279        }
2280    }
2281
2282    private void upgradeToVersion203(SQLiteDatabase db) {
2283        // Garbage-collect first. A bug in Eclair was sometimes leaving
2284        // raw_contacts in the database that no longer had contacts associated
2285        // with them.  To avoid failures during this database upgrade, drop
2286        // the orphaned raw_contacts.
2287        db.execSQL(
2288                "DELETE FROM raw_contacts" +
2289                " WHERE contact_id NOT NULL" +
2290                " AND contact_id NOT IN (SELECT _id FROM contacts)");
2291
2292        db.execSQL(
2293                "ALTER TABLE " + Tables.CONTACTS +
2294                " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)");
2295        db.execSQL(
2296                "ALTER TABLE " + Tables.RAW_CONTACTS +
2297                " ADD contact_in_visible_group INTEGER NOT NULL DEFAULT 0");
2298
2299        // For each Contact, find the RawContact that contributed the display name
2300        db.execSQL(
2301                "UPDATE " + Tables.CONTACTS +
2302                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
2303                        " SELECT " + RawContacts._ID +
2304                        " FROM " + Tables.RAW_CONTACTS +
2305                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
2306                        " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" +
2307                                Tables.CONTACTS + "." + Contacts.DISPLAY_NAME +
2308                        " ORDER BY " + RawContacts._ID +
2309                        " LIMIT 1)"
2310        );
2311
2312        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
2313                Contacts.NAME_RAW_CONTACT_ID +
2314        ");");
2315
2316        // If for some unknown reason we missed some names, let's make sure there are
2317        // no contacts without a name, picking a raw contact "at random".
2318        db.execSQL(
2319                "UPDATE " + Tables.CONTACTS +
2320                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
2321                        " SELECT " + RawContacts._ID +
2322                        " FROM " + Tables.RAW_CONTACTS +
2323                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
2324                        " ORDER BY " + RawContacts._ID +
2325                        " LIMIT 1)" +
2326                " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL"
2327        );
2328
2329        // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use.
2330        db.execSQL(
2331                "UPDATE " + Tables.CONTACTS +
2332                " SET " + Contacts.DISPLAY_NAME + "=NULL"
2333        );
2334
2335        // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow
2336        // indexing on (display_name, in_visible_group)
2337        db.execSQL(
2338                "UPDATE " + Tables.RAW_CONTACTS +
2339                " SET contact_in_visible_group=(" +
2340                        "SELECT " + Contacts.IN_VISIBLE_GROUP +
2341                        " FROM " + Tables.CONTACTS +
2342                        " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" +
2343                " WHERE " + RawContacts.CONTACT_ID + " NOT NULL"
2344        );
2345
2346        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
2347                "contact_in_visible_group" + "," +
2348                RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" +
2349        ");");
2350
2351        db.execSQL("DROP INDEX contacts_visible_index");
2352        db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
2353                Contacts.IN_VISIBLE_GROUP +
2354        ");");
2355    }
2356
2357    private void upgradeToVersion205(SQLiteDatabase db) {
2358        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2359                + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;");
2360        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2361                + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;");
2362        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2363                + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;");
2364        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2365                + " ADD " + RawContacts.SORT_KEY_PRIMARY
2366                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
2367        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2368                + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE
2369                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
2370
2371        final Locale locale = Locale.getDefault();
2372
2373        NameSplitter splitter = createNameSplitter();
2374
2375        SQLiteStatement rawContactUpdate = db.compileStatement(
2376                "UPDATE " + Tables.RAW_CONTACTS +
2377                " SET " +
2378                        RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
2379                        RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
2380                        RawContacts.PHONETIC_NAME + "=?," +
2381                        RawContacts.PHONETIC_NAME_STYLE + "=?," +
2382                        RawContacts.SORT_KEY_PRIMARY + "=?," +
2383                        RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
2384                " WHERE " + RawContacts._ID + "=?");
2385
2386        upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter);
2387        upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter);
2388
2389        db.execSQL("DROP INDEX raw_contact_sort_key1_index");
2390        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
2391                "contact_in_visible_group" + "," +
2392                RawContacts.SORT_KEY_PRIMARY +
2393        ");");
2394
2395        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
2396                "contact_in_visible_group" + "," +
2397                RawContacts.SORT_KEY_ALTERNATIVE +
2398        ");");
2399    }
2400
2401    private interface StructName205Query {
2402        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
2403
2404        String COLUMNS[] = {
2405                DataColumns.CONCRETE_ID,
2406                Data.RAW_CONTACT_ID,
2407                RawContacts.DISPLAY_NAME_SOURCE,
2408                RawContacts.DISPLAY_NAME_PRIMARY,
2409                StructuredName.PREFIX,
2410                StructuredName.GIVEN_NAME,
2411                StructuredName.MIDDLE_NAME,
2412                StructuredName.FAMILY_NAME,
2413                StructuredName.SUFFIX,
2414                StructuredName.PHONETIC_FAMILY_NAME,
2415                StructuredName.PHONETIC_MIDDLE_NAME,
2416                StructuredName.PHONETIC_GIVEN_NAME,
2417        };
2418
2419        int ID = 0;
2420        int RAW_CONTACT_ID = 1;
2421        int DISPLAY_NAME_SOURCE = 2;
2422        int DISPLAY_NAME = 3;
2423        int PREFIX = 4;
2424        int GIVEN_NAME = 5;
2425        int MIDDLE_NAME = 6;
2426        int FAMILY_NAME = 7;
2427        int SUFFIX = 8;
2428        int PHONETIC_FAMILY_NAME = 9;
2429        int PHONETIC_MIDDLE_NAME = 10;
2430        int PHONETIC_GIVEN_NAME = 11;
2431    }
2432
2433    private void upgradeStructuredNamesToVersion205(SQLiteDatabase db,
2434            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2435
2436        // Process structured names to detect the style of the full name and phonetic name
2437
2438        long mMimeType;
2439        try {
2440            mMimeType = DatabaseUtils.longForQuery(db,
2441                    "SELECT " + MimetypesColumns._ID +
2442                    " FROM " + Tables.MIMETYPES +
2443                    " WHERE " + MimetypesColumns.MIMETYPE
2444                            + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null);
2445        } catch (SQLiteDoneException e) {
2446            // No structured names in the database
2447            return;
2448        }
2449
2450        SQLiteStatement structuredNameUpdate = db.compileStatement(
2451                "UPDATE " + Tables.DATA +
2452                " SET " +
2453                        StructuredName.FULL_NAME_STYLE + "=?," +
2454                        StructuredName.DISPLAY_NAME + "=?," +
2455                        StructuredName.PHONETIC_NAME_STYLE + "=?" +
2456                " WHERE " + Data._ID + "=?");
2457
2458        NameSplitter.Name name = new NameSplitter.Name();
2459        StringBuilder sb = new StringBuilder();
2460        Cursor cursor = db.query(StructName205Query.TABLE,
2461                StructName205Query.COLUMNS,
2462                DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null);
2463        try {
2464            while (cursor.moveToNext()) {
2465                long dataId = cursor.getLong(StructName205Query.ID);
2466                long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID);
2467                int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE);
2468                String displayName = cursor.getString(StructName205Query.DISPLAY_NAME);
2469
2470                name.clear();
2471                name.prefix = cursor.getString(StructName205Query.PREFIX);
2472                name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME);
2473                name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME);
2474                name.familyName = cursor.getString(StructName205Query.FAMILY_NAME);
2475                name.suffix = cursor.getString(StructName205Query.SUFFIX);
2476                name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME);
2477                name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME);
2478                name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME);
2479
2480                upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name,
2481                        structuredNameUpdate, rawContactUpdate, splitter, sb);
2482            }
2483        } finally {
2484            cursor.close();
2485        }
2486    }
2487
2488    private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource,
2489            String currentDisplayName, NameSplitter.Name name,
2490            SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate,
2491            NameSplitter splitter, StringBuilder sb) {
2492
2493        splitter.guessNameStyle(name);
2494        int unadjustedFullNameStyle = name.fullNameStyle;
2495        name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle);
2496        String displayName = splitter.join(name, true, true);
2497
2498        // Don't update database with the adjusted fullNameStyle as it is locale
2499        // related
2500        structuredNameUpdate.bindLong(1, unadjustedFullNameStyle);
2501        DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName);
2502        structuredNameUpdate.bindLong(3, name.phoneticNameStyle);
2503        structuredNameUpdate.bindLong(4, dataId);
2504        structuredNameUpdate.execute();
2505
2506        if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) {
2507            String displayNameAlternative = splitter.join(name, false, false);
2508            String phoneticName = splitter.joinPhoneticName(name);
2509            String sortKey = null;
2510            String sortKeyAlternative = null;
2511
2512            if (phoneticName != null) {
2513                sortKey = sortKeyAlternative = phoneticName;
2514            } else if (name.fullNameStyle == FullNameStyle.CHINESE ||
2515                    name.fullNameStyle == FullNameStyle.CJK) {
2516                sortKey = sortKeyAlternative = ContactLocaleUtils.getIntance()
2517                        .getSortKey(displayName, name.fullNameStyle);
2518            }
2519
2520            if (sortKey == null) {
2521                sortKey = displayName;
2522                sortKeyAlternative = displayNameAlternative;
2523            }
2524
2525            updateRawContact205(rawContactUpdate, rawContactId, displayName,
2526                    displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey,
2527                    sortKeyAlternative);
2528        }
2529    }
2530
2531    private interface Organization205Query {
2532        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
2533
2534        String COLUMNS[] = {
2535                DataColumns.CONCRETE_ID,
2536                Data.RAW_CONTACT_ID,
2537                Organization.COMPANY,
2538                Organization.PHONETIC_NAME,
2539        };
2540
2541        int ID = 0;
2542        int RAW_CONTACT_ID = 1;
2543        int COMPANY = 2;
2544        int PHONETIC_NAME = 3;
2545    }
2546
2547    private void upgradeOrganizationsToVersion205(SQLiteDatabase db,
2548            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2549        final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE);
2550
2551        SQLiteStatement organizationUpdate = db.compileStatement(
2552                "UPDATE " + Tables.DATA +
2553                " SET " +
2554                        Organization.PHONETIC_NAME_STYLE + "=?" +
2555                " WHERE " + Data._ID + "=?");
2556
2557        Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS,
2558                DataColumns.MIMETYPE_ID + "=" + mimeType + " AND "
2559                        + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION,
2560                null, null, null, null);
2561        try {
2562            while (cursor.moveToNext()) {
2563                long dataId = cursor.getLong(Organization205Query.ID);
2564                long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID);
2565                String company = cursor.getString(Organization205Query.COMPANY);
2566                String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME);
2567
2568                int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName);
2569
2570                organizationUpdate.bindLong(1, phoneticNameStyle);
2571                organizationUpdate.bindLong(2, dataId);
2572                organizationUpdate.execute();
2573
2574                String sortKey = null;
2575                if (phoneticName == null && company != null) {
2576                    int nameStyle = splitter.guessFullNameStyle(company);
2577                    nameStyle = splitter.getAdjustedFullNameStyle(nameStyle);
2578                    if (nameStyle == FullNameStyle.CHINESE ||
2579                            nameStyle == FullNameStyle.CJK ) {
2580                        sortKey = ContactLocaleUtils.getIntance()
2581                                .getSortKey(company, nameStyle);
2582                    }
2583                }
2584
2585                if (sortKey == null) {
2586                    sortKey = company;
2587                }
2588
2589                updateRawContact205(rawContactUpdate, rawContactId, company,
2590                        company, phoneticNameStyle, phoneticName, sortKey, sortKey);
2591            }
2592        } finally {
2593            cursor.close();
2594        }
2595    }
2596
2597    private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId,
2598            String displayName, String displayNameAlternative, int phoneticNameStyle,
2599            String phoneticName, String sortKeyPrimary, String sortKeyAlternative) {
2600        bindString(rawContactUpdate, 1, displayName);
2601        bindString(rawContactUpdate, 2, displayNameAlternative);
2602        bindString(rawContactUpdate, 3, phoneticName);
2603        rawContactUpdate.bindLong(4, phoneticNameStyle);
2604        bindString(rawContactUpdate, 5, sortKeyPrimary);
2605        bindString(rawContactUpdate, 6, sortKeyAlternative);
2606        rawContactUpdate.bindLong(7, rawContactId);
2607        rawContactUpdate.execute();
2608    }
2609
2610    private void upgrateToVersion206(SQLiteDatabase db) {
2611        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2612                + " ADD " + RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0;");
2613    }
2614
2615    /**
2616     * Fix for the bug where name lookup records for organizations would get removed by
2617     * unrelated updates of the data rows.
2618     */
2619    private void upgradeToVersion300(SQLiteDatabase db) {
2620        // No longer needed
2621    }
2622
2623    private static final class Upgrade303Query {
2624        public static final String TABLE = Tables.DATA;
2625
2626        public static final String SELECTION =
2627                DataColumns.MIMETYPE_ID + "=?" +
2628                    " AND " + Data._ID + " NOT IN " +
2629                    "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" +
2630                    " AND " + Data.DATA1 + " NOT NULL";
2631
2632        public static final String COLUMNS[] = {
2633                Data._ID,
2634                Data.RAW_CONTACT_ID,
2635                Data.DATA1,
2636        };
2637
2638        public static final int ID = 0;
2639        public static final int RAW_CONTACT_ID = 1;
2640        public static final int DATA1 = 2;
2641    }
2642
2643    /**
2644     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2645     * emails during the sync.  We need to restore the lost name lookup rows.
2646     */
2647    private void upgradeEmailToVersion303(SQLiteDatabase db) {
2648        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2649        if (mimeTypeId == -1) {
2650            return;
2651        }
2652
2653        ContentValues values = new ContentValues();
2654
2655        // Find all data rows with the mime type "email" that are missing name lookup
2656        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2657                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2658                null, null, null);
2659        try {
2660            while (cursor.moveToNext()) {
2661                long dataId = cursor.getLong(Upgrade303Query.ID);
2662                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2663                String value = cursor.getString(Upgrade303Query.DATA1);
2664                value = extractHandleFromEmailAddress(value);
2665
2666                if (value != null) {
2667                    values.put(NameLookupColumns.DATA_ID, dataId);
2668                    values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2669                    values.put(NameLookupColumns.NAME_TYPE, NameLookupType.EMAIL_BASED_NICKNAME);
2670                    values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2671                    db.insert(Tables.NAME_LOOKUP, null, values);
2672                }
2673            }
2674        } finally {
2675            cursor.close();
2676        }
2677    }
2678
2679    /**
2680     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2681     * nicknames during the sync.  We need to restore the lost name lookup rows.
2682     */
2683    private void upgradeNicknameToVersion303(SQLiteDatabase db) {
2684        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
2685        if (mimeTypeId == -1) {
2686            return;
2687        }
2688
2689        ContentValues values = new ContentValues();
2690
2691        // Find all data rows with the mime type "nickname" that are missing name lookup
2692        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2693                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2694                null, null, null);
2695        try {
2696            while (cursor.moveToNext()) {
2697                long dataId = cursor.getLong(Upgrade303Query.ID);
2698                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2699                String value = cursor.getString(Upgrade303Query.DATA1);
2700
2701                values.put(NameLookupColumns.DATA_ID, dataId);
2702                values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2703                values.put(NameLookupColumns.NAME_TYPE, NameLookupType.NICKNAME);
2704                values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2705                db.insert(Tables.NAME_LOOKUP, null, values);
2706            }
2707        } finally {
2708            cursor.close();
2709        }
2710    }
2711
2712    private void upgradeToVersion304(SQLiteDatabase db) {
2713        // Mimetype table requires an index on mime type
2714        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" +
2715                MimetypesColumns.MIMETYPE +
2716        ");");
2717    }
2718
2719    private void upgradeToVersion306(SQLiteDatabase db) {
2720        // Fix invalid lookup that was used for Exchange contacts (it was not escaped)
2721        // It happened when a new contact was created AND synchronized
2722        final StringBuilder lookupKeyBuilder = new StringBuilder();
2723        final SQLiteStatement updateStatement = db.compileStatement(
2724                "UPDATE contacts " +
2725                "SET lookup=? " +
2726                "WHERE _id=?");
2727        final Cursor contactIdCursor = db.rawQuery(
2728                "SELECT DISTINCT contact_id " +
2729                "FROM raw_contacts " +
2730                "WHERE deleted=0 AND account_type='com.android.exchange'",
2731                null);
2732        try {
2733            while (contactIdCursor.moveToNext()) {
2734                final long contactId = contactIdCursor.getLong(0);
2735                lookupKeyBuilder.setLength(0);
2736                final Cursor c = db.rawQuery(
2737                        "SELECT account_type, account_name, _id, sourceid, display_name " +
2738                        "FROM raw_contacts " +
2739                        "WHERE contact_id=? " +
2740                        "ORDER BY _id",
2741                        new String[] { String.valueOf(contactId) });
2742                try {
2743                    while (c.moveToNext()) {
2744                        ContactLookupKey.appendToLookupKey(lookupKeyBuilder,
2745                                c.getString(0),
2746                                c.getString(1),
2747                                c.getLong(2),
2748                                c.getString(3),
2749                                c.getString(4));
2750                    }
2751                } finally {
2752                    c.close();
2753                }
2754
2755                if (lookupKeyBuilder.length() == 0) {
2756                    updateStatement.bindNull(1);
2757                } else {
2758                    updateStatement.bindString(1, Uri.encode(lookupKeyBuilder.toString()));
2759                }
2760                updateStatement.bindLong(2, contactId);
2761
2762                updateStatement.execute();
2763            }
2764        } finally {
2765            updateStatement.close();
2766            contactIdCursor.close();
2767        }
2768    }
2769
2770    private void upgradeToVersion307(SQLiteDatabase db) {
2771        db.execSQL("CREATE TABLE properties (" +
2772                "property_key TEXT PRIMARY_KEY, " +
2773                "property_value TEXT" +
2774        ");");
2775    }
2776
2777    private void upgradeToVersion308(SQLiteDatabase db) {
2778        db.execSQL("CREATE TABLE accounts (" +
2779                "account_name TEXT, " +
2780                "account_type TEXT " +
2781        ");");
2782
2783        db.execSQL("INSERT INTO accounts " +
2784                "SELECT DISTINCT account_name, account_type FROM raw_contacts");
2785    }
2786
2787    private void upgradeToVersion400(SQLiteDatabase db) {
2788        db.execSQL("ALTER TABLE " + Tables.GROUPS
2789                + " ADD " + Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0;");
2790        db.execSQL("ALTER TABLE " + Tables.GROUPS
2791                + " ADD " + Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0;");
2792    }
2793
2794    private void upgradeToVersion353(SQLiteDatabase db) {
2795        db.execSQL("DELETE FROM contacts " +
2796                "WHERE NOT EXISTS (SELECT 1 FROM raw_contacts WHERE contact_id=contacts._id)");
2797    }
2798
2799    private void rebuildNameLookup(SQLiteDatabase db) {
2800        db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2801        insertNameLookup(db);
2802        createContactsIndexes(db);
2803    }
2804
2805    /**
2806     * Regenerates all locale-sensitive data: nickname_lookup, name_lookup and sort keys.
2807     */
2808    public void setLocale(ContactsProvider2 provider, Locale locale) {
2809        Log.i(TAG, "Switching to locale " + locale);
2810
2811        long start = SystemClock.uptimeMillis();
2812        SQLiteDatabase db = getWritableDatabase();
2813        db.setLocale(locale);
2814        db.beginTransaction();
2815        try {
2816            db.execSQL("DROP INDEX raw_contact_sort_key1_index");
2817            db.execSQL("DROP INDEX raw_contact_sort_key2_index");
2818            db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2819
2820            loadNicknameLookupTable(db);
2821            insertNameLookup(db);
2822            rebuildSortKeys(db, provider);
2823            createContactsIndexes(db);
2824            db.setTransactionSuccessful();
2825        } finally {
2826            db.endTransaction();
2827        }
2828
2829        Log.i(TAG, "Locale change completed in " + (SystemClock.uptimeMillis() - start) + "ms");
2830    }
2831
2832    /**
2833     * Regenerates sort keys for all contacts.
2834     */
2835    private void rebuildSortKeys(SQLiteDatabase db, ContactsProvider2 provider) {
2836        Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID},
2837                null, null, null, null, null);
2838        try {
2839            while (cursor.moveToNext()) {
2840                long rawContactId = cursor.getLong(0);
2841                updateRawContactDisplayName(db, rawContactId);
2842            }
2843        } finally {
2844            cursor.close();
2845        }
2846    }
2847
2848    private void insertNameLookup(SQLiteDatabase db) {
2849        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP);
2850
2851        SQLiteStatement nameLookupInsert = db.compileStatement(
2852                "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
2853                        + NameLookupColumns.RAW_CONTACT_ID + ","
2854                        + NameLookupColumns.DATA_ID + ","
2855                        + NameLookupColumns.NAME_TYPE + ","
2856                        + NameLookupColumns.NORMALIZED_NAME +
2857                ") VALUES (?,?,?,?)");
2858
2859        try {
2860            insertStructuredNameLookup(db, nameLookupInsert);
2861            insertEmailLookup(db, nameLookupInsert);
2862            insertNicknameLookup(db, nameLookupInsert);
2863        } finally {
2864            nameLookupInsert.close();
2865        }
2866    }
2867
2868    private static final class StructuredNameQuery {
2869        public static final String TABLE = Tables.DATA;
2870
2871        public static final String SELECTION =
2872                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2873
2874        public static final String COLUMNS[] = {
2875                StructuredName._ID,
2876                StructuredName.RAW_CONTACT_ID,
2877                StructuredName.DISPLAY_NAME,
2878        };
2879
2880        public static final int ID = 0;
2881        public static final int RAW_CONTACT_ID = 1;
2882        public static final int DISPLAY_NAME = 2;
2883    }
2884
2885    private class StructuredNameLookupBuilder extends NameLookupBuilder {
2886
2887        private final SQLiteStatement mNameLookupInsert;
2888        private final CommonNicknameCache mCommonNicknameCache;
2889
2890        public StructuredNameLookupBuilder(NameSplitter splitter,
2891                CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) {
2892            super(splitter);
2893            this.mCommonNicknameCache = commonNicknameCache;
2894            this.mNameLookupInsert = nameLookupInsert;
2895        }
2896
2897        @Override
2898        protected void insertNameLookup(long rawContactId, long dataId, int lookupType,
2899                String name) {
2900            if (!TextUtils.isEmpty(name)) {
2901                ContactsDatabaseHelper.this.insertNormalizedNameLookup(mNameLookupInsert,
2902                        rawContactId, dataId, lookupType, name);
2903            }
2904        }
2905
2906        @Override
2907        protected String[] getCommonNicknameClusters(String normalizedName) {
2908            return mCommonNicknameCache.getCommonNicknameClusters(normalizedName);
2909        }
2910    }
2911
2912    /**
2913     * Inserts name lookup rows for all structured names in the database.
2914     */
2915    private void insertStructuredNameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2916        NameSplitter nameSplitter = createNameSplitter();
2917        NameLookupBuilder nameLookupBuilder = new StructuredNameLookupBuilder(nameSplitter,
2918                new CommonNicknameCache(db), nameLookupInsert);
2919        final long mimeTypeId = lookupMimeTypeId(db, StructuredName.CONTENT_ITEM_TYPE);
2920        Cursor cursor = db.query(StructuredNameQuery.TABLE, StructuredNameQuery.COLUMNS,
2921                StructuredNameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2922                null, null, null);
2923        try {
2924            while (cursor.moveToNext()) {
2925                long dataId = cursor.getLong(StructuredNameQuery.ID);
2926                long rawContactId = cursor.getLong(StructuredNameQuery.RAW_CONTACT_ID);
2927                String name = cursor.getString(StructuredNameQuery.DISPLAY_NAME);
2928                int fullNameStyle = nameSplitter.guessFullNameStyle(name);
2929                fullNameStyle = nameSplitter.getAdjustedFullNameStyle(fullNameStyle);
2930                nameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle);
2931            }
2932        } finally {
2933            cursor.close();
2934        }
2935    }
2936
2937    private static final class OrganizationQuery {
2938        public static final String TABLE = Tables.DATA;
2939
2940        public static final String SELECTION =
2941                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2942
2943        public static final String COLUMNS[] = {
2944                Organization._ID,
2945                Organization.RAW_CONTACT_ID,
2946                Organization.COMPANY,
2947                Organization.TITLE,
2948        };
2949
2950        public static final int ID = 0;
2951        public static final int RAW_CONTACT_ID = 1;
2952        public static final int COMPANY = 2;
2953        public static final int TITLE = 3;
2954    }
2955
2956    private static final class EmailQuery {
2957        public static final String TABLE = Tables.DATA;
2958
2959        public static final String SELECTION =
2960                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2961
2962        public static final String COLUMNS[] = {
2963                Email._ID,
2964                Email.RAW_CONTACT_ID,
2965                Email.ADDRESS,
2966        };
2967
2968        public static final int ID = 0;
2969        public static final int RAW_CONTACT_ID = 1;
2970        public static final int ADDRESS = 2;
2971    }
2972
2973    /**
2974     * Inserts name lookup rows for all email addresses in the database.
2975     */
2976    private void insertEmailLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2977        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2978        Cursor cursor = db.query(EmailQuery.TABLE, EmailQuery.COLUMNS,
2979                EmailQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2980                null, null, null);
2981        try {
2982            while (cursor.moveToNext()) {
2983                long dataId = cursor.getLong(EmailQuery.ID);
2984                long rawContactId = cursor.getLong(EmailQuery.RAW_CONTACT_ID);
2985                String address = cursor.getString(EmailQuery.ADDRESS);
2986                address = extractHandleFromEmailAddress(address);
2987                insertNameLookup(nameLookupInsert, rawContactId, dataId,
2988                        NameLookupType.EMAIL_BASED_NICKNAME, address);
2989            }
2990        } finally {
2991            cursor.close();
2992        }
2993    }
2994
2995    private static final class NicknameQuery {
2996        public static final String TABLE = Tables.DATA;
2997
2998        public static final String SELECTION =
2999                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
3000
3001        public static final String COLUMNS[] = {
3002                Nickname._ID,
3003                Nickname.RAW_CONTACT_ID,
3004                Nickname.NAME,
3005        };
3006
3007        public static final int ID = 0;
3008        public static final int RAW_CONTACT_ID = 1;
3009        public static final int NAME = 2;
3010    }
3011
3012    /**
3013     * Inserts name lookup rows for all nicknames in the database.
3014     */
3015    private void insertNicknameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
3016        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
3017        Cursor cursor = db.query(NicknameQuery.TABLE, NicknameQuery.COLUMNS,
3018                NicknameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
3019                null, null, null);
3020        try {
3021            while (cursor.moveToNext()) {
3022                long dataId = cursor.getLong(NicknameQuery.ID);
3023                long rawContactId = cursor.getLong(NicknameQuery.RAW_CONTACT_ID);
3024                String nickname = cursor.getString(NicknameQuery.NAME);
3025                insertNameLookup(nameLookupInsert, rawContactId, dataId,
3026                        NameLookupType.NICKNAME, nickname);
3027            }
3028        } finally {
3029            cursor.close();
3030        }
3031    }
3032
3033    /**
3034     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
3035     */
3036    public void insertNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
3037            int lookupType, String name) {
3038        if (TextUtils.isEmpty(name)) {
3039            return;
3040        }
3041
3042        String normalized = NameNormalizer.normalize(name);
3043        if (TextUtils.isEmpty(normalized)) {
3044            return;
3045        }
3046
3047        insertNormalizedNameLookup(stmt, rawContactId, dataId, lookupType, normalized);
3048    }
3049
3050    private void insertNormalizedNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
3051            int lookupType, String normalizedName) {
3052        stmt.bindLong(1, rawContactId);
3053        stmt.bindLong(2, dataId);
3054        stmt.bindLong(3, lookupType);
3055        stmt.bindString(4, normalizedName);
3056        stmt.executeInsert();
3057    }
3058
3059    /**
3060     * Changing the VISIBLE bit from a field on both RawContacts and Contacts to a separate table.
3061     */
3062    private void upgradeToVersion401(SQLiteDatabase db) {
3063        db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" +
3064                Contacts._ID + " INTEGER PRIMARY KEY" +
3065        ");");
3066        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
3067                " SELECT " + Contacts._ID +
3068                " FROM " + Tables.CONTACTS +
3069                " WHERE " + Contacts.IN_VISIBLE_GROUP + "!=0");
3070        db.execSQL("DROP INDEX contacts_visible_index");
3071    }
3072
3073    /**
3074     * Introducing a new table: directories.
3075     */
3076    private void upgradeToVersion402(SQLiteDatabase db) {
3077        createDirectoriesTable(db);
3078    }
3079
3080    private void upgradeToVersion403(SQLiteDatabase db) {
3081        db.execSQL("DROP TABLE IF EXISTS directories;");
3082        createDirectoriesTable(db);
3083
3084        db.execSQL("ALTER TABLE raw_contacts"
3085                + " ADD raw_contact_is_read_only INTEGER NOT NULL DEFAULT 0;");
3086
3087        db.execSQL("ALTER TABLE data"
3088                + " ADD is_read_only INTEGER NOT NULL DEFAULT 0;");
3089    }
3090
3091    private void upgradeToVersion405(SQLiteDatabase db) {
3092        db.execSQL("DROP TABLE IF EXISTS phone_lookup;");
3093        // Private phone numbers table used for lookup
3094        db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
3095                PhoneLookupColumns.DATA_ID
3096                + " INTEGER REFERENCES data(_id) NOT NULL," +
3097                PhoneLookupColumns.RAW_CONTACT_ID
3098                + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
3099                PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
3100                PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
3101        ");");
3102
3103        db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
3104                PhoneLookupColumns.NORMALIZED_NUMBER + "," +
3105                PhoneLookupColumns.RAW_CONTACT_ID + "," +
3106                PhoneLookupColumns.DATA_ID +
3107        ");");
3108
3109        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
3110                PhoneLookupColumns.MIN_MATCH + "," +
3111                PhoneLookupColumns.RAW_CONTACT_ID + "," +
3112                PhoneLookupColumns.DATA_ID +
3113        ");");
3114
3115        final long mimeTypeId = lookupMimeTypeId(db, Phone.CONTENT_ITEM_TYPE);
3116        if (mimeTypeId == -1) {
3117            return;
3118        }
3119
3120        Cursor cursor = db.rawQuery(
3121                    "SELECT _id, " + Phone.RAW_CONTACT_ID + ", " + Phone.NUMBER +
3122                    " FROM " + Tables.DATA +
3123                    " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimeTypeId
3124                            + " AND " + Phone.NUMBER + " NOT NULL", null);
3125
3126        ContentValues phoneValues = new ContentValues();
3127        try {
3128            while (cursor.moveToNext()) {
3129                long dataID = cursor.getLong(0);
3130                long rawContactID = cursor.getLong(1);
3131                String number = cursor.getString(2);
3132                String normalizedNumber = PhoneNumberUtils.normalizeNumber(number);
3133                if (!TextUtils.isEmpty(normalizedNumber)) {
3134                    phoneValues.clear();
3135                    phoneValues.put(PhoneLookupColumns.RAW_CONTACT_ID, rawContactID);
3136                    phoneValues.put(PhoneLookupColumns.DATA_ID, dataID);
3137                    phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, normalizedNumber);
3138                    phoneValues.put(PhoneLookupColumns.MIN_MATCH,
3139                            PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber));
3140                    db.insert(Tables.PHONE_LOOKUP, null, phoneValues);
3141                }
3142            }
3143        } finally {
3144            cursor.close();
3145        }
3146    }
3147
3148    private void upgradeToVersion406(SQLiteDatabase db) {
3149        db.execSQL("ALTER TABLE calls ADD countryiso TEXT;");
3150    }
3151
3152    private void upgradeToVersion409(SQLiteDatabase db) {
3153        db.execSQL("DROP TABLE IF EXISTS directories;");
3154        createDirectoriesTable(db);
3155    }
3156
3157    /**
3158     * Adding DEFAULT_DIRECTORY table.
3159     * DEFAULT_DIRECTORY should contain every contact which should be shown to users in default.
3160     * - if a contact doesn't belong to any account (local contact), it should be in
3161     *   default_directory
3162     * - if a contact belongs to an account that doesn't have a "default" group, it should be in
3163     *   default_directory
3164     * - if a contact belongs to an account that has a "default" group (like Google directory,
3165     *   which has "My contacts" group as default), it should be in default_directory.
3166     *
3167     * This logic assumes that accounts with the "default" group should have at least one
3168     * group with AUTO_ADD (implying it is the default group) flag in the groups table.
3169     */
3170    private void upgradeToVersion411(SQLiteDatabase db) {
3171        db.execSQL("DROP TABLE IF EXISTS " + Tables.DEFAULT_DIRECTORY);
3172        db.execSQL("CREATE TABLE default_directory (_id INTEGER PRIMARY KEY);");
3173
3174        // Process contacts without an account
3175        db.execSQL("INSERT OR IGNORE INTO default_directory " +
3176                " SELECT contact_id " +
3177                " FROM raw_contacts " +
3178                " WHERE raw_contacts.account_name IS NULL " +
3179                "   AND raw_contacts.account_type IS NULL ");
3180
3181        // Process accounts that don't have a default group (e.g. Exchange).
3182        db.execSQL("INSERT OR IGNORE INTO default_directory " +
3183                " SELECT contact_id " +
3184                " FROM raw_contacts " +
3185                " WHERE NOT EXISTS" +
3186                " (SELECT _id " +
3187                "  FROM groups " +
3188                "  WHERE raw_contacts.account_name = groups.account_name" +
3189                "    AND raw_contacts.account_type = groups.account_type" +
3190                "    AND groups.auto_add != 0)");
3191
3192        final long mimetype = lookupMimeTypeId(db, GroupMembership.CONTENT_ITEM_TYPE);
3193
3194        // Process accounts that do have a default group (e.g. Google)
3195        db.execSQL("INSERT OR IGNORE INTO default_directory " +
3196                " SELECT contact_id " +
3197                " FROM raw_contacts " +
3198                " JOIN data " +
3199                "   ON (raw_contacts._id=raw_contact_id)" +
3200                " WHERE mimetype_id=" + mimetype +
3201                " AND EXISTS" +
3202                " (SELECT _id" +
3203                "  FROM groups" +
3204                "  WHERE raw_contacts.account_name = groups.account_name" +
3205                "    AND raw_contacts.account_type = groups.account_type" +
3206                "    AND groups.auto_add != 0)");
3207    }
3208
3209    private void upgradeToVersion413(SQLiteDatabase db) {
3210        db.execSQL("DROP TABLE IF EXISTS directories;");
3211        createDirectoriesTable(db);
3212    }
3213
3214    private void upgradeToVersion415(SQLiteDatabase db) {
3215        db.execSQL(
3216                "ALTER TABLE " + Tables.GROUPS +
3217                " ADD " + Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0");
3218        db.execSQL(
3219                "UPDATE " + Tables.GROUPS +
3220                "   SET " + Groups.GROUP_IS_READ_ONLY + "=1" +
3221                " WHERE " + Groups.SYSTEM_ID + " NOT NULL");
3222    }
3223
3224    private void upgradeToVersion416(SQLiteDatabase db) {
3225        db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP +
3226                " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");");
3227    }
3228
3229    private void upgradeToVersion501(SQLiteDatabase db) {
3230        // Remove organization rows from the name lookup, we now use search index for that
3231        db.execSQL("DELETE FROM name_lookup WHERE name_type=5");
3232    }
3233
3234    private void upgradeToVersion502(SQLiteDatabase db) {
3235        // Remove Chinese and Korean name lookup - this data is now in the search index
3236        db.execSQL("DELETE FROM name_lookup WHERE name_type IN (6, 7)");
3237    }
3238
3239    private void upgradeToVersion504(SQLiteDatabase db) {
3240        populateMimeTypeCache(db);
3241
3242        // Find all names with prefixes and recreate display name
3243        Cursor cursor = db.rawQuery(
3244                "SELECT " + StructuredName.RAW_CONTACT_ID +
3245                " FROM " + Tables.DATA +
3246                " WHERE " + DataColumns.MIMETYPE_ID + "=?"
3247                        + " AND " + StructuredName.PREFIX + " NOT NULL",
3248                new String[]{ String.valueOf(mMimeTypeIdStructuredName) });
3249
3250        try {
3251            while(cursor.moveToNext()) {
3252                long rawContactId = cursor.getLong(0);
3253                updateRawContactDisplayName(db, rawContactId);
3254            }
3255
3256        } finally {
3257            cursor.close();
3258        }
3259    }
3260
3261    private void upgradeToVersion600(SQLiteDatabase db) {
3262        // Add a column to the Accounts table to track which raw contact ID (if any) represents that
3263        // account's contribution to the user's profile Contact.
3264        db.execSQL("ALTER TABLE accounts" +
3265                " ADD profile_raw_contact_id INTEGER");
3266        db.execSQL("CREATE INDEX accounts_profile_raw_contact_id_index ON accounts" +
3267                " (profile_raw_contact_id);");
3268    }
3269
3270    private void upgradeToVersion601(SQLiteDatabase db) {
3271        db.execSQL("CREATE TABLE data_usage_stat(" +
3272                "stat_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3273                "data_id INTEGER NOT NULL, " +
3274                "usage_type INTEGER NOT NULL DEFAULT 0, " +
3275                "times_used INTEGER NOT NULL DEFAULT 0, " +
3276                "last_time_used INTERGER NOT NULL DEFAULT 0, " +
3277                "FOREIGN KEY(data_id) REFERENCES data(_id));");
3278        db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " +
3279                "data_usage_stat (data_id, usage_type)");
3280    }
3281
3282    private void upgradeToVersion602(SQLiteDatabase db) {
3283        db.execSQL("ALTER TABLE calls ADD voicemail_uri TEXT;");
3284        db.execSQL("ALTER TABLE calls ADD _data TEXT;");
3285        db.execSQL("ALTER TABLE calls ADD has_content INTEGER;");
3286        db.execSQL("ALTER TABLE calls ADD mime_type TEXT;");
3287        db.execSQL("ALTER TABLE calls ADD source_data TEXT;");
3288        db.execSQL("ALTER TABLE calls ADD source_package TEXT;");
3289        db.execSQL("ALTER TABLE calls ADD state INTEGER;");
3290    }
3291
3292    private void upgradeToVersion604(SQLiteDatabase db) {
3293        db.execSQL("CREATE TABLE voicemail_status (" +
3294                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
3295                "source_package TEXT UNIQUE NOT NULL," +
3296                "settings_uri TEXT," +
3297                "voicemail_access_uri TEXT," +
3298                "configuration_state INTEGER," +
3299                "data_channel_state INTEGER," +
3300                "notification_channel_state INTEGER" +
3301        ");");
3302    }
3303
3304    private void upgradeToVersion605(SQLiteDatabase db) {
3305        // This version used to create the stream item and stream item photos tables, but a newer
3306        // version of those tables is created in version 609 below.  So omitting the creation in
3307        // this upgrade step to avoid a create->drop->create.
3308    }
3309
3310    private void upgradeToVersion606(SQLiteDatabase db) {
3311        db.execSQL("DROP VIEW IF EXISTS view_contacts_restricted;");
3312        db.execSQL("DROP VIEW IF EXISTS view_data_restricted;");
3313        db.execSQL("DROP VIEW IF EXISTS view_raw_contacts_restricted;");
3314        db.execSQL("DROP VIEW IF EXISTS view_raw_entities_restricted;");
3315        db.execSQL("DROP VIEW IF EXISTS view_entities_restricted;");
3316        db.execSQL("DROP VIEW IF EXISTS view_data_usage_stat_restricted;");
3317        db.execSQL("DROP INDEX IF EXISTS contacts_restricted_index");
3318
3319        // We should remove the restricted columns here as well, but unfortunately SQLite doesn't
3320        // provide ALTER TABLE DROP COLUMN. As they have DEFAULT 0, we can keep but ignore them
3321    }
3322
3323    private void upgradeToVersion607(SQLiteDatabase db) {
3324        // We added "action" and "action_uri" to groups here, but realized this was not a smart
3325        // move. This upgrade step has been removed (all dogfood phones that executed this step
3326        // will have those columns, but that shouldn't hurt. Unfortunately, SQLite makes it hard
3327        // to remove columns)
3328    }
3329
3330    private void upgradeToVersion608(SQLiteDatabase db) {
3331        db.execSQL("ALTER TABLE contacts ADD photo_file_id INTEGER REFERENCES photo_files(_id);");
3332
3333        db.execSQL("CREATE TABLE photo_files(" +
3334                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3335                "height INTEGER NOT NULL, " +
3336                "width INTEGER NOT NULL, " +
3337                "filesize INTEGER NOT NULL);");
3338    }
3339
3340    private void upgradeToVersion609(SQLiteDatabase db) {
3341        // This version used to create the stream item and stream item photos tables, but a newer
3342        // version of those tables is created in version 613 below.  So omitting the creation in
3343        // this upgrade step to avoid a create->drop->create.
3344    }
3345
3346    private void upgradeToVersion610(SQLiteDatabase db) {
3347        db.execSQL("ALTER TABLE calls ADD is_read INTEGER;");
3348    }
3349
3350    private void upgradeToVersion611(SQLiteDatabase db) {
3351        db.execSQL("ALTER TABLE raw_contacts ADD data_set TEXT DEFAULT NULL;");
3352        db.execSQL("ALTER TABLE groups ADD data_set TEXT DEFAULT NULL;");
3353        db.execSQL("ALTER TABLE accounts ADD data_set TEXT DEFAULT NULL;");
3354
3355        db.execSQL("CREATE INDEX raw_contacts_source_id_data_set_index ON raw_contacts " +
3356                "(sourceid, account_type, account_name, data_set);");
3357
3358        db.execSQL("CREATE INDEX groups_source_id_data_set_index ON groups " +
3359                "(sourceid, account_type, account_name, data_set);");
3360    }
3361
3362    private void upgradeToVersion612(SQLiteDatabase db) {
3363        db.execSQL("ALTER TABLE calls ADD geocoded_location TEXT DEFAULT NULL;");
3364        // Old calls will not have a geocoded location; new calls will get it when inserted.
3365    }
3366
3367    private void upgradeToVersion613(SQLiteDatabase db) {
3368        // The stream item and stream item photos APIs were not in-use by anyone in the time
3369        // between their initial creation (in v609) and this update.  So we're just dropping
3370        // and re-creating them to get appropriate columns.  The delta is as follows:
3371        // - In stream_items, package_id was replaced by res_package.
3372        // - In stream_item_photos, picture was replaced by photo_file_id.
3373        // - Instead of resource ids for icon and label, we use resource name strings now
3374        // - Added sync columns
3375        // - Removed action and action_uri
3376        // - Text and comments are now nullable
3377
3378        db.execSQL("DROP TABLE IF EXISTS stream_items");
3379        db.execSQL("DROP TABLE IF EXISTS stream_item_photos");
3380
3381        db.execSQL("CREATE TABLE stream_items(" +
3382                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3383                "raw_contact_id INTEGER NOT NULL, " +
3384                "res_package TEXT, " +
3385                "icon TEXT, " +
3386                "label TEXT, " +
3387                "text TEXT, " +
3388                "timestamp INTEGER NOT NULL, " +
3389                "comments TEXT, " +
3390                "stream_item_sync1 TEXT, " +
3391                "stream_item_sync2 TEXT, " +
3392                "stream_item_sync3 TEXT, " +
3393                "stream_item_sync4 TEXT, " +
3394                "FOREIGN KEY(raw_contact_id) REFERENCES raw_contacts(_id));");
3395
3396        db.execSQL("CREATE TABLE stream_item_photos(" +
3397                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3398                "stream_item_id INTEGER NOT NULL, " +
3399                "sort_index INTEGER, " +
3400                "photo_file_id INTEGER NOT NULL, " +
3401                "stream_item_photo_sync1 TEXT, " +
3402                "stream_item_photo_sync2 TEXT, " +
3403                "stream_item_photo_sync3 TEXT, " +
3404                "stream_item_photo_sync4 TEXT, " +
3405                "FOREIGN KEY(stream_item_id) REFERENCES stream_items(_id));");
3406    }
3407
3408    public String extractHandleFromEmailAddress(String email) {
3409        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
3410        if (tokens.length == 0) {
3411            return null;
3412        }
3413
3414        String address = tokens[0].getAddress();
3415        int at = address.indexOf('@');
3416        if (at != -1) {
3417            return address.substring(0, at);
3418        }
3419        return null;
3420    }
3421
3422    public String extractAddressFromEmailAddress(String email) {
3423        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
3424        if (tokens.length == 0) {
3425            return null;
3426        }
3427
3428        return tokens[0].getAddress().trim();
3429    }
3430
3431    private static long lookupMimeTypeId(SQLiteDatabase db, String mimeType) {
3432        try {
3433            return DatabaseUtils.longForQuery(db,
3434                    "SELECT " + MimetypesColumns._ID +
3435                    " FROM " + Tables.MIMETYPES +
3436                    " WHERE " + MimetypesColumns.MIMETYPE
3437                            + "='" + mimeType + "'", null);
3438        } catch (SQLiteDoneException e) {
3439            // No rows of this type in the database
3440            return -1;
3441        }
3442    }
3443
3444    private void bindString(SQLiteStatement stmt, int index, String value) {
3445        if (value == null) {
3446            stmt.bindNull(index);
3447        } else {
3448            stmt.bindString(index, value);
3449        }
3450    }
3451
3452    private void bindLong(SQLiteStatement stmt, int index, Number value) {
3453        if (value == null) {
3454            stmt.bindNull(index);
3455        } else {
3456            stmt.bindLong(index, value.longValue());
3457        }
3458    }
3459
3460    /**
3461     * Adds index stats into the SQLite database to force it to always use the lookup indexes.
3462     */
3463    private void updateSqliteStats(SQLiteDatabase db) {
3464
3465        // Specific stats strings are based on an actual large database after running ANALYZE
3466        try {
3467            updateIndexStats(db, Tables.CONTACTS,
3468                    "contacts_has_phone_index", "10000 500");
3469
3470            updateIndexStats(db, Tables.RAW_CONTACTS,
3471                    "raw_contacts_source_id_index", "10000 1 1 1");
3472            updateIndexStats(db, Tables.RAW_CONTACTS,
3473                    "raw_contacts_contact_id_index", "10000 2");
3474
3475            updateIndexStats(db, Tables.NAME_LOOKUP,
3476                    "name_lookup_raw_contact_id_index", "10000 3");
3477            updateIndexStats(db, Tables.NAME_LOOKUP,
3478                    "name_lookup_index", "10000 3 2 2 1");
3479            updateIndexStats(db, Tables.NAME_LOOKUP,
3480                    "sqlite_autoindex_name_lookup_1", "10000 3 2 1");
3481
3482            updateIndexStats(db, Tables.PHONE_LOOKUP,
3483                    "phone_lookup_index", "10000 2 2 1");
3484            updateIndexStats(db, Tables.PHONE_LOOKUP,
3485                    "phone_lookup_min_match_index", "10000 2 2 1");
3486
3487            updateIndexStats(db, Tables.DATA,
3488                    "data_mimetype_data1_index", "60000 5000 2");
3489            updateIndexStats(db, Tables.DATA,
3490                    "data_raw_contact_id", "60000 10");
3491
3492            updateIndexStats(db, Tables.GROUPS,
3493                    "groups_source_id_index", "50 1 1 1");
3494
3495            updateIndexStats(db, Tables.NICKNAME_LOOKUP,
3496                    "sqlite_autoindex_name_lookup_1", "500 2 1");
3497
3498        } catch (SQLException e) {
3499            Log.e(TAG, "Could not update index stats", e);
3500        }
3501    }
3502
3503    /**
3504     * Stores statistics for a given index.
3505     *
3506     * @param stats has the following structure: the first index is the expected size of
3507     * the table.  The following integer(s) are the expected number of records selected with the
3508     * index.  There should be one integer per indexed column.
3509     */
3510    private void updateIndexStats(SQLiteDatabase db, String table, String index,
3511            String stats) {
3512        db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl='" + table + "' AND idx='" + index + "';");
3513        db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat)"
3514                + " VALUES ('" + table + "','" + index + "','" + stats + "');");
3515    }
3516
3517    @Override
3518    public synchronized SQLiteDatabase getWritableDatabase() {
3519        SQLiteDatabase db = super.getWritableDatabase();
3520        if (mReopenDatabase) {
3521            mReopenDatabase = false;
3522            close();
3523            db = super.getWritableDatabase();
3524        }
3525        return db;
3526    }
3527
3528    /**
3529     * Wipes all data except mime type and package lookup tables.
3530     */
3531    public void wipeData() {
3532        SQLiteDatabase db = getWritableDatabase();
3533
3534        db.execSQL("DELETE FROM " + Tables.ACCOUNTS + ";");
3535        db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL, NULL, NULL)");
3536
3537        db.execSQL("DELETE FROM " + Tables.CONTACTS + ";");
3538        db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";");
3539        db.execSQL("DELETE FROM " + Tables.STREAM_ITEMS + ";");
3540        db.execSQL("DELETE FROM " + Tables.STREAM_ITEM_PHOTOS + ";");
3541        db.execSQL("DELETE FROM " + Tables.PHOTO_FILES + ";");
3542        db.execSQL("DELETE FROM " + Tables.DATA + ";");
3543        db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";");
3544        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";");
3545        db.execSQL("DELETE FROM " + Tables.GROUPS + ";");
3546        db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";");
3547        db.execSQL("DELETE FROM " + Tables.SETTINGS + ";");
3548        db.execSQL("DELETE FROM " + Tables.ACTIVITIES + ";");
3549        db.execSQL("DELETE FROM " + Tables.CALLS + ";");
3550        db.execSQL("DELETE FROM " + Tables.DIRECTORIES + ";");
3551        db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + ";");
3552
3553        // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP
3554    }
3555
3556    public NameSplitter createNameSplitter() {
3557        mNameSplitter = new NameSplitter(
3558                mContext.getString(com.android.internal.R.string.common_name_prefixes),
3559                mContext.getString(com.android.internal.R.string.common_last_name_prefixes),
3560                mContext.getString(com.android.internal.R.string.common_name_suffixes),
3561                mContext.getString(com.android.internal.R.string.common_name_conjunctions),
3562                Locale.getDefault());
3563        return mNameSplitter;
3564    }
3565
3566    /**
3567     * Return the {@link ApplicationInfo#uid} for the given package name.
3568     */
3569    public static int getUidForPackageName(PackageManager pm, String packageName) {
3570        try {
3571            ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */);
3572            return clientInfo.uid;
3573        } catch (NameNotFoundException e) {
3574            throw new RuntimeException(e);
3575        }
3576    }
3577
3578    /**
3579     * Perform an internal string-to-integer lookup using the compiled
3580     * {@link SQLiteStatement} provided, using the in-memory cache to speed up
3581     * lookups. If a mapping isn't found in cache or database, it will be
3582     * created. All new, uncached answers are added to the cache automatically.
3583     *
3584     * @param query Compiled statement used to query for the mapping.
3585     * @param insert Compiled statement used to insert a new mapping when no
3586     *            existing one is found in cache or from query.
3587     * @param value Value to find mapping for.
3588     * @param cache In-memory cache of previous answers.
3589     * @return An unique integer mapping for the given value.
3590     */
3591    private long getCachedId(SQLiteStatement query, SQLiteStatement insert,
3592            String value, HashMap<String, Long> cache) {
3593        // Try an in-memory cache lookup
3594        if (cache.containsKey(value)) {
3595            return cache.get(value);
3596        }
3597
3598        synchronized (query) {
3599            long id = -1;
3600            try {
3601                // Try searching database for mapping
3602                DatabaseUtils.bindObjectToProgram(query, 1, value);
3603                id = query.simpleQueryForLong();
3604            } catch (SQLiteDoneException e) {
3605                // Nothing found, so try inserting new mapping
3606                DatabaseUtils.bindObjectToProgram(insert, 1, value);
3607                id = insert.executeInsert();
3608            }
3609            if (id != -1) {
3610                // Cache and return the new answer
3611                cache.put(value, id);
3612                return id;
3613            } else {
3614                // Otherwise throw if no mapping found or created
3615                throw new IllegalStateException("Couldn't find or create internal "
3616                        + "lookup table entry for value " + value);
3617            }
3618        }
3619    }
3620
3621    /**
3622     * Convert a package name into an integer, using {@link Tables#PACKAGES} for
3623     * lookups and possible allocation of new IDs as needed.
3624     */
3625    public long getPackageId(String packageName) {
3626        if (mPackageQuery == null) {
3627            mPackageQuery = getWritableDatabase().compileStatement(
3628                    "SELECT " + PackagesColumns._ID +
3629                    " FROM " + Tables.PACKAGES +
3630                    " WHERE " + PackagesColumns.PACKAGE + "=?");
3631
3632        }
3633        if (mPackageInsert == null) {
3634            mPackageInsert = getWritableDatabase().compileStatement(
3635                    "INSERT INTO " + Tables.PACKAGES + "("
3636                            + PackagesColumns.PACKAGE +
3637                    ") VALUES (?)");
3638        }
3639        return getCachedId(mPackageQuery, mPackageInsert, packageName, mPackageCache);
3640    }
3641
3642    /**
3643     * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for
3644     * lookups and possible allocation of new IDs as needed.
3645     */
3646    public long getMimeTypeId(String mimetype) {
3647        return getCachedId(mMimetypeQuery, mMimetypeInsert, mimetype, mMimetypeCache);
3648    }
3649
3650    public long getMimeTypeIdForStructuredName() {
3651        return mMimeTypeIdStructuredName;
3652    }
3653
3654    public long getMimeTypeIdForOrganization() {
3655        return mMimeTypeIdOrganization;
3656    }
3657
3658    public long getMimeTypeIdForIm() {
3659        return mMimeTypeIdIm;
3660    }
3661
3662    public long getMimeTypeIdForEmail() {
3663        return mMimeTypeIdEmail;
3664    }
3665
3666    public long getMimeTypeIdForSip() {
3667        return mMimeTypeIdSip;
3668    }
3669
3670    public int getDisplayNameSourceForMimeTypeId(int mimeTypeId) {
3671        if (mimeTypeId == mMimeTypeIdStructuredName) {
3672            return DisplayNameSources.STRUCTURED_NAME;
3673        } else if (mimeTypeId == mMimeTypeIdEmail) {
3674            return DisplayNameSources.EMAIL;
3675        } else if (mimeTypeId == mMimeTypeIdPhone) {
3676            return DisplayNameSources.PHONE;
3677        } else if (mimeTypeId == mMimeTypeIdOrganization) {
3678            return DisplayNameSources.ORGANIZATION;
3679        } else if (mimeTypeId == mMimeTypeIdNickname) {
3680            return DisplayNameSources.NICKNAME;
3681        } else {
3682            return DisplayNameSources.UNDEFINED;
3683        }
3684    }
3685
3686    /**
3687     * Find the mimetype for the given {@link Data#_ID}.
3688     */
3689    public String getDataMimeType(long dataId) {
3690        if (mDataMimetypeQuery == null) {
3691            mDataMimetypeQuery = getWritableDatabase().compileStatement(
3692                    "SELECT " + MimetypesColumns.MIMETYPE +
3693                    " FROM " + Tables.DATA_JOIN_MIMETYPES +
3694                    " WHERE " + Tables.DATA + "." + Data._ID + "=?");
3695        }
3696        try {
3697            // Try database query to find mimetype
3698            DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId);
3699            String mimetype = mDataMimetypeQuery.simpleQueryForString();
3700            return mimetype;
3701        } catch (SQLiteDoneException e) {
3702            // No valid mapping found, so return null
3703            return null;
3704        }
3705    }
3706
3707    /**
3708     * Find the mime-type for the given {@link Activities#_ID}.
3709     */
3710    public String getActivityMimeType(long activityId) {
3711        if (mActivitiesMimetypeQuery == null) {
3712            mActivitiesMimetypeQuery = getWritableDatabase().compileStatement(
3713                    "SELECT " + MimetypesColumns.MIMETYPE +
3714                    " FROM " + Tables.ACTIVITIES_JOIN_MIMETYPES +
3715                    " WHERE " + Tables.ACTIVITIES + "." + Activities._ID + "=?");
3716        }
3717        try {
3718            // Try database query to find mimetype
3719            DatabaseUtils.bindObjectToProgram(mActivitiesMimetypeQuery, 1, activityId);
3720            String mimetype = mActivitiesMimetypeQuery.simpleQueryForString();
3721            return mimetype;
3722        } catch (SQLiteDoneException e) {
3723            // No valid mapping found, so return null
3724            return null;
3725        }
3726    }
3727
3728    /**
3729     * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts.
3730     */
3731    public void updateAllVisible() {
3732        updateCustomContactVisibility(getWritableDatabase(), "");
3733    }
3734
3735    /**
3736     * Updates contact visibility and return true iff the visibility was actually changed.
3737     */
3738    public boolean updateContactVisibleOnlyIfChanged(TransactionContext txContext, long contactId) {
3739        return updateContactVisible(txContext, contactId, true);
3740    }
3741
3742    /**
3743     * Update {@link Contacts#IN_VISIBLE_GROUP} and
3744     * {@link Tables#DEFAULT_DIRECTORY} for a specific contact.
3745     */
3746    public void updateContactVisible(TransactionContext txContext, long contactId) {
3747        updateContactVisible(txContext, contactId, false);
3748    }
3749
3750    public boolean updateContactVisible(
3751            TransactionContext txContext, long contactId, boolean onlyIfChanged) {
3752        SQLiteDatabase db = getWritableDatabase();
3753        updateCustomContactVisibility(db, " AND " + Contacts._ID + "=" + contactId);
3754
3755        String contactIdAsString = String.valueOf(contactId);
3756        long mimetype = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3757
3758        // The contact will be included in the default directory if contains
3759        // a raw contact that is in any group or in an account that
3760        // does not have any AUTO_ADD groups.
3761        boolean newVisibility = DatabaseUtils.longForQuery(db,
3762                "SELECT EXISTS (" +
3763                    "SELECT " + RawContacts.CONTACT_ID +
3764                    " FROM " + Tables.RAW_CONTACTS +
3765                    " JOIN " + Tables.DATA +
3766                    "   ON (" + RawContactsColumns.CONCRETE_ID + "="
3767                            + Data.RAW_CONTACT_ID + ")" +
3768                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3769                    "   AND " + DataColumns.MIMETYPE_ID + "=?" +
3770                ") OR EXISTS (" +
3771                    "SELECT " + RawContacts._ID +
3772                    " FROM " + Tables.RAW_CONTACTS +
3773                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3774                    "   AND NOT EXISTS" +
3775                        " (SELECT " + Groups._ID +
3776                        "  FROM " + Tables.GROUPS +
3777                        "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
3778                                + GroupsColumns.CONCRETE_ACCOUNT_NAME +
3779                        "  AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
3780                                + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
3781                        "  AND (" + RawContactsColumns.CONCRETE_DATA_SET + " = "
3782                                + GroupsColumns.CONCRETE_DATA_SET
3783                                + " OR " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL AND "
3784                                + GroupsColumns.CONCRETE_DATA_SET + " IS NULL)" +
3785                        "  AND " + Groups.AUTO_ADD + " != 0" +
3786                        ")" +
3787                ") OR EXISTS (" +
3788                    "SELECT " + RawContacts._ID +
3789                    " FROM " + Tables.RAW_CONTACTS +
3790                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3791                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " +
3792                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL" +
3793                    "   AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL" +
3794                ")",
3795                new String[] {
3796                    contactIdAsString,
3797                    String.valueOf(mimetype),
3798                    contactIdAsString,
3799                    contactIdAsString
3800                }) != 0;
3801
3802        if (onlyIfChanged) {
3803            boolean oldVisibility = isContactInDefaultDirectory(db, contactId);
3804            if (oldVisibility == newVisibility) {
3805                return false;
3806            }
3807        }
3808
3809        if (newVisibility) {
3810            db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " VALUES(?)",
3811                    new String[] { contactIdAsString });
3812            txContext.invalidateSearchIndexForContact(contactId);
3813        } else {
3814            db.execSQL("DELETE FROM " + Tables.DEFAULT_DIRECTORY +
3815                        " WHERE " + Contacts._ID + "=?",
3816                    new String[] { contactIdAsString });
3817            db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX +
3818                        " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
3819                    new String[] { contactIdAsString });
3820        }
3821        return true;
3822    }
3823
3824    public boolean isContactInDefaultDirectory(SQLiteDatabase db, long contactId) {
3825        if (mContactInDefaultDirectoryQuery == null) {
3826            mContactInDefaultDirectoryQuery = db.compileStatement(
3827                    "SELECT EXISTS (" +
3828                            "SELECT 1 FROM " + Tables.DEFAULT_DIRECTORY +
3829                            " WHERE " + Contacts._ID + "=?)");
3830        }
3831        mContactInDefaultDirectoryQuery.bindLong(1, contactId);
3832        return mContactInDefaultDirectoryQuery.simpleQueryForLong() != 0;
3833    }
3834
3835    private void updateCustomContactVisibility(SQLiteDatabase db, String selection) {
3836        final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3837        String[] selectionArgs = new String[]{String.valueOf(groupMembershipMimetypeId)};
3838
3839        // First delete what needs to be deleted, then insert what needs to be added.
3840        // Since flash writes are very expensive, this approach is much better than
3841        // delete-all-insert-all.
3842        db.execSQL("DELETE FROM " + Tables.VISIBLE_CONTACTS +
3843                   " WHERE " + "_id NOT IN" +
3844                        "(SELECT " + Contacts._ID +
3845                        " FROM " + Tables.CONTACTS +
3846                        " WHERE (" + Clauses.CONTACT_IS_VISIBLE + ")=1) " + selection,
3847                selectionArgs);
3848
3849        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
3850                   " SELECT " + Contacts._ID +
3851                   " FROM " + Tables.CONTACTS +
3852                   " WHERE " + Contacts._ID +
3853                   " NOT IN " + Tables.VISIBLE_CONTACTS +
3854                           " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=1 " + selection,
3855                selectionArgs);
3856    }
3857
3858    /**
3859     * Returns contact ID for the given contact or zero if it is NULL.
3860     */
3861    public long getContactId(long rawContactId) {
3862        if (mContactIdQuery == null) {
3863            mContactIdQuery = getWritableDatabase().compileStatement(
3864                    "SELECT " + RawContacts.CONTACT_ID +
3865                    " FROM " + Tables.RAW_CONTACTS +
3866                    " WHERE " + RawContacts._ID + "=?");
3867        }
3868        try {
3869            DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId);
3870            return mContactIdQuery.simpleQueryForLong();
3871        } catch (SQLiteDoneException e) {
3872            // No valid mapping found, so return 0
3873            return 0;
3874        }
3875    }
3876
3877    public int getAggregationMode(long rawContactId) {
3878        if (mAggregationModeQuery == null) {
3879            mAggregationModeQuery = getWritableDatabase().compileStatement(
3880                    "SELECT " + RawContacts.AGGREGATION_MODE +
3881                    " FROM " + Tables.RAW_CONTACTS +
3882                    " WHERE " + RawContacts._ID + "=?");
3883        }
3884        try {
3885            DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId);
3886            return (int)mAggregationModeQuery.simpleQueryForLong();
3887        } catch (SQLiteDoneException e) {
3888            // No valid row found, so return "disabled"
3889            return RawContacts.AGGREGATION_MODE_DISABLED;
3890        }
3891    }
3892
3893    public void buildPhoneLookupAndContactQuery(
3894            SQLiteQueryBuilder qb, String normalizedNumber, String numberE164) {
3895        String minMatch = PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber);
3896        StringBuilder sb = new StringBuilder();
3897        appendPhoneLookupTables(sb, minMatch, true);
3898        qb.setTables(sb.toString());
3899
3900        sb = new StringBuilder();
3901        appendPhoneLookupSelection(sb, normalizedNumber, numberE164);
3902        qb.appendWhere(sb.toString());
3903    }
3904
3905    public String buildPhoneLookupAsNestedQuery(String number) {
3906        StringBuilder sb = new StringBuilder();
3907        final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
3908        sb.append("(SELECT DISTINCT raw_contact_id" + " FROM ");
3909        appendPhoneLookupTables(sb, minMatch, false);
3910        sb.append(" WHERE ");
3911        appendPhoneLookupSelection(sb, number, null);
3912        sb.append(")");
3913        return sb.toString();
3914    }
3915
3916    private void appendPhoneLookupTables(StringBuilder sb, final String minMatch,
3917            boolean joinContacts) {
3918        sb.append(Tables.RAW_CONTACTS);
3919        if (joinContacts) {
3920            sb.append(" JOIN " + Views.CONTACTS + " contacts_view"
3921                    + " ON (contacts_view._id = raw_contacts.contact_id)");
3922        }
3923        sb.append(", (SELECT data_id, normalized_number, length(normalized_number) as len "
3924                + " FROM phone_lookup " + " WHERE (" + Tables.PHONE_LOOKUP + "."
3925                + PhoneLookupColumns.MIN_MATCH + " = '");
3926        sb.append(minMatch);
3927        sb.append("')) AS lookup, " + Tables.DATA);
3928    }
3929
3930    private void appendPhoneLookupSelection(StringBuilder sb, String number, String numberE164) {
3931        sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id");
3932        boolean hasNumberE164 = !TextUtils.isEmpty(numberE164);
3933        boolean hasNumber = !TextUtils.isEmpty(number);
3934        if (hasNumberE164 || hasNumber) {
3935            sb.append(" AND ( ");
3936            if (hasNumberE164) {
3937                sb.append(" lookup.normalized_number = ");
3938                DatabaseUtils.appendEscapedSQLString(sb, numberE164);
3939            }
3940            if (hasNumberE164 && hasNumber) {
3941                sb.append(" OR ");
3942            }
3943            if (hasNumber) {
3944                int numberLen = number.length();
3945                sb.append(" lookup.len <= ");
3946                sb.append(numberLen);
3947                sb.append(" AND substr(");
3948                DatabaseUtils.appendEscapedSQLString(sb, number);
3949                sb.append(',');
3950                sb.append(numberLen);
3951                sb.append(" - lookup.len + 1) = lookup.normalized_number");
3952            }
3953            sb.append(')');
3954        }
3955    }
3956
3957    public String getUseStrictPhoneNumberComparisonParameter() {
3958        return mUseStrictPhoneNumberComparison ? "1" : "0";
3959    }
3960
3961    /**
3962     * Loads common nickname mappings into the database.
3963     */
3964    private void loadNicknameLookupTable(SQLiteDatabase db) {
3965        db.execSQL("DELETE FROM " + Tables.NICKNAME_LOOKUP);
3966
3967        String[] strings = mContext.getResources().getStringArray(
3968                com.android.internal.R.array.common_nicknames);
3969        if (strings == null || strings.length == 0) {
3970            return;
3971        }
3972
3973        SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO "
3974                + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + ","
3975                + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)");
3976
3977        try {
3978            for (int clusterId = 0; clusterId < strings.length; clusterId++) {
3979                String[] names = strings[clusterId].split(",");
3980                for (int j = 0; j < names.length; j++) {
3981                    String name = NameNormalizer.normalize(names[j]);
3982                    try {
3983                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name);
3984                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2,
3985                                String.valueOf(clusterId));
3986                        nicknameLookupInsert.executeInsert();
3987                    } catch (SQLiteException e) {
3988
3989                        // Print the exception and keep going - this is not a fatal error
3990                        Log.e(TAG, "Cannot insert nickname: " + names[j], e);
3991                    }
3992                }
3993            }
3994        } finally {
3995            nicknameLookupInsert.close();
3996        }
3997    }
3998
3999    public static void copyStringValue(ContentValues toValues, String toKey,
4000            ContentValues fromValues, String fromKey) {
4001        if (fromValues.containsKey(fromKey)) {
4002            toValues.put(toKey, fromValues.getAsString(fromKey));
4003        }
4004    }
4005
4006    public static void copyLongValue(ContentValues toValues, String toKey,
4007            ContentValues fromValues, String fromKey) {
4008        if (fromValues.containsKey(fromKey)) {
4009            long longValue;
4010            Object value = fromValues.get(fromKey);
4011            if (value instanceof Boolean) {
4012                if ((Boolean)value) {
4013                    longValue = 1;
4014                } else {
4015                    longValue = 0;
4016                }
4017            } else if (value instanceof String) {
4018                longValue = Long.parseLong((String)value);
4019            } else {
4020                longValue = ((Number)value).longValue();
4021            }
4022            toValues.put(toKey, longValue);
4023        }
4024    }
4025
4026    public SyncStateContentProviderHelper getSyncState() {
4027        return mSyncState;
4028    }
4029
4030    /**
4031     * Delete the aggregate contact if it has no constituent raw contacts other
4032     * than the supplied one.
4033     */
4034    public void removeContactIfSingleton(long rawContactId) {
4035        SQLiteDatabase db = getWritableDatabase();
4036
4037        // Obtain contact ID from the supplied raw contact ID
4038        String contactIdFromRawContactId = "(SELECT " + RawContacts.CONTACT_ID + " FROM "
4039                + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=" + rawContactId + ")";
4040
4041        // Find other raw contacts in the same aggregate contact
4042        String otherRawContacts = "(SELECT contacts1." + RawContacts._ID + " FROM "
4043                + Tables.RAW_CONTACTS + " contacts1 JOIN " + Tables.RAW_CONTACTS + " contacts2 ON ("
4044                + "contacts1." + RawContacts.CONTACT_ID + "=contacts2." + RawContacts.CONTACT_ID
4045                + ") WHERE contacts1." + RawContacts._ID + "!=" + rawContactId + ""
4046                + " AND contacts2." + RawContacts._ID + "=" + rawContactId + ")";
4047
4048        db.execSQL("DELETE FROM " + Tables.CONTACTS
4049                + " WHERE " + Contacts._ID + "=" + contactIdFromRawContactId
4050                + " AND NOT EXISTS " + otherRawContacts + ";");
4051    }
4052
4053    /**
4054     * Returns the value from the {@link Tables#PROPERTIES} table.
4055     */
4056    public String getProperty(String key, String defaultValue) {
4057        Cursor cursor = getReadableDatabase().query(Tables.PROPERTIES,
4058                new String[]{PropertiesColumns.PROPERTY_VALUE},
4059                PropertiesColumns.PROPERTY_KEY + "=?",
4060                new String[]{key}, null, null, null);
4061        String value = null;
4062        try {
4063            if (cursor.moveToFirst()) {
4064                value = cursor.getString(0);
4065            }
4066        } finally {
4067            cursor.close();
4068        }
4069
4070        return value != null ? value : defaultValue;
4071    }
4072
4073    /**
4074     * Stores a key-value pair in the {@link Tables#PROPERTIES} table.
4075     */
4076    public void setProperty(String key, String value) {
4077        setProperty(getWritableDatabase(), key, value);
4078    }
4079
4080    private void setProperty(SQLiteDatabase db, String key, String value) {
4081        ContentValues values = new ContentValues();
4082        values.put(PropertiesColumns.PROPERTY_KEY, key);
4083        values.put(PropertiesColumns.PROPERTY_VALUE, value);
4084        db.replace(Tables.PROPERTIES, null, values);
4085    }
4086
4087    /**
4088     * Test if any of the columns appear in the given projection.
4089     */
4090    public boolean isInProjection(String[] projection, String... columns) {
4091        if (projection == null) {
4092            return true;
4093        }
4094
4095        // Optimized for a single-column test
4096        if (columns.length == 1) {
4097            String column = columns[0];
4098            for (String test : projection) {
4099                if (column.equals(test)) {
4100                    return true;
4101                }
4102            }
4103        } else {
4104            for (String test : projection) {
4105                for (String column : columns) {
4106                    if (column.equals(test)) {
4107                        return true;
4108                    }
4109                }
4110            }
4111        }
4112        return false;
4113    }
4114
4115    /**
4116     * Returns a detailed exception message for the supplied URI.  It includes the calling
4117     * user and calling package(s).
4118     */
4119    public String exceptionMessage(Uri uri) {
4120        return exceptionMessage(null, uri);
4121    }
4122
4123    /**
4124     * Returns a detailed exception message for the supplied URI.  It includes the calling
4125     * user and calling package(s).
4126     */
4127    public String exceptionMessage(String message, Uri uri) {
4128        StringBuilder sb = new StringBuilder();
4129        if (message != null) {
4130            sb.append(message).append("; ");
4131        }
4132        sb.append("URI: ").append(uri);
4133        final PackageManager pm = mContext.getPackageManager();
4134        int callingUid = Binder.getCallingUid();
4135        sb.append(", calling user: ");
4136        String userName = pm.getNameForUid(callingUid);
4137        if (userName != null) {
4138            sb.append(userName);
4139        } else {
4140            sb.append(callingUid);
4141        }
4142
4143        final String[] callerPackages = pm.getPackagesForUid(callingUid);
4144        if (callerPackages != null && callerPackages.length > 0) {
4145            if (callerPackages.length == 1) {
4146                sb.append(", calling package:");
4147                sb.append(callerPackages[0]);
4148            } else {
4149                sb.append(", calling package is one of: [");
4150                for (int i = 0; i < callerPackages.length; i++) {
4151                    if (i != 0) {
4152                        sb.append(", ");
4153                    }
4154                    sb.append(callerPackages[i]);
4155                }
4156                sb.append("]");
4157            }
4158        }
4159
4160        return sb.toString();
4161    }
4162
4163    protected String getCountryIso() {
4164        CountryDetector detector =
4165            (CountryDetector) mContext.getSystemService(Context.COUNTRY_DETECTOR);
4166        return detector.detectCountry().getCountryIso();
4167    }
4168
4169    public void deleteStatusUpdate(long dataId) {
4170        if (mStatusUpdateDelete == null) {
4171            mStatusUpdateDelete = getWritableDatabase().compileStatement(
4172                    "DELETE FROM " + Tables.STATUS_UPDATES +
4173                    " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
4174        }
4175        mStatusUpdateDelete.bindLong(1, dataId);
4176        mStatusUpdateDelete.execute();
4177    }
4178
4179    public void replaceStatusUpdate(Long dataId, long timestamp, String status, String resPackage,
4180            Integer iconResource, Integer labelResource) {
4181        if (mStatusUpdateReplace == null) {
4182            mStatusUpdateReplace = getWritableDatabase().compileStatement(
4183                    "INSERT OR REPLACE INTO " + Tables.STATUS_UPDATES + "("
4184                            + StatusUpdatesColumns.DATA_ID + ", "
4185                            + StatusUpdates.STATUS_TIMESTAMP + ","
4186                            + StatusUpdates.STATUS + ","
4187                            + StatusUpdates.STATUS_RES_PACKAGE + ","
4188                            + StatusUpdates.STATUS_ICON + ","
4189                            + StatusUpdates.STATUS_LABEL + ")" +
4190                    " VALUES (?,?,?,?,?,?)");
4191        }
4192        mStatusUpdateReplace.bindLong(1, dataId);
4193        mStatusUpdateReplace.bindLong(2, timestamp);
4194        bindString(mStatusUpdateReplace, 3, status);
4195        bindString(mStatusUpdateReplace, 4, resPackage);
4196        bindLong(mStatusUpdateReplace, 5, iconResource);
4197        bindLong(mStatusUpdateReplace, 6, labelResource);
4198        mStatusUpdateReplace.execute();
4199    }
4200
4201    public void insertStatusUpdate(Long dataId, String status, String resPackage,
4202            Integer iconResource, Integer labelResource) {
4203        if (mStatusUpdateInsert == null) {
4204            mStatusUpdateInsert = getWritableDatabase().compileStatement(
4205                    "INSERT INTO " + Tables.STATUS_UPDATES + "("
4206                            + StatusUpdatesColumns.DATA_ID + ", "
4207                            + StatusUpdates.STATUS + ","
4208                            + StatusUpdates.STATUS_RES_PACKAGE + ","
4209                            + StatusUpdates.STATUS_ICON + ","
4210                            + StatusUpdates.STATUS_LABEL + ")" +
4211                    " VALUES (?,?,?,?,?)");
4212        }
4213        try {
4214            mStatusUpdateInsert.bindLong(1, dataId);
4215            bindString(mStatusUpdateInsert, 2, status);
4216            bindString(mStatusUpdateInsert, 3, resPackage);
4217            bindLong(mStatusUpdateInsert, 4, iconResource);
4218            bindLong(mStatusUpdateInsert, 5, labelResource);
4219            mStatusUpdateInsert.executeInsert();
4220        } catch (SQLiteConstraintException e) {
4221            // The row already exists - update it
4222            if (mStatusUpdateAutoTimestamp == null) {
4223                mStatusUpdateAutoTimestamp = getWritableDatabase().compileStatement(
4224                        "UPDATE " + Tables.STATUS_UPDATES +
4225                        " SET " + StatusUpdates.STATUS_TIMESTAMP + "=?,"
4226                                + StatusUpdates.STATUS + "=?" +
4227                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"
4228                                + " AND " + StatusUpdates.STATUS + "!=?");
4229            }
4230
4231            long timestamp = System.currentTimeMillis();
4232            mStatusUpdateAutoTimestamp.bindLong(1, timestamp);
4233            bindString(mStatusUpdateAutoTimestamp, 2, status);
4234            mStatusUpdateAutoTimestamp.bindLong(3, dataId);
4235            bindString(mStatusUpdateAutoTimestamp, 4, status);
4236            mStatusUpdateAutoTimestamp.execute();
4237
4238            if (mStatusAttributionUpdate == null) {
4239                mStatusAttributionUpdate = getWritableDatabase().compileStatement(
4240                        "UPDATE " + Tables.STATUS_UPDATES +
4241                        " SET " + StatusUpdates.STATUS_RES_PACKAGE + "=?,"
4242                                + StatusUpdates.STATUS_ICON + "=?,"
4243                                + StatusUpdates.STATUS_LABEL + "=?" +
4244                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
4245            }
4246            bindString(mStatusAttributionUpdate, 1, resPackage);
4247            bindLong(mStatusAttributionUpdate, 2, iconResource);
4248            bindLong(mStatusAttributionUpdate, 3, labelResource);
4249            mStatusAttributionUpdate.bindLong(4, dataId);
4250            mStatusAttributionUpdate.execute();
4251        }
4252    }
4253
4254    /**
4255     * Resets the {@link RawContacts#NAME_VERIFIED} flag to 0 on all other raw
4256     * contacts in the same aggregate
4257     */
4258    public void resetNameVerifiedForOtherRawContacts(long rawContactId) {
4259        if (mResetNameVerifiedForOtherRawContacts == null) {
4260            mResetNameVerifiedForOtherRawContacts = getWritableDatabase().compileStatement(
4261                    "UPDATE " + Tables.RAW_CONTACTS +
4262                    " SET " + RawContacts.NAME_VERIFIED + "=0" +
4263                    " WHERE " + RawContacts.CONTACT_ID + "=(" +
4264                            "SELECT " + RawContacts.CONTACT_ID +
4265                            " FROM " + Tables.RAW_CONTACTS +
4266                            " WHERE " + RawContacts._ID + "=?)" +
4267                    " AND " + RawContacts._ID + "!=?");
4268        }
4269        mResetNameVerifiedForOtherRawContacts.bindLong(1, rawContactId);
4270        mResetNameVerifiedForOtherRawContacts.bindLong(2, rawContactId);
4271        mResetNameVerifiedForOtherRawContacts.execute();
4272    }
4273
4274    private interface RawContactNameQuery {
4275        public static final String RAW_SQL =
4276                "SELECT "
4277                        + DataColumns.MIMETYPE_ID + ","
4278                        + Data.IS_PRIMARY + ","
4279                        + Data.DATA1 + ","
4280                        + Data.DATA2 + ","
4281                        + Data.DATA3 + ","
4282                        + Data.DATA4 + ","
4283                        + Data.DATA5 + ","
4284                        + Data.DATA6 + ","
4285                        + Data.DATA7 + ","
4286                        + Data.DATA8 + ","
4287                        + Data.DATA9 + ","
4288                        + Data.DATA10 + ","
4289                        + Data.DATA11 +
4290                " FROM " + Tables.DATA +
4291                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
4292                        " AND (" + Data.DATA1 + " NOT NULL OR " +
4293                                Organization.TITLE + " NOT NULL)";
4294
4295        public static final int MIMETYPE = 0;
4296        public static final int IS_PRIMARY = 1;
4297        public static final int DATA1 = 2;
4298        public static final int GIVEN_NAME = 3;                         // data2
4299        public static final int FAMILY_NAME = 4;                        // data3
4300        public static final int PREFIX = 5;                             // data4
4301        public static final int TITLE = 5;                              // data4
4302        public static final int MIDDLE_NAME = 6;                        // data5
4303        public static final int SUFFIX = 7;                             // data6
4304        public static final int PHONETIC_GIVEN_NAME = 8;                // data7
4305        public static final int PHONETIC_MIDDLE_NAME = 9;               // data8
4306        public static final int ORGANIZATION_PHONETIC_NAME = 9;         // data8
4307        public static final int PHONETIC_FAMILY_NAME = 10;              // data9
4308        public static final int FULL_NAME_STYLE = 11;                   // data10
4309        public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11;  // data10
4310        public static final int PHONETIC_NAME_STYLE = 12;               // data11
4311    }
4312
4313    /**
4314     * Updates a raw contact display name based on data rows, e.g. structured name,
4315     * organization, email etc.
4316     */
4317    public void updateRawContactDisplayName(SQLiteDatabase db, long rawContactId) {
4318        if (mNameSplitter == null) {
4319            createNameSplitter();
4320        }
4321
4322        int bestDisplayNameSource = DisplayNameSources.UNDEFINED;
4323        NameSplitter.Name bestName = null;
4324        String bestDisplayName = null;
4325        String bestPhoneticName = null;
4326        int bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4327
4328        mSelectionArgs1[0] = String.valueOf(rawContactId);
4329        Cursor c = db.rawQuery(RawContactNameQuery.RAW_SQL, mSelectionArgs1);
4330        try {
4331            while (c.moveToNext()) {
4332                int mimeType = c.getInt(RawContactNameQuery.MIMETYPE);
4333                int source = getDisplayNameSourceForMimeTypeId(mimeType);
4334                if (source < bestDisplayNameSource || source == DisplayNameSources.UNDEFINED) {
4335                    continue;
4336                }
4337
4338                if (source == bestDisplayNameSource
4339                        && c.getInt(RawContactNameQuery.IS_PRIMARY) == 0) {
4340                    continue;
4341                }
4342
4343                if (mimeType == getMimeTypeIdForStructuredName()) {
4344                    NameSplitter.Name name;
4345                    if (bestName != null) {
4346                        name = new NameSplitter.Name();
4347                    } else {
4348                        name = mName;
4349                        name.clear();
4350                    }
4351                    name.prefix = c.getString(RawContactNameQuery.PREFIX);
4352                    name.givenNames = c.getString(RawContactNameQuery.GIVEN_NAME);
4353                    name.middleName = c.getString(RawContactNameQuery.MIDDLE_NAME);
4354                    name.familyName = c.getString(RawContactNameQuery.FAMILY_NAME);
4355                    name.suffix = c.getString(RawContactNameQuery.SUFFIX);
4356                    name.fullNameStyle = c.isNull(RawContactNameQuery.FULL_NAME_STYLE)
4357                            ? FullNameStyle.UNDEFINED
4358                            : c.getInt(RawContactNameQuery.FULL_NAME_STYLE);
4359                    name.phoneticFamilyName = c.getString(RawContactNameQuery.PHONETIC_FAMILY_NAME);
4360                    name.phoneticMiddleName = c.getString(RawContactNameQuery.PHONETIC_MIDDLE_NAME);
4361                    name.phoneticGivenName = c.getString(RawContactNameQuery.PHONETIC_GIVEN_NAME);
4362                    name.phoneticNameStyle = c.isNull(RawContactNameQuery.PHONETIC_NAME_STYLE)
4363                            ? PhoneticNameStyle.UNDEFINED
4364                            : c.getInt(RawContactNameQuery.PHONETIC_NAME_STYLE);
4365                    if (!name.isEmpty()) {
4366                        bestDisplayNameSource = source;
4367                        bestName = name;
4368                    }
4369                } else if (mimeType == getMimeTypeIdForOrganization()) {
4370                    mCharArrayBuffer.sizeCopied = 0;
4371                    c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer);
4372                    if (mCharArrayBuffer.sizeCopied != 0) {
4373                        bestDisplayNameSource = source;
4374                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
4375                                mCharArrayBuffer.sizeCopied);
4376                        bestPhoneticName = c.getString(
4377                                RawContactNameQuery.ORGANIZATION_PHONETIC_NAME);
4378                        bestPhoneticNameStyle =
4379                                c.isNull(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE)
4380                                   ? PhoneticNameStyle.UNDEFINED
4381                                   : c.getInt(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE);
4382                    } else {
4383                        c.copyStringToBuffer(RawContactNameQuery.TITLE, mCharArrayBuffer);
4384                        if (mCharArrayBuffer.sizeCopied != 0) {
4385                            bestDisplayNameSource = source;
4386                            bestDisplayName = new String(mCharArrayBuffer.data, 0,
4387                                    mCharArrayBuffer.sizeCopied);
4388                            bestPhoneticName = null;
4389                            bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4390                        }
4391                    }
4392                } else {
4393                    // Display name is at DATA1 in all other types.
4394                    // This is ensured in the constructor.
4395
4396                    mCharArrayBuffer.sizeCopied = 0;
4397                    c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer);
4398                    if (mCharArrayBuffer.sizeCopied != 0) {
4399                        bestDisplayNameSource = source;
4400                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
4401                                mCharArrayBuffer.sizeCopied);
4402                        bestPhoneticName = null;
4403                        bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4404                    }
4405                }
4406            }
4407
4408        } finally {
4409            c.close();
4410        }
4411
4412        String displayNamePrimary;
4413        String displayNameAlternative;
4414        String sortNamePrimary;
4415        String sortNameAlternative;
4416        String sortKeyPrimary = null;
4417        String sortKeyAlternative = null;
4418        int displayNameStyle = FullNameStyle.UNDEFINED;
4419
4420        if (bestDisplayNameSource == DisplayNameSources.STRUCTURED_NAME) {
4421            displayNameStyle = bestName.fullNameStyle;
4422            if (displayNameStyle == FullNameStyle.CJK
4423                    || displayNameStyle == FullNameStyle.UNDEFINED) {
4424                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
4425                bestName.fullNameStyle = displayNameStyle;
4426            }
4427
4428            displayNamePrimary = mNameSplitter.join(bestName, true, true);
4429            displayNameAlternative = mNameSplitter.join(bestName, false, true);
4430
4431            if (TextUtils.isEmpty(bestName.prefix)) {
4432                sortNamePrimary = displayNamePrimary;
4433                sortNameAlternative = displayNameAlternative;
4434            } else {
4435                sortNamePrimary = mNameSplitter.join(bestName, true, false);
4436                sortNameAlternative = mNameSplitter.join(bestName, false, false);
4437            }
4438
4439            bestPhoneticName = mNameSplitter.joinPhoneticName(bestName);
4440            bestPhoneticNameStyle = bestName.phoneticNameStyle;
4441        } else {
4442            displayNamePrimary = displayNameAlternative = bestDisplayName;
4443            sortNamePrimary = sortNameAlternative = bestDisplayName;
4444        }
4445
4446        if (bestPhoneticName != null) {
4447            sortKeyPrimary = sortKeyAlternative = bestPhoneticName;
4448            if (bestPhoneticNameStyle == PhoneticNameStyle.UNDEFINED) {
4449                bestPhoneticNameStyle = mNameSplitter.guessPhoneticNameStyle(bestPhoneticName);
4450            }
4451        } else {
4452            if (displayNameStyle == FullNameStyle.UNDEFINED) {
4453                displayNameStyle = mNameSplitter.guessFullNameStyle(bestDisplayName);
4454                if (displayNameStyle == FullNameStyle.UNDEFINED
4455                        || displayNameStyle == FullNameStyle.CJK) {
4456                    displayNameStyle = mNameSplitter.getAdjustedNameStyleBasedOnPhoneticNameStyle(
4457                            displayNameStyle, bestPhoneticNameStyle);
4458                }
4459                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
4460            }
4461            if (displayNameStyle == FullNameStyle.CHINESE ||
4462                    displayNameStyle == FullNameStyle.CJK) {
4463                sortKeyPrimary = sortKeyAlternative =
4464                        ContactLocaleUtils.getIntance().getSortKey(
4465                                sortNamePrimary, displayNameStyle);
4466            }
4467        }
4468
4469        if (sortKeyPrimary == null) {
4470            sortKeyPrimary = sortNamePrimary;
4471            sortKeyAlternative = sortNameAlternative;
4472        }
4473
4474        if (mRawContactDisplayNameUpdate == null) {
4475            mRawContactDisplayNameUpdate = db.compileStatement(
4476                    "UPDATE " + Tables.RAW_CONTACTS +
4477                    " SET " +
4478                            RawContacts.DISPLAY_NAME_SOURCE + "=?," +
4479                            RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
4480                            RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
4481                            RawContacts.PHONETIC_NAME + "=?," +
4482                            RawContacts.PHONETIC_NAME_STYLE + "=?," +
4483                            RawContacts.SORT_KEY_PRIMARY + "=?," +
4484                            RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
4485                    " WHERE " + RawContacts._ID + "=?");
4486        }
4487
4488        mRawContactDisplayNameUpdate.bindLong(1, bestDisplayNameSource);
4489        bindString(mRawContactDisplayNameUpdate, 2, displayNamePrimary);
4490        bindString(mRawContactDisplayNameUpdate, 3, displayNameAlternative);
4491        bindString(mRawContactDisplayNameUpdate, 4, bestPhoneticName);
4492        mRawContactDisplayNameUpdate.bindLong(5, bestPhoneticNameStyle);
4493        bindString(mRawContactDisplayNameUpdate, 6, sortKeyPrimary);
4494        bindString(mRawContactDisplayNameUpdate, 7, sortKeyAlternative);
4495        mRawContactDisplayNameUpdate.bindLong(8, rawContactId);
4496        mRawContactDisplayNameUpdate.execute();
4497    }
4498
4499    /*
4500     * Sets the given dataId record in the "data" table to primary, and resets all data records of
4501     * the same mimetype and under the same contact to not be primary.
4502     *
4503     * @param dataId the id of the data record to be set to primary. Pass -1 to clear the primary
4504     * flag of all data items of this raw contacts
4505     */
4506    public void setIsPrimary(long rawContactId, long dataId, long mimeTypeId) {
4507        if (mSetPrimaryStatement == null) {
4508            mSetPrimaryStatement = getWritableDatabase().compileStatement(
4509                    "UPDATE " + Tables.DATA +
4510                    " SET " + Data.IS_PRIMARY + "=(_id=?)" +
4511                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4512                    "   AND " + Data.RAW_CONTACT_ID + "=?");
4513        }
4514        mSetPrimaryStatement.bindLong(1, dataId);
4515        mSetPrimaryStatement.bindLong(2, mimeTypeId);
4516        mSetPrimaryStatement.bindLong(3, rawContactId);
4517        mSetPrimaryStatement.execute();
4518    }
4519
4520    /*
4521     * Clears the super primary of all data items of the given raw contact. does not touch
4522     * other raw contacts of the same joined aggregate
4523     */
4524    public void clearSuperPrimary(long rawContactId, long mimeTypeId) {
4525        if (mClearSuperPrimaryStatement == null) {
4526            mClearSuperPrimaryStatement = getWritableDatabase().compileStatement(
4527                    "UPDATE " + Tables.DATA +
4528                    " SET " + Data.IS_SUPER_PRIMARY + "=0" +
4529                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4530                    "   AND " + Data.RAW_CONTACT_ID + "=?");
4531        }
4532        mClearSuperPrimaryStatement.bindLong(1, mimeTypeId);
4533        mClearSuperPrimaryStatement.bindLong(2, rawContactId);
4534        mClearSuperPrimaryStatement.execute();
4535    }
4536
4537    /*
4538     * Sets the given dataId record in the "data" table to "super primary", and resets all data
4539     * records of the same mimetype and under the same aggregate to not be "super primary".
4540     *
4541     * @param dataId the id of the data record to be set to primary.
4542     */
4543    public void setIsSuperPrimary(long rawContactId, long dataId, long mimeTypeId) {
4544        if (mSetSuperPrimaryStatement == null) {
4545            mSetSuperPrimaryStatement = getWritableDatabase().compileStatement(
4546                    "UPDATE " + Tables.DATA +
4547                    " SET " + Data.IS_SUPER_PRIMARY + "=(" + Data._ID + "=?)" +
4548                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4549                    "   AND " + Data.RAW_CONTACT_ID + " IN (" +
4550                            "SELECT " + RawContacts._ID +
4551                            " FROM " + Tables.RAW_CONTACTS +
4552                            " WHERE " + RawContacts.CONTACT_ID + " =(" +
4553                                    "SELECT " + RawContacts.CONTACT_ID +
4554                                    " FROM " + Tables.RAW_CONTACTS +
4555                                    " WHERE " + RawContacts._ID + "=?))");
4556        }
4557        mSetSuperPrimaryStatement.bindLong(1, dataId);
4558        mSetSuperPrimaryStatement.bindLong(2, mimeTypeId);
4559        mSetSuperPrimaryStatement.bindLong(3, rawContactId);
4560        mSetSuperPrimaryStatement.execute();
4561    }
4562
4563    /**
4564     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
4565     */
4566    public void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) {
4567        if (TextUtils.isEmpty(name)) {
4568            return;
4569        }
4570
4571        if (mNameLookupInsert == null) {
4572            mNameLookupInsert = getWritableDatabase().compileStatement(
4573                    "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
4574                            + NameLookupColumns.RAW_CONTACT_ID + ","
4575                            + NameLookupColumns.DATA_ID + ","
4576                            + NameLookupColumns.NAME_TYPE + ","
4577                            + NameLookupColumns.NORMALIZED_NAME
4578                    + ") VALUES (?,?,?,?)");
4579        }
4580        mNameLookupInsert.bindLong(1, rawContactId);
4581        mNameLookupInsert.bindLong(2, dataId);
4582        mNameLookupInsert.bindLong(3, lookupType);
4583        bindString(mNameLookupInsert, 4, name);
4584        mNameLookupInsert.executeInsert();
4585    }
4586
4587    /**
4588     * Deletes all {@link Tables#NAME_LOOKUP} table rows associated with the specified data element.
4589     */
4590    public void deleteNameLookup(long dataId) {
4591        if (mNameLookupDelete == null) {
4592            mNameLookupDelete = getWritableDatabase().compileStatement(
4593                    "DELETE FROM " + Tables.NAME_LOOKUP +
4594                    " WHERE " + NameLookupColumns.DATA_ID + "=?");
4595        }
4596        mNameLookupDelete.bindLong(1, dataId);
4597        mNameLookupDelete.execute();
4598    }
4599
4600    public String insertNameLookupForEmail(long rawContactId, long dataId, String email) {
4601        if (TextUtils.isEmpty(email)) {
4602            return null;
4603        }
4604
4605        String address = extractHandleFromEmailAddress(email);
4606        if (address == null) {
4607            return null;
4608        }
4609
4610        insertNameLookup(rawContactId, dataId,
4611                NameLookupType.EMAIL_BASED_NICKNAME, NameNormalizer.normalize(address));
4612        return address;
4613    }
4614
4615    /**
4616     * Normalizes the nickname and inserts it in the name lookup table.
4617     */
4618    public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) {
4619        if (TextUtils.isEmpty(nickname)) {
4620            return;
4621        }
4622
4623        insertNameLookup(rawContactId, dataId,
4624                NameLookupType.NICKNAME, NameNormalizer.normalize(nickname));
4625    }
4626
4627    public void insertNameLookupForPhoneticName(long rawContactId, long dataId, String familyName,
4628            String middleName, String givenName) {
4629        mSb.setLength(0);
4630        if (familyName != null) {
4631            mSb.append(familyName.trim());
4632        }
4633        if (middleName != null) {
4634            mSb.append(middleName.trim());
4635        }
4636        if (givenName != null) {
4637            mSb.append(givenName.trim());
4638        }
4639
4640        if (mSb.length() > 0) {
4641            insertNameLookup(rawContactId, dataId, NameLookupType.NAME_COLLATION_KEY,
4642                    NameNormalizer.normalize(mSb.toString()));
4643        }
4644    }
4645
4646    /**
4647     * Performs a query and returns true if any Data item of the raw contact with the given
4648     * id and mimetype is marked as super-primary
4649     */
4650    public boolean rawContactHasSuperPrimary(long rawContactId, long mimeTypeId) {
4651        final Cursor existsCursor = getReadableDatabase().rawQuery(
4652                "SELECT EXISTS(SELECT 1 FROM " + Tables.DATA +
4653                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
4654                " AND " + DataColumns.MIMETYPE_ID + "=?" +
4655                " AND " + Data.IS_SUPER_PRIMARY + "<>0)",
4656                new String[] { String.valueOf(rawContactId), String.valueOf(mimeTypeId) });
4657        try {
4658            if (!existsCursor.moveToFirst()) throw new IllegalStateException();
4659            return existsCursor.getInt(0) != 0;
4660        } finally {
4661            existsCursor.close();
4662        }
4663    }
4664
4665    public String getCurrentCountryIso() {
4666        return mCountryMonitor.getCountryIso();
4667    }
4668
4669    /* package */ String querySearchIndexContentForTest(long contactId) {
4670        return DatabaseUtils.stringForQuery(getReadableDatabase(),
4671                "SELECT " + SearchIndexColumns.CONTENT +
4672                " FROM " + Tables.SEARCH_INDEX +
4673                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
4674                new String[] { String.valueOf(contactId) });
4675    }
4676
4677    /* package */ String querySearchIndexTokensForTest(long contactId) {
4678        return DatabaseUtils.stringForQuery(getReadableDatabase(),
4679                "SELECT " + SearchIndexColumns.TOKENS +
4680                " FROM " + Tables.SEARCH_INDEX +
4681                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
4682                new String[] { String.valueOf(contactId) });
4683    }
4684}
4685