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