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