ContactsDatabaseHelper.java revision aeaba441ddb05dede8bd86291ca78f42d670d54c
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 = 612;
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                Calls.GEOCODED_LOCATION + " TEXT," +
1158                Voicemails._DATA + " TEXT," +
1159                Voicemails.HAS_CONTENT + " INTEGER," +
1160                Voicemails.MIME_TYPE + " TEXT," +
1161                Voicemails.SOURCE_DATA + " TEXT," +
1162                Voicemails.SOURCE_PACKAGE + " TEXT," +
1163                Voicemails.STATE + " INTEGER" +
1164        ");");
1165
1166        // Voicemail source status table.
1167        db.execSQL("CREATE TABLE " + Tables.VOICEMAIL_STATUS + " (" +
1168                VoicemailContract.Status._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1169                VoicemailContract.Status.SOURCE_PACKAGE + " TEXT UNIQUE NOT NULL," +
1170                VoicemailContract.Status.SETTINGS_URI + " TEXT," +
1171                VoicemailContract.Status.VOICEMAIL_ACCESS_URI + " TEXT," +
1172                VoicemailContract.Status.CONFIGURATION_STATE + " INTEGER," +
1173                VoicemailContract.Status.DATA_CHANNEL_STATE + " INTEGER," +
1174                VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE + " INTEGER" +
1175        ");");
1176
1177        // Activities table
1178        db.execSQL("CREATE TABLE " + Tables.ACTIVITIES + " (" +
1179                Activities._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1180                ActivitiesColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
1181                ActivitiesColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
1182                Activities.RAW_ID + " TEXT," +
1183                Activities.IN_REPLY_TO + " TEXT," +
1184                Activities.AUTHOR_CONTACT_ID +  " INTEGER REFERENCES raw_contacts(_id)," +
1185                Activities.TARGET_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
1186                Activities.PUBLISHED + " INTEGER NOT NULL," +
1187                Activities.THREAD_PUBLISHED + " INTEGER NOT NULL," +
1188                Activities.TITLE + " TEXT NOT NULL," +
1189                Activities.SUMMARY + " TEXT," +
1190                Activities.LINK + " TEXT, " +
1191                Activities.THUMBNAIL + " BLOB" +
1192        ");");
1193
1194        db.execSQL("CREATE TABLE " + Tables.STATUS_UPDATES + " (" +
1195                StatusUpdatesColumns.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
1196                StatusUpdates.STATUS + " TEXT," +
1197                StatusUpdates.STATUS_TIMESTAMP + " INTEGER," +
1198                StatusUpdates.STATUS_RES_PACKAGE + " TEXT, " +
1199                StatusUpdates.STATUS_LABEL + " INTEGER, " +
1200                StatusUpdates.STATUS_ICON + " INTEGER" +
1201        ");");
1202
1203        db.execSQL("CREATE TABLE " + Tables.PROPERTIES + " (" +
1204                PropertiesColumns.PROPERTY_KEY + " TEXT PRIMARY KEY, " +
1205                PropertiesColumns.PROPERTY_VALUE + " TEXT " +
1206        ");");
1207
1208        db.execSQL("CREATE TABLE " + Tables.ACCOUNTS + " (" +
1209                AccountsColumns.ACCOUNT_NAME + " TEXT, " +
1210                AccountsColumns.ACCOUNT_TYPE + " TEXT, " +
1211                AccountsColumns.DATA_SET + " TEXT, " +
1212                AccountsColumns.PROFILE_RAW_CONTACT_ID + " INTEGER" +
1213        ");");
1214
1215        db.execSQL("CREATE INDEX accounts_profile_raw_contact_id_index ON " +
1216                Tables.ACCOUNTS + " (" +
1217                AccountsColumns.PROFILE_RAW_CONTACT_ID +
1218        ");");
1219
1220        // Allow contacts without any account to be created for now.  Achieve that
1221        // by inserting a fake account with both type and name as NULL.
1222        db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL, NULL, NULL)");
1223
1224        createDirectoriesTable(db);
1225        createSearchIndexTable(db);
1226
1227        db.execSQL("CREATE TABLE " + Tables.DATA_USAGE_STAT + "(" +
1228                DataUsageStatColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
1229                DataUsageStatColumns.DATA_ID + " INTEGER NOT NULL, " +
1230                DataUsageStatColumns.USAGE_TYPE_INT + " INTEGER NOT NULL DEFAULT 0, " +
1231                DataUsageStatColumns.TIMES_USED + " INTEGER NOT NULL DEFAULT 0, " +
1232                DataUsageStatColumns.LAST_TIME_USED + " INTERGER NOT NULL DEFAULT 0, " +
1233                "FOREIGN KEY(" + DataUsageStatColumns.DATA_ID + ") REFERENCES "
1234                        + Tables.DATA + "(" + Data._ID + ")" +
1235        ");");
1236        db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " +
1237                Tables.DATA_USAGE_STAT + " (" +
1238                DataUsageStatColumns.DATA_ID + ", " +
1239                DataUsageStatColumns.USAGE_TYPE_INT +
1240        ");");
1241
1242        createContactsViews(db);
1243        createGroupsView(db);
1244        createContactsTriggers(db);
1245        createContactsIndexes(db);
1246
1247        loadNicknameLookupTable(db);
1248
1249        // Add the legacy API support views, etc
1250        LegacyApiSupport.createDatabase(db);
1251
1252        if (mDatabaseOptimizationEnabled) {
1253            // This will create a sqlite_stat1 table that is used for query optimization
1254            db.execSQL("ANALYZE;");
1255
1256            updateSqliteStats(db);
1257
1258            // We need to close and reopen the database connection so that the stats are
1259            // taken into account. Make a note of it and do the actual reopening in the
1260            // getWritableDatabase method.
1261            mReopenDatabase = true;
1262        }
1263
1264        ContentResolver.requestSync(null /* all accounts */,
1265                ContactsContract.AUTHORITY, new Bundle());
1266    }
1267
1268    private void createDirectoriesTable(SQLiteDatabase db) {
1269        db.execSQL("CREATE TABLE " + Tables.DIRECTORIES + "(" +
1270                Directory._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
1271                Directory.PACKAGE_NAME + " TEXT NOT NULL," +
1272                Directory.DIRECTORY_AUTHORITY + " TEXT NOT NULL," +
1273                Directory.TYPE_RESOURCE_ID + " INTEGER," +
1274                DirectoryColumns.TYPE_RESOURCE_NAME + " TEXT," +
1275                Directory.ACCOUNT_TYPE + " TEXT," +
1276                Directory.ACCOUNT_NAME + " TEXT," +
1277                Directory.DISPLAY_NAME + " TEXT, " +
1278                Directory.EXPORT_SUPPORT + " INTEGER NOT NULL" +
1279                        " DEFAULT " + Directory.EXPORT_SUPPORT_NONE + "," +
1280                Directory.SHORTCUT_SUPPORT + " INTEGER NOT NULL" +
1281                        " DEFAULT " + Directory.SHORTCUT_SUPPORT_NONE + "," +
1282                Directory.PHOTO_SUPPORT + " INTEGER NOT NULL" +
1283                        " DEFAULT " + Directory.PHOTO_SUPPORT_NONE +
1284        ");");
1285
1286        // Trigger a full scan of directories in the system
1287        setProperty(db, ContactDirectoryManager.PROPERTY_DIRECTORY_SCAN_COMPLETE, "0");
1288    }
1289
1290    public void createSearchIndexTable(SQLiteDatabase db) {
1291        db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_INDEX);
1292        db.execSQL("CREATE VIRTUAL TABLE " + Tables.SEARCH_INDEX
1293                + " USING FTS4 ("
1294                    + SearchIndexColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id) NOT NULL,"
1295                    + SearchIndexColumns.CONTENT + " TEXT, "
1296                    + SearchIndexColumns.NAME + " TEXT, "
1297                    + SearchIndexColumns.TOKENS + " TEXT"
1298                + ")");
1299    }
1300
1301    private static void createContactsTriggers(SQLiteDatabase db) {
1302
1303        /*
1304         * Automatically delete Data rows when a raw contact is deleted.
1305         */
1306        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;");
1307        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted "
1308                + "   BEFORE DELETE ON " + Tables.RAW_CONTACTS
1309                + " BEGIN "
1310                + "   DELETE FROM " + Tables.DATA
1311                + "     WHERE " + Data.RAW_CONTACT_ID
1312                                + "=OLD." + RawContacts._ID + ";"
1313                + "   DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS
1314                + "     WHERE " + AggregationExceptions.RAW_CONTACT_ID1
1315                                + "=OLD." + RawContacts._ID
1316                + "        OR " + AggregationExceptions.RAW_CONTACT_ID2
1317                                + "=OLD." + RawContacts._ID + ";"
1318                + "   DELETE FROM " + Tables.VISIBLE_CONTACTS
1319                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1320                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1321                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1322                + "           )=1;"
1323                + "   DELETE FROM " + Tables.DEFAULT_DIRECTORY
1324                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1325                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1326                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1327                + "           )=1;"
1328                + "   DELETE FROM " + Tables.CONTACTS
1329                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
1330                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
1331                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
1332                + "           )=1;"
1333                + " END");
1334
1335
1336        db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;");
1337        db.execSQL("DROP TRIGGER IF EXISTS raw_contacts_times_contacted;");
1338
1339        /*
1340         * Triggers that update {@link RawContacts#VERSION} when the contact is
1341         * marked for deletion or any time a data row is inserted, updated or
1342         * deleted.
1343         */
1344        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;");
1345        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted "
1346                + "   AFTER UPDATE ON " + Tables.RAW_CONTACTS
1347                + " BEGIN "
1348                + "   UPDATE " + Tables.RAW_CONTACTS
1349                + "     SET "
1350                +         RawContacts.VERSION + "=OLD." + RawContacts.VERSION + "+1 "
1351                + "     WHERE " + RawContacts._ID + "=OLD." + RawContacts._ID
1352                + "       AND NEW." + RawContacts.DELETED + "!= OLD." + RawContacts.DELETED + ";"
1353                + " END");
1354
1355        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_updated;");
1356        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_updated AFTER UPDATE ON " + Tables.DATA
1357                + " BEGIN "
1358                + "   UPDATE " + Tables.DATA
1359                + "     SET " + Data.DATA_VERSION + "=OLD." + Data.DATA_VERSION + "+1 "
1360                + "     WHERE " + Data._ID + "=OLD." + Data._ID + ";"
1361                + "   UPDATE " + Tables.RAW_CONTACTS
1362                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
1363                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
1364                + " END");
1365
1366        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_deleted;");
1367        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_deleted BEFORE DELETE ON " + Tables.DATA
1368                + " BEGIN "
1369                + "   UPDATE " + Tables.RAW_CONTACTS
1370                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
1371                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
1372                + "   DELETE FROM " + Tables.PHONE_LOOKUP
1373                + "     WHERE " + PhoneLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1374                + "   DELETE FROM " + Tables.STATUS_UPDATES
1375                + "     WHERE " + StatusUpdatesColumns.DATA_ID + "=OLD." + Data._ID + ";"
1376                + "   DELETE FROM " + Tables.NAME_LOOKUP
1377                + "     WHERE " + NameLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1378                + " END");
1379
1380
1381        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_updated1;");
1382        db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_updated1 "
1383                + "   AFTER UPDATE ON " + Tables.GROUPS
1384                + " BEGIN "
1385                + "   UPDATE " + Tables.GROUPS
1386                + "     SET "
1387                +         Groups.VERSION + "=OLD." + Groups.VERSION + "+1"
1388                + "     WHERE " + Groups._ID + "=OLD." + Groups._ID + ";"
1389                + " END");
1390    }
1391
1392    private static void createContactsIndexes(SQLiteDatabase db) {
1393        db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
1394        db.execSQL("CREATE INDEX name_lookup_index ON " + Tables.NAME_LOOKUP + " (" +
1395                NameLookupColumns.NORMALIZED_NAME + "," +
1396                NameLookupColumns.NAME_TYPE + ", " +
1397                NameLookupColumns.RAW_CONTACT_ID + ", " +
1398                NameLookupColumns.DATA_ID +
1399        ");");
1400
1401        db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key1_index");
1402        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
1403                RawContacts.SORT_KEY_PRIMARY +
1404        ");");
1405
1406        db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key2_index");
1407        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
1408                RawContacts.SORT_KEY_ALTERNATIVE +
1409        ");");
1410    }
1411
1412    private static void createContactsViews(SQLiteDatabase db) {
1413        db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS + ";");
1414        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA + ";");
1415        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS + ";");
1416        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_ENTITIES + ";");
1417        db.execSQL("DROP VIEW IF EXISTS " + Views.ENTITIES + ";");
1418        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_USAGE_STAT + ";");
1419
1420        String dataColumns =
1421                Data.IS_PRIMARY + ", "
1422                + Data.IS_SUPER_PRIMARY + ", "
1423                + Data.DATA_VERSION + ", "
1424                + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + ","
1425                + MimetypesColumns.MIMETYPE + " AS " + Data.MIMETYPE + ", "
1426                + Data.IS_READ_ONLY + ", "
1427                + Data.DATA1 + ", "
1428                + Data.DATA2 + ", "
1429                + Data.DATA3 + ", "
1430                + Data.DATA4 + ", "
1431                + Data.DATA5 + ", "
1432                + Data.DATA6 + ", "
1433                + Data.DATA7 + ", "
1434                + Data.DATA8 + ", "
1435                + Data.DATA9 + ", "
1436                + Data.DATA10 + ", "
1437                + Data.DATA11 + ", "
1438                + Data.DATA12 + ", "
1439                + Data.DATA13 + ", "
1440                + Data.DATA14 + ", "
1441                + Data.DATA15 + ", "
1442                + Data.SYNC1 + ", "
1443                + Data.SYNC2 + ", "
1444                + Data.SYNC3 + ", "
1445                + Data.SYNC4;
1446
1447        String syncColumns =
1448                RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ","
1449                + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ","
1450                + RawContactsColumns.CONCRETE_DATA_SET + " AS " + RawContacts.DATA_SET + ","
1451                + "(CASE WHEN " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL THEN "
1452                        + RawContactsColumns.CONCRETE_ACCOUNT_TYPE
1453                        + " ELSE " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + "||'/'||"
1454                        + RawContactsColumns.CONCRETE_DATA_SET + " END) AS "
1455                        + RawContacts.ACCOUNT_TYPE_AND_DATA_SET + ","
1456                + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + ","
1457                + RawContactsColumns.CONCRETE_NAME_VERIFIED + " AS "
1458                        + RawContacts.NAME_VERIFIED + ","
1459                + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + ","
1460                + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + ","
1461                + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + ","
1462                + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + ","
1463                + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + ","
1464                + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4;
1465
1466        String baseContactColumns =
1467                Contacts.HAS_PHONE_NUMBER + ", "
1468                + Contacts.NAME_RAW_CONTACT_ID + ", "
1469                + Contacts.LOOKUP_KEY + ", "
1470                + Contacts.PHOTO_ID + ", "
1471                + Contacts.PHOTO_FILE_ID + ", "
1472                + Clauses.CONTACT_VISIBLE + " AS " + Contacts.IN_VISIBLE_GROUP + ", "
1473                + ContactsColumns.LAST_STATUS_UPDATE_ID;
1474
1475        String contactOptionColumns =
1476                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1477                        + " AS " + RawContacts.CUSTOM_RINGTONE + ","
1478                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1479                        + " AS " + RawContacts.SEND_TO_VOICEMAIL + ","
1480                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1481                        + " AS " + RawContacts.LAST_TIME_CONTACTED + ","
1482                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1483                        + " AS " + RawContacts.TIMES_CONTACTED + ","
1484                + ContactsColumns.CONCRETE_STARRED
1485                        + " AS " + RawContacts.STARRED;
1486
1487        String contactNameColumns =
1488                "name_raw_contact." + RawContacts.DISPLAY_NAME_SOURCE
1489                        + " AS " + Contacts.DISPLAY_NAME_SOURCE + ", "
1490                + "name_raw_contact." + RawContacts.DISPLAY_NAME_PRIMARY
1491                        + " AS " + Contacts.DISPLAY_NAME_PRIMARY + ", "
1492                + "name_raw_contact." + RawContacts.DISPLAY_NAME_ALTERNATIVE
1493                        + " AS " + Contacts.DISPLAY_NAME_ALTERNATIVE + ", "
1494                + "name_raw_contact." + RawContacts.PHONETIC_NAME
1495                        + " AS " + Contacts.PHONETIC_NAME + ", "
1496                + "name_raw_contact." + RawContacts.PHONETIC_NAME_STYLE
1497                        + " AS " + Contacts.PHONETIC_NAME_STYLE + ", "
1498                + "name_raw_contact." + RawContacts.SORT_KEY_PRIMARY
1499                        + " AS " + Contacts.SORT_KEY_PRIMARY + ", "
1500                + "name_raw_contact." + RawContacts.SORT_KEY_ALTERNATIVE
1501                        + " AS " + Contacts.SORT_KEY_ALTERNATIVE;
1502
1503        String dataSelect = "SELECT "
1504                + DataColumns.CONCRETE_ID + " AS " + Data._ID + ","
1505                + Data.RAW_CONTACT_ID + ", "
1506                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1507                + syncColumns + ", "
1508                + dataColumns + ", "
1509                + contactOptionColumns + ", "
1510                + contactNameColumns + ", "
1511                + baseContactColumns + ", "
1512                + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1513                        Contacts.PHOTO_URI) + ", "
1514                + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1515                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1516                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1517                    " WHERE " + DataColumns.CONCRETE_RAW_CONTACT_ID +
1518                    "=" + AccountsColumns.PROFILE_RAW_CONTACT_ID + ") AS " +
1519                    RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", "
1520                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1521                + " FROM " + Tables.DATA
1522                + " JOIN " + Tables.MIMETYPES + " ON ("
1523                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1524                + " JOIN " + Tables.RAW_CONTACTS + " ON ("
1525                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1526                + " JOIN " + Tables.CONTACTS + " ON ("
1527                +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
1528                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1529                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
1530                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1531                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1532                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1533                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1534                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1535                        + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1536
1537        db.execSQL("CREATE VIEW " + Views.DATA + " AS " + dataSelect);
1538
1539        String rawContactOptionColumns =
1540                RawContacts.CUSTOM_RINGTONE + ","
1541                + RawContacts.SEND_TO_VOICEMAIL + ","
1542                + RawContacts.LAST_TIME_CONTACTED + ","
1543                + RawContacts.TIMES_CONTACTED + ","
1544                + RawContacts.STARRED;
1545
1546        String rawContactsSelect = "SELECT "
1547                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ","
1548                + RawContacts.CONTACT_ID + ", "
1549                + RawContacts.AGGREGATION_MODE + ", "
1550                + RawContacts.RAW_CONTACT_IS_READ_ONLY + ", "
1551                + RawContacts.DELETED + ", "
1552                + RawContacts.DISPLAY_NAME_SOURCE  + ", "
1553                + RawContacts.DISPLAY_NAME_PRIMARY  + ", "
1554                + RawContacts.DISPLAY_NAME_ALTERNATIVE  + ", "
1555                + RawContacts.PHONETIC_NAME  + ", "
1556                + RawContacts.PHONETIC_NAME_STYLE  + ", "
1557                + RawContacts.SORT_KEY_PRIMARY  + ", "
1558                + RawContacts.SORT_KEY_ALTERNATIVE + ", "
1559                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1560                    " WHERE " + AccountsColumns.PROFILE_RAW_CONTACT_ID +
1561                    "=" + RawContactsColumns.CONCRETE_ID + ") AS " +
1562                    RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", "
1563                + rawContactOptionColumns + ", "
1564                + syncColumns
1565                + " FROM " + Tables.RAW_CONTACTS;
1566
1567        db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS + " AS " + rawContactsSelect);
1568
1569        String contactsColumns =
1570                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1571                        + " AS " + Contacts.CUSTOM_RINGTONE + ", "
1572                + contactNameColumns + ", "
1573                + baseContactColumns + ", "
1574                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1575                        + " AS " + Contacts.LAST_TIME_CONTACTED + ", "
1576                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1577                        + " AS " + Contacts.SEND_TO_VOICEMAIL + ", "
1578                + ContactsColumns.CONCRETE_STARRED
1579                        + " AS " + Contacts.STARRED + ", "
1580                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1581                        + " AS " + Contacts.TIMES_CONTACTED;
1582
1583        String contactsSelect = "SELECT "
1584                + ContactsColumns.CONCRETE_ID + " AS " + Contacts._ID + ","
1585                + contactsColumns + ", "
1586                + buildDisplayPhotoUriAlias(ContactsColumns.CONCRETE_ID, Contacts.PHOTO_URI) + ", "
1587                + buildThumbnailPhotoUriAlias(ContactsColumns.CONCRETE_ID,
1588                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1589                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1590                    " JOIN " + Tables.RAW_CONTACTS + " ON " + RawContactsColumns.CONCRETE_ID + "=" +
1591                    AccountsColumns.PROFILE_RAW_CONTACT_ID +
1592                    " WHERE " + RawContactsColumns.CONCRETE_CONTACT_ID +
1593                    "=" + ContactsColumns.CONCRETE_ID + ") AS " +
1594                    Contacts.IS_USER_PROFILE
1595                + " FROM " + Tables.CONTACTS
1596                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1597                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")";
1598
1599        db.execSQL("CREATE VIEW " + Views.CONTACTS + " AS " + contactsSelect);
1600
1601        String rawEntitiesSelect = "SELECT "
1602                + RawContacts.CONTACT_ID + ", "
1603                + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
1604                + dataColumns + ", "
1605                + syncColumns + ", "
1606                + Data.SYNC1 + ", "
1607                + Data.SYNC2 + ", "
1608                + Data.SYNC3 + ", "
1609                + Data.SYNC4 + ", "
1610                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ", "
1611                + DataColumns.CONCRETE_ID + " AS " + RawContacts.Entity.DATA_ID + ","
1612                + RawContactsColumns.CONCRETE_STARRED + " AS " + RawContacts.STARRED + ","
1613                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1614                    " WHERE " + RawContactsColumns.CONCRETE_ID +
1615                    "=" + AccountsColumns.PROFILE_RAW_CONTACT_ID + ") AS " +
1616                    RawContacts.RAW_CONTACT_IS_USER_PROFILE + ","
1617                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1618                + " FROM " + Tables.RAW_CONTACTS
1619                + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
1620                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1621                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1622                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1623                + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
1624                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1625                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1626                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1627                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1628                + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1629
1630        db.execSQL("CREATE VIEW " + Views.RAW_ENTITIES + " AS "
1631                + rawEntitiesSelect);
1632
1633        String entitiesSelect = "SELECT "
1634                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + Contacts._ID + ", "
1635                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1636                + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
1637                + dataColumns + ", "
1638                + syncColumns + ", "
1639                + contactsColumns + ", "
1640                + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1641                        Contacts.PHOTO_URI) + ", "
1642                + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID,
1643                        Contacts.PHOTO_THUMBNAIL_URI) + ", "
1644                + "EXISTS (SELECT 1 FROM " + Tables.ACCOUNTS +
1645                    " JOIN " + Tables.RAW_CONTACTS + " ON " + RawContactsColumns.CONCRETE_ID + "=" +
1646                    AccountsColumns.PROFILE_RAW_CONTACT_ID +
1647                    " WHERE " + RawContactsColumns.CONCRETE_CONTACT_ID +
1648                    "=" + ContactsColumns.CONCRETE_ID + ") AS " +
1649                    Contacts.IS_USER_PROFILE + ", "
1650                + Data.SYNC1 + ", "
1651                + Data.SYNC2 + ", "
1652                + Data.SYNC3 + ", "
1653                + Data.SYNC4 + ", "
1654                + RawContactsColumns.CONCRETE_ID + " AS " + Contacts.Entity.RAW_CONTACT_ID + ", "
1655                + DataColumns.CONCRETE_ID + " AS " + Contacts.Entity.DATA_ID + ","
1656                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1657                + " FROM " + Tables.RAW_CONTACTS
1658                + " JOIN " + Tables.CONTACTS + " ON ("
1659                +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
1660                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1661                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
1662                + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
1663                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1664                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1665                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1666                + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
1667                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1668                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1669                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1670                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1671                + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1672
1673        db.execSQL("CREATE VIEW " + Views.ENTITIES + " AS "
1674                + entitiesSelect);
1675
1676        String dataUsageStatSelect = "SELECT "
1677                + DataUsageStatColumns.CONCRETE_ID + " AS " + DataUsageStatColumns._ID + ", "
1678                + DataUsageStatColumns.DATA_ID + ", "
1679                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1680                + MimetypesColumns.CONCRETE_MIMETYPE + " AS " + Data.MIMETYPE + ", "
1681                + DataUsageStatColumns.USAGE_TYPE_INT + ", "
1682                + DataUsageStatColumns.TIMES_USED + ", "
1683                + DataUsageStatColumns.LAST_TIME_USED
1684                + " FROM " + Tables.DATA_USAGE_STAT
1685                + " JOIN " + Tables.DATA + " ON ("
1686                +   DataColumns.CONCRETE_ID + "=" + DataUsageStatColumns.CONCRETE_DATA_ID + ")"
1687                + " JOIN " + Tables.RAW_CONTACTS + " ON ("
1688                +   RawContactsColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_RAW_CONTACT_ID
1689                    + " )"
1690                + " JOIN " + Tables.MIMETYPES + " ON ("
1691                +   MimetypesColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_MIMETYPE_ID + ")";
1692
1693        db.execSQL("CREATE VIEW " + Views.DATA_USAGE_STAT + " AS " + dataUsageStatSelect);
1694    }
1695
1696    private static String buildDisplayPhotoUriAlias(String contactIdColumn, String alias) {
1697        return "(CASE WHEN " + Contacts.PHOTO_FILE_ID + " IS NULL THEN (CASE WHEN "
1698                + Contacts.PHOTO_ID + " IS NULL"
1699                + " OR " + Contacts.PHOTO_ID + "=0"
1700                + " THEN NULL"
1701                + " ELSE '" + Contacts.CONTENT_URI + "/'||"
1702                        + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'"
1703                + " END) ELSE '" + DisplayPhoto.CONTENT_URI + "/'||"
1704                        + Contacts.PHOTO_FILE_ID + " END)"
1705                + " AS " + alias;
1706    }
1707
1708    private static String buildThumbnailPhotoUriAlias(String contactIdColumn, String alias) {
1709        return "(CASE WHEN "
1710                + Contacts.PHOTO_ID + " IS NULL"
1711                + " OR " + Contacts.PHOTO_ID + "=0"
1712                + " THEN NULL"
1713                + " ELSE '" + Contacts.CONTENT_URI + "/'||"
1714                        + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'"
1715                + " END)"
1716                + " AS " + alias;
1717    }
1718
1719    private static void createGroupsView(SQLiteDatabase db) {
1720        db.execSQL("DROP VIEW IF EXISTS " + Views.GROUPS + ";");
1721        String groupsColumns =
1722                Groups.ACCOUNT_NAME + ","
1723                + Groups.ACCOUNT_TYPE + ","
1724                + Groups.DATA_SET + ","
1725                + "(CASE WHEN " + Groups.DATA_SET + " IS NULL THEN " + Groups.ACCOUNT_TYPE
1726                    + " ELSE " + Groups.ACCOUNT_TYPE + "||" + Groups.DATA_SET + " END) AS "
1727                    + Groups.ACCOUNT_TYPE_AND_DATA_SET + ","
1728                + Groups.SOURCE_ID + ","
1729                + Groups.VERSION + ","
1730                + Groups.DIRTY + ","
1731                + Groups.TITLE + ","
1732                + Groups.TITLE_RES + ","
1733                + Groups.NOTES + ","
1734                + Groups.ACTION + ", "
1735                + Groups.ACTION_URI + ", "
1736                + Groups.SYSTEM_ID + ","
1737                + Groups.DELETED + ","
1738                + Groups.GROUP_VISIBLE + ","
1739                + Groups.SHOULD_SYNC + ","
1740                + Groups.AUTO_ADD + ","
1741                + Groups.FAVORITES + ","
1742                + Groups.GROUP_IS_READ_ONLY + ","
1743                + Groups.SYNC1 + ","
1744                + Groups.SYNC2 + ","
1745                + Groups.SYNC3 + ","
1746                + Groups.SYNC4 + ","
1747                + PackagesColumns.PACKAGE + " AS " + Groups.RES_PACKAGE;
1748
1749        String groupsSelect = "SELECT "
1750                + GroupsColumns.CONCRETE_ID + " AS " + Groups._ID + ","
1751                + groupsColumns
1752                + " FROM " + Tables.GROUPS_JOIN_PACKAGES;
1753
1754        db.execSQL("CREATE VIEW " + Views.GROUPS + " AS " + groupsSelect);
1755    }
1756
1757    @Override
1758    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1759        if (oldVersion < 99) {
1760            Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion
1761                    + ", data will be lost!");
1762
1763            db.execSQL("DROP TABLE IF EXISTS " + Tables.CONTACTS + ";");
1764            db.execSQL("DROP TABLE IF EXISTS " + Tables.RAW_CONTACTS + ";");
1765            db.execSQL("DROP TABLE IF EXISTS " + Tables.PACKAGES + ";");
1766            db.execSQL("DROP TABLE IF EXISTS " + Tables.MIMETYPES + ";");
1767            db.execSQL("DROP TABLE IF EXISTS " + Tables.DATA + ";");
1768            db.execSQL("DROP TABLE IF EXISTS " + Tables.PHONE_LOOKUP + ";");
1769            db.execSQL("DROP TABLE IF EXISTS " + Tables.NAME_LOOKUP + ";");
1770            db.execSQL("DROP TABLE IF EXISTS " + Tables.NICKNAME_LOOKUP + ";");
1771            db.execSQL("DROP TABLE IF EXISTS " + Tables.GROUPS + ";");
1772            db.execSQL("DROP TABLE IF EXISTS " + Tables.ACTIVITIES + ";");
1773            db.execSQL("DROP TABLE IF EXISTS " + Tables.CALLS + ";");
1774            db.execSQL("DROP TABLE IF EXISTS " + Tables.SETTINGS + ";");
1775            db.execSQL("DROP TABLE IF EXISTS " + Tables.STATUS_UPDATES + ";");
1776
1777            // TODO: we should not be dropping agg_exceptions and contact_options. In case that
1778            // table's schema changes, we should try to preserve the data, because it was entered
1779            // by the user and has never been synched to the server.
1780            db.execSQL("DROP TABLE IF EXISTS " + Tables.AGGREGATION_EXCEPTIONS + ";");
1781
1782            onCreate(db);
1783            return;
1784        }
1785
1786        Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion);
1787
1788        boolean upgradeViewsAndTriggers = false;
1789        boolean upgradeNameLookup = false;
1790        boolean upgradeLegacyApiSupport = false;
1791        boolean upgradeSearchIndex = false;
1792
1793        if (oldVersion == 99) {
1794            upgradeViewsAndTriggers = true;
1795            oldVersion++;
1796        }
1797
1798        if (oldVersion == 100) {
1799            db.execSQL("CREATE INDEX IF NOT EXISTS mimetypes_mimetype_index ON "
1800                    + Tables.MIMETYPES + " ("
1801                            + MimetypesColumns.MIMETYPE + ","
1802                            + MimetypesColumns._ID + ");");
1803            updateIndexStats(db, Tables.MIMETYPES,
1804                    "mimetypes_mimetype_index", "50 1 1");
1805
1806            upgradeViewsAndTriggers = true;
1807            oldVersion++;
1808        }
1809
1810        if (oldVersion == 101) {
1811            upgradeViewsAndTriggers = true;
1812            oldVersion++;
1813        }
1814
1815        if (oldVersion == 102) {
1816            upgradeViewsAndTriggers = true;
1817            oldVersion++;
1818        }
1819
1820        if (oldVersion == 103) {
1821            upgradeViewsAndTriggers = true;
1822            oldVersion++;
1823        }
1824
1825        if (oldVersion == 104 || oldVersion == 201) {
1826            LegacyApiSupport.createSettingsTable(db);
1827            upgradeViewsAndTriggers = true;
1828            oldVersion++;
1829        }
1830
1831        if (oldVersion == 105) {
1832            upgradeToVersion202(db);
1833            upgradeNameLookup = true;
1834            oldVersion = 202;
1835        }
1836
1837        if (oldVersion == 202) {
1838            upgradeToVersion203(db);
1839            upgradeViewsAndTriggers = true;
1840            oldVersion++;
1841        }
1842
1843        if (oldVersion == 203) {
1844            upgradeViewsAndTriggers = true;
1845            oldVersion++;
1846        }
1847
1848        if (oldVersion == 204) {
1849            upgradeToVersion205(db);
1850            upgradeViewsAndTriggers = true;
1851            oldVersion++;
1852        }
1853
1854        if (oldVersion == 205) {
1855            upgrateToVersion206(db);
1856            upgradeViewsAndTriggers = true;
1857            oldVersion++;
1858        }
1859
1860        if (oldVersion == 206) {
1861            upgradeToVersion300(db);
1862            oldVersion = 300;
1863        }
1864
1865        if (oldVersion == 300) {
1866            upgradeViewsAndTriggers = true;
1867            oldVersion = 301;
1868        }
1869
1870        if (oldVersion == 301) {
1871            upgradeViewsAndTriggers = true;
1872            oldVersion = 302;
1873        }
1874
1875        if (oldVersion == 302) {
1876            upgradeEmailToVersion303(db);
1877            upgradeNicknameToVersion303(db);
1878            oldVersion = 303;
1879        }
1880
1881        if (oldVersion == 303) {
1882            upgradeToVersion304(db);
1883            oldVersion = 304;
1884        }
1885
1886        if (oldVersion == 304) {
1887            upgradeNameLookup = true;
1888            oldVersion = 305;
1889        }
1890
1891        if (oldVersion == 305) {
1892            upgradeToVersion306(db);
1893            oldVersion = 306;
1894        }
1895
1896        if (oldVersion == 306) {
1897            upgradeToVersion307(db);
1898            oldVersion = 307;
1899        }
1900
1901        if (oldVersion == 307) {
1902            upgradeToVersion308(db);
1903            oldVersion = 308;
1904        }
1905
1906        // Gingerbread upgrades
1907        if (oldVersion < 350) {
1908            upgradeViewsAndTriggers = true;
1909            oldVersion = 351;
1910        }
1911
1912        if (oldVersion == 351) {
1913            upgradeNameLookup = true;
1914            oldVersion = 352;
1915        }
1916
1917        if (oldVersion == 352) {
1918            upgradeToVersion353(db);
1919            oldVersion = 353;
1920        }
1921
1922        // Honeycomb upgrades
1923        if (oldVersion < 400) {
1924            upgradeViewsAndTriggers = true;
1925            upgradeToVersion400(db);
1926            oldVersion = 400;
1927        }
1928
1929        if (oldVersion == 400) {
1930            upgradeViewsAndTriggers = true;
1931            upgradeToVersion401(db);
1932            oldVersion = 401;
1933        }
1934
1935        if (oldVersion == 401) {
1936            upgradeToVersion402(db);
1937            oldVersion = 402;
1938        }
1939
1940        if (oldVersion == 402) {
1941            upgradeViewsAndTriggers = true;
1942            upgradeToVersion403(db);
1943            oldVersion = 403;
1944        }
1945
1946        if (oldVersion == 403) {
1947            upgradeViewsAndTriggers = true;
1948            oldVersion = 404;
1949        }
1950
1951        if (oldVersion == 404) {
1952            upgradeViewsAndTriggers = true;
1953            upgradeToVersion405(db);
1954            oldVersion = 405;
1955        }
1956
1957        if (oldVersion == 405) {
1958            upgradeViewsAndTriggers = true;
1959            upgradeToVersion406(db);
1960            oldVersion = 406;
1961        }
1962
1963        if (oldVersion == 406) {
1964            upgradeViewsAndTriggers = true;
1965            oldVersion = 407;
1966        }
1967
1968        if (oldVersion == 407) {
1969            // Obsolete
1970            oldVersion = 408;
1971        }
1972
1973        if (oldVersion == 408) {
1974            upgradeViewsAndTriggers = true;
1975            upgradeToVersion409(db);
1976            oldVersion = 409;
1977        }
1978
1979        if (oldVersion == 409) {
1980            upgradeViewsAndTriggers = true;
1981            oldVersion = 410;
1982        }
1983
1984        if (oldVersion == 410) {
1985            upgradeToVersion411(db);
1986            oldVersion = 411;
1987        }
1988
1989        if (oldVersion == 411) {
1990            // Same upgrade as 353, only on Honeycomb devices
1991            upgradeToVersion353(db);
1992            oldVersion = 412;
1993        }
1994
1995        if (oldVersion == 412) {
1996            upgradeToVersion413(db);
1997            oldVersion = 413;
1998        }
1999
2000        if (oldVersion == 413) {
2001            upgradeNameLookup = true;
2002            oldVersion = 414;
2003        }
2004
2005        if (oldVersion == 414) {
2006            upgradeToVersion415(db);
2007            upgradeViewsAndTriggers = true;
2008            oldVersion = 415;
2009        }
2010
2011        if (oldVersion == 415) {
2012            upgradeToVersion416(db);
2013            oldVersion = 416;
2014        }
2015
2016        if (oldVersion == 416) {
2017            upgradeLegacyApiSupport = true;
2018            oldVersion = 417;
2019        }
2020
2021        // Honeycomb-MR1 upgrades
2022        if (oldVersion < 500) {
2023            upgradeSearchIndex = true;
2024        }
2025
2026        if (oldVersion < 501) {
2027            upgradeSearchIndex = true;
2028            upgradeToVersion501(db);
2029            oldVersion = 501;
2030        }
2031
2032        if (oldVersion < 502) {
2033            upgradeSearchIndex = true;
2034            upgradeToVersion502(db);
2035            oldVersion = 502;
2036        }
2037
2038        if (oldVersion < 503) {
2039            upgradeSearchIndex = true;
2040            oldVersion = 503;
2041        }
2042
2043        if (oldVersion < 504) {
2044            upgradeToVersion504(db);
2045            oldVersion = 504;
2046        }
2047
2048        if (oldVersion < 600) {
2049            upgradeToVersion600(db);
2050            upgradeViewsAndTriggers = true;
2051            oldVersion = 600;
2052        }
2053
2054        if (oldVersion < 601) {
2055            upgradeToVersion601(db);
2056            oldVersion = 601;
2057        }
2058
2059        if (oldVersion < 602) {
2060            upgradeToVersion602(db);
2061            oldVersion = 602;
2062        }
2063
2064        if (oldVersion < 603) {
2065            upgradeViewsAndTriggers = true;
2066            oldVersion = 603;
2067        }
2068
2069        if (oldVersion < 604) {
2070            upgradeToVersion604(db);
2071            oldVersion = 604;
2072        }
2073
2074        if (oldVersion < 605) {
2075            upgradeViewsAndTriggers = true;
2076            upgradeToVersion605(db);
2077            oldVersion = 605;
2078        }
2079
2080        if (oldVersion < 606) {
2081            upgradeViewsAndTriggers = true;
2082            upgradeLegacyApiSupport = true;
2083            upgradeToVersion606(db);
2084            oldVersion = 606;
2085        }
2086
2087        if (oldVersion < 607) {
2088            upgradeViewsAndTriggers = true;
2089            upgradeToVersion607(db);
2090            oldVersion = 607;
2091        }
2092
2093        if (oldVersion < 608) {
2094            upgradeViewsAndTriggers = true;
2095            upgradeToVersion608(db);
2096            oldVersion = 608;
2097        }
2098
2099        if (oldVersion < 609) {
2100            upgradeToVersion609(db);
2101            oldVersion = 609;
2102        }
2103
2104        if (oldVersion < 610) {
2105            upgradeToVersion610(db);
2106            oldVersion = 610;
2107        }
2108
2109        if (oldVersion < 611) {
2110            upgradeViewsAndTriggers = true;
2111            upgradeToVersion611(db);
2112            oldVersion = 611;
2113        }
2114
2115        if (oldVersion < 612) {
2116            upgradeViewsAndTriggers = true;
2117            upgradeToVersion612(db);
2118            oldVersion = 612;
2119        }
2120
2121        if (upgradeViewsAndTriggers) {
2122            createContactsViews(db);
2123            createGroupsView(db);
2124            createContactsTriggers(db);
2125            createContactsIndexes(db);
2126            updateSqliteStats(db);
2127            upgradeLegacyApiSupport = true;
2128            mReopenDatabase = true;
2129        }
2130
2131        if (upgradeLegacyApiSupport) {
2132            LegacyApiSupport.createViews(db);
2133        }
2134
2135        if (upgradeNameLookup) {
2136            rebuildNameLookup(db);
2137        }
2138
2139        if (upgradeSearchIndex) {
2140            setProperty(db, SearchIndexManager.PROPERTY_SEARCH_INDEX_VERSION, "0");
2141        }
2142
2143        if (oldVersion != newVersion) {
2144            throw new IllegalStateException(
2145                    "error upgrading the database to version " + newVersion);
2146        }
2147    }
2148
2149    private void upgradeToVersion202(SQLiteDatabase db) {
2150        db.execSQL(
2151                "ALTER TABLE " + Tables.PHONE_LOOKUP +
2152                " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;");
2153
2154        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
2155                PhoneLookupColumns.MIN_MATCH + "," +
2156                PhoneLookupColumns.RAW_CONTACT_ID + "," +
2157                PhoneLookupColumns.DATA_ID +
2158        ");");
2159
2160        updateIndexStats(db, Tables.PHONE_LOOKUP,
2161                "phone_lookup_min_match_index", "10000 2 2 1");
2162
2163        SQLiteStatement update = db.compileStatement(
2164                "UPDATE " + Tables.PHONE_LOOKUP +
2165                " SET " + PhoneLookupColumns.MIN_MATCH + "=?" +
2166                " WHERE " + PhoneLookupColumns.DATA_ID + "=?");
2167
2168        // Populate the new column
2169        Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA +
2170                " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")",
2171                new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null);
2172        try {
2173            while (c.moveToNext()) {
2174                long dataId = c.getLong(0);
2175                String number = c.getString(1);
2176                if (!TextUtils.isEmpty(number)) {
2177                    update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number));
2178                    update.bindLong(2, dataId);
2179                    update.execute();
2180                }
2181            }
2182        } finally {
2183            c.close();
2184        }
2185    }
2186
2187    private void upgradeToVersion203(SQLiteDatabase db) {
2188        // Garbage-collect first. A bug in Eclair was sometimes leaving
2189        // raw_contacts in the database that no longer had contacts associated
2190        // with them.  To avoid failures during this database upgrade, drop
2191        // the orphaned raw_contacts.
2192        db.execSQL(
2193                "DELETE FROM raw_contacts" +
2194                " WHERE contact_id NOT NULL" +
2195                " AND contact_id NOT IN (SELECT _id FROM contacts)");
2196
2197        db.execSQL(
2198                "ALTER TABLE " + Tables.CONTACTS +
2199                " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)");
2200        db.execSQL(
2201                "ALTER TABLE " + Tables.RAW_CONTACTS +
2202                " ADD contact_in_visible_group INTEGER NOT NULL DEFAULT 0");
2203
2204        // For each Contact, find the RawContact that contributed the display name
2205        db.execSQL(
2206                "UPDATE " + Tables.CONTACTS +
2207                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
2208                        " SELECT " + RawContacts._ID +
2209                        " FROM " + Tables.RAW_CONTACTS +
2210                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
2211                        " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" +
2212                                Tables.CONTACTS + "." + Contacts.DISPLAY_NAME +
2213                        " ORDER BY " + RawContacts._ID +
2214                        " LIMIT 1)"
2215        );
2216
2217        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
2218                Contacts.NAME_RAW_CONTACT_ID +
2219        ");");
2220
2221        // If for some unknown reason we missed some names, let's make sure there are
2222        // no contacts without a name, picking a raw contact "at random".
2223        db.execSQL(
2224                "UPDATE " + Tables.CONTACTS +
2225                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
2226                        " SELECT " + RawContacts._ID +
2227                        " FROM " + Tables.RAW_CONTACTS +
2228                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
2229                        " ORDER BY " + RawContacts._ID +
2230                        " LIMIT 1)" +
2231                " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL"
2232        );
2233
2234        // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use.
2235        db.execSQL(
2236                "UPDATE " + Tables.CONTACTS +
2237                " SET " + Contacts.DISPLAY_NAME + "=NULL"
2238        );
2239
2240        // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow
2241        // indexing on (display_name, in_visible_group)
2242        db.execSQL(
2243                "UPDATE " + Tables.RAW_CONTACTS +
2244                " SET contact_in_visible_group=(" +
2245                        "SELECT " + Contacts.IN_VISIBLE_GROUP +
2246                        " FROM " + Tables.CONTACTS +
2247                        " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" +
2248                " WHERE " + RawContacts.CONTACT_ID + " NOT NULL"
2249        );
2250
2251        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
2252                "contact_in_visible_group" + "," +
2253                RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" +
2254        ");");
2255
2256        db.execSQL("DROP INDEX contacts_visible_index");
2257        db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
2258                Contacts.IN_VISIBLE_GROUP +
2259        ");");
2260    }
2261
2262    private void upgradeToVersion205(SQLiteDatabase db) {
2263        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2264                + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;");
2265        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2266                + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;");
2267        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2268                + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;");
2269        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2270                + " ADD " + RawContacts.SORT_KEY_PRIMARY
2271                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
2272        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2273                + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE
2274                + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
2275
2276        final Locale locale = Locale.getDefault();
2277
2278        NameSplitter splitter = createNameSplitter();
2279
2280        SQLiteStatement rawContactUpdate = db.compileStatement(
2281                "UPDATE " + Tables.RAW_CONTACTS +
2282                " SET " +
2283                        RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
2284                        RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
2285                        RawContacts.PHONETIC_NAME + "=?," +
2286                        RawContacts.PHONETIC_NAME_STYLE + "=?," +
2287                        RawContacts.SORT_KEY_PRIMARY + "=?," +
2288                        RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
2289                " WHERE " + RawContacts._ID + "=?");
2290
2291        upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter);
2292        upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter);
2293
2294        db.execSQL("DROP INDEX raw_contact_sort_key1_index");
2295        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
2296                "contact_in_visible_group" + "," +
2297                RawContacts.SORT_KEY_PRIMARY +
2298        ");");
2299
2300        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
2301                "contact_in_visible_group" + "," +
2302                RawContacts.SORT_KEY_ALTERNATIVE +
2303        ");");
2304    }
2305
2306    private interface StructName205Query {
2307        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
2308
2309        String COLUMNS[] = {
2310                DataColumns.CONCRETE_ID,
2311                Data.RAW_CONTACT_ID,
2312                RawContacts.DISPLAY_NAME_SOURCE,
2313                RawContacts.DISPLAY_NAME_PRIMARY,
2314                StructuredName.PREFIX,
2315                StructuredName.GIVEN_NAME,
2316                StructuredName.MIDDLE_NAME,
2317                StructuredName.FAMILY_NAME,
2318                StructuredName.SUFFIX,
2319                StructuredName.PHONETIC_FAMILY_NAME,
2320                StructuredName.PHONETIC_MIDDLE_NAME,
2321                StructuredName.PHONETIC_GIVEN_NAME,
2322        };
2323
2324        int ID = 0;
2325        int RAW_CONTACT_ID = 1;
2326        int DISPLAY_NAME_SOURCE = 2;
2327        int DISPLAY_NAME = 3;
2328        int PREFIX = 4;
2329        int GIVEN_NAME = 5;
2330        int MIDDLE_NAME = 6;
2331        int FAMILY_NAME = 7;
2332        int SUFFIX = 8;
2333        int PHONETIC_FAMILY_NAME = 9;
2334        int PHONETIC_MIDDLE_NAME = 10;
2335        int PHONETIC_GIVEN_NAME = 11;
2336    }
2337
2338    private void upgradeStructuredNamesToVersion205(SQLiteDatabase db,
2339            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2340
2341        // Process structured names to detect the style of the full name and phonetic name
2342
2343        long mMimeType;
2344        try {
2345            mMimeType = DatabaseUtils.longForQuery(db,
2346                    "SELECT " + MimetypesColumns._ID +
2347                    " FROM " + Tables.MIMETYPES +
2348                    " WHERE " + MimetypesColumns.MIMETYPE
2349                            + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null);
2350        } catch (SQLiteDoneException e) {
2351            // No structured names in the database
2352            return;
2353        }
2354
2355        SQLiteStatement structuredNameUpdate = db.compileStatement(
2356                "UPDATE " + Tables.DATA +
2357                " SET " +
2358                        StructuredName.FULL_NAME_STYLE + "=?," +
2359                        StructuredName.DISPLAY_NAME + "=?," +
2360                        StructuredName.PHONETIC_NAME_STYLE + "=?" +
2361                " WHERE " + Data._ID + "=?");
2362
2363        NameSplitter.Name name = new NameSplitter.Name();
2364        StringBuilder sb = new StringBuilder();
2365        Cursor cursor = db.query(StructName205Query.TABLE,
2366                StructName205Query.COLUMNS,
2367                DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null);
2368        try {
2369            while (cursor.moveToNext()) {
2370                long dataId = cursor.getLong(StructName205Query.ID);
2371                long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID);
2372                int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE);
2373                String displayName = cursor.getString(StructName205Query.DISPLAY_NAME);
2374
2375                name.clear();
2376                name.prefix = cursor.getString(StructName205Query.PREFIX);
2377                name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME);
2378                name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME);
2379                name.familyName = cursor.getString(StructName205Query.FAMILY_NAME);
2380                name.suffix = cursor.getString(StructName205Query.SUFFIX);
2381                name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME);
2382                name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME);
2383                name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME);
2384
2385                upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name,
2386                        structuredNameUpdate, rawContactUpdate, splitter, sb);
2387            }
2388        } finally {
2389            cursor.close();
2390        }
2391    }
2392
2393    private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource,
2394            String currentDisplayName, NameSplitter.Name name,
2395            SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate,
2396            NameSplitter splitter, StringBuilder sb) {
2397
2398        splitter.guessNameStyle(name);
2399        int unadjustedFullNameStyle = name.fullNameStyle;
2400        name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle);
2401        String displayName = splitter.join(name, true, true);
2402
2403        // Don't update database with the adjusted fullNameStyle as it is locale
2404        // related
2405        structuredNameUpdate.bindLong(1, unadjustedFullNameStyle);
2406        DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName);
2407        structuredNameUpdate.bindLong(3, name.phoneticNameStyle);
2408        structuredNameUpdate.bindLong(4, dataId);
2409        structuredNameUpdate.execute();
2410
2411        if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) {
2412            String displayNameAlternative = splitter.join(name, false, false);
2413            String phoneticName = splitter.joinPhoneticName(name);
2414            String sortKey = null;
2415            String sortKeyAlternative = null;
2416
2417            if (phoneticName != null) {
2418                sortKey = sortKeyAlternative = phoneticName;
2419            } else if (name.fullNameStyle == FullNameStyle.CHINESE ||
2420                    name.fullNameStyle == FullNameStyle.CJK) {
2421                sortKey = sortKeyAlternative = ContactLocaleUtils.getIntance()
2422                        .getSortKey(displayName, name.fullNameStyle);
2423            }
2424
2425            if (sortKey == null) {
2426                sortKey = displayName;
2427                sortKeyAlternative = displayNameAlternative;
2428            }
2429
2430            updateRawContact205(rawContactUpdate, rawContactId, displayName,
2431                    displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey,
2432                    sortKeyAlternative);
2433        }
2434    }
2435
2436    private interface Organization205Query {
2437        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
2438
2439        String COLUMNS[] = {
2440                DataColumns.CONCRETE_ID,
2441                Data.RAW_CONTACT_ID,
2442                Organization.COMPANY,
2443                Organization.PHONETIC_NAME,
2444        };
2445
2446        int ID = 0;
2447        int RAW_CONTACT_ID = 1;
2448        int COMPANY = 2;
2449        int PHONETIC_NAME = 3;
2450    }
2451
2452    private void upgradeOrganizationsToVersion205(SQLiteDatabase db,
2453            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
2454        final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE);
2455
2456        SQLiteStatement organizationUpdate = db.compileStatement(
2457                "UPDATE " + Tables.DATA +
2458                " SET " +
2459                        Organization.PHONETIC_NAME_STYLE + "=?" +
2460                " WHERE " + Data._ID + "=?");
2461
2462        Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS,
2463                DataColumns.MIMETYPE_ID + "=" + mimeType + " AND "
2464                        + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION,
2465                null, null, null, null);
2466        try {
2467            while (cursor.moveToNext()) {
2468                long dataId = cursor.getLong(Organization205Query.ID);
2469                long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID);
2470                String company = cursor.getString(Organization205Query.COMPANY);
2471                String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME);
2472
2473                int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName);
2474
2475                organizationUpdate.bindLong(1, phoneticNameStyle);
2476                organizationUpdate.bindLong(2, dataId);
2477                organizationUpdate.execute();
2478
2479                String sortKey = null;
2480                if (phoneticName == null && company != null) {
2481                    int nameStyle = splitter.guessFullNameStyle(company);
2482                    nameStyle = splitter.getAdjustedFullNameStyle(nameStyle);
2483                    if (nameStyle == FullNameStyle.CHINESE ||
2484                            nameStyle == FullNameStyle.CJK ) {
2485                        sortKey = ContactLocaleUtils.getIntance()
2486                                .getSortKey(company, nameStyle);
2487                    }
2488                }
2489
2490                if (sortKey == null) {
2491                    sortKey = company;
2492                }
2493
2494                updateRawContact205(rawContactUpdate, rawContactId, company,
2495                        company, phoneticNameStyle, phoneticName, sortKey, sortKey);
2496            }
2497        } finally {
2498            cursor.close();
2499        }
2500    }
2501
2502    private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId,
2503            String displayName, String displayNameAlternative, int phoneticNameStyle,
2504            String phoneticName, String sortKeyPrimary, String sortKeyAlternative) {
2505        bindString(rawContactUpdate, 1, displayName);
2506        bindString(rawContactUpdate, 2, displayNameAlternative);
2507        bindString(rawContactUpdate, 3, phoneticName);
2508        rawContactUpdate.bindLong(4, phoneticNameStyle);
2509        bindString(rawContactUpdate, 5, sortKeyPrimary);
2510        bindString(rawContactUpdate, 6, sortKeyAlternative);
2511        rawContactUpdate.bindLong(7, rawContactId);
2512        rawContactUpdate.execute();
2513    }
2514
2515    private void upgrateToVersion206(SQLiteDatabase db) {
2516        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
2517                + " ADD " + RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0;");
2518    }
2519
2520    /**
2521     * Fix for the bug where name lookup records for organizations would get removed by
2522     * unrelated updates of the data rows.
2523     */
2524    private void upgradeToVersion300(SQLiteDatabase db) {
2525        // No longer needed
2526    }
2527
2528    private static final class Upgrade303Query {
2529        public static final String TABLE = Tables.DATA;
2530
2531        public static final String SELECTION =
2532                DataColumns.MIMETYPE_ID + "=?" +
2533                    " AND " + Data._ID + " NOT IN " +
2534                    "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" +
2535                    " AND " + Data.DATA1 + " NOT NULL";
2536
2537        public static final String COLUMNS[] = {
2538                Data._ID,
2539                Data.RAW_CONTACT_ID,
2540                Data.DATA1,
2541        };
2542
2543        public static final int ID = 0;
2544        public static final int RAW_CONTACT_ID = 1;
2545        public static final int DATA1 = 2;
2546    }
2547
2548    /**
2549     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2550     * emails during the sync.  We need to restore the lost name lookup rows.
2551     */
2552    private void upgradeEmailToVersion303(SQLiteDatabase db) {
2553        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2554        if (mimeTypeId == -1) {
2555            return;
2556        }
2557
2558        ContentValues values = new ContentValues();
2559
2560        // Find all data rows with the mime type "email" that are missing name lookup
2561        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2562                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2563                null, null, null);
2564        try {
2565            while (cursor.moveToNext()) {
2566                long dataId = cursor.getLong(Upgrade303Query.ID);
2567                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2568                String value = cursor.getString(Upgrade303Query.DATA1);
2569                value = extractHandleFromEmailAddress(value);
2570
2571                if (value != null) {
2572                    values.put(NameLookupColumns.DATA_ID, dataId);
2573                    values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2574                    values.put(NameLookupColumns.NAME_TYPE, NameLookupType.EMAIL_BASED_NICKNAME);
2575                    values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2576                    db.insert(Tables.NAME_LOOKUP, null, values);
2577                }
2578            }
2579        } finally {
2580            cursor.close();
2581        }
2582    }
2583
2584    /**
2585     * The {@link ContactsProvider2#update} method was deleting name lookup for new
2586     * nicknames during the sync.  We need to restore the lost name lookup rows.
2587     */
2588    private void upgradeNicknameToVersion303(SQLiteDatabase db) {
2589        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
2590        if (mimeTypeId == -1) {
2591            return;
2592        }
2593
2594        ContentValues values = new ContentValues();
2595
2596        // Find all data rows with the mime type "nickname" that are missing name lookup
2597        Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
2598                Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2599                null, null, null);
2600        try {
2601            while (cursor.moveToNext()) {
2602                long dataId = cursor.getLong(Upgrade303Query.ID);
2603                long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
2604                String value = cursor.getString(Upgrade303Query.DATA1);
2605
2606                values.put(NameLookupColumns.DATA_ID, dataId);
2607                values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
2608                values.put(NameLookupColumns.NAME_TYPE, NameLookupType.NICKNAME);
2609                values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
2610                db.insert(Tables.NAME_LOOKUP, null, values);
2611            }
2612        } finally {
2613            cursor.close();
2614        }
2615    }
2616
2617    private void upgradeToVersion304(SQLiteDatabase db) {
2618        // Mimetype table requires an index on mime type
2619        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" +
2620                MimetypesColumns.MIMETYPE +
2621        ");");
2622    }
2623
2624    private void upgradeToVersion306(SQLiteDatabase db) {
2625        // Fix invalid lookup that was used for Exchange contacts (it was not escaped)
2626        // It happened when a new contact was created AND synchronized
2627        final StringBuilder lookupKeyBuilder = new StringBuilder();
2628        final SQLiteStatement updateStatement = db.compileStatement(
2629                "UPDATE contacts " +
2630                "SET lookup=? " +
2631                "WHERE _id=?");
2632        final Cursor contactIdCursor = db.rawQuery(
2633                "SELECT DISTINCT contact_id " +
2634                "FROM raw_contacts " +
2635                "WHERE deleted=0 AND account_type='com.android.exchange'",
2636                null);
2637        try {
2638            while (contactIdCursor.moveToNext()) {
2639                final long contactId = contactIdCursor.getLong(0);
2640                lookupKeyBuilder.setLength(0);
2641                final Cursor c = db.rawQuery(
2642                        "SELECT account_type, account_name, _id, sourceid, display_name " +
2643                        "FROM raw_contacts " +
2644                        "WHERE contact_id=? " +
2645                        "ORDER BY _id",
2646                        new String[] { String.valueOf(contactId) });
2647                try {
2648                    while (c.moveToNext()) {
2649                        ContactLookupKey.appendToLookupKey(lookupKeyBuilder,
2650                                c.getString(0),
2651                                c.getString(1),
2652                                c.getLong(2),
2653                                c.getString(3),
2654                                c.getString(4));
2655                    }
2656                } finally {
2657                    c.close();
2658                }
2659
2660                if (lookupKeyBuilder.length() == 0) {
2661                    updateStatement.bindNull(1);
2662                } else {
2663                    updateStatement.bindString(1, Uri.encode(lookupKeyBuilder.toString()));
2664                }
2665                updateStatement.bindLong(2, contactId);
2666
2667                updateStatement.execute();
2668            }
2669        } finally {
2670            updateStatement.close();
2671            contactIdCursor.close();
2672        }
2673    }
2674
2675    private void upgradeToVersion307(SQLiteDatabase db) {
2676        db.execSQL("CREATE TABLE properties (" +
2677                "property_key TEXT PRIMARY_KEY, " +
2678                "property_value TEXT" +
2679        ");");
2680    }
2681
2682    private void upgradeToVersion308(SQLiteDatabase db) {
2683        db.execSQL("CREATE TABLE accounts (" +
2684                "account_name TEXT, " +
2685                "account_type TEXT " +
2686        ");");
2687
2688        db.execSQL("INSERT INTO accounts " +
2689                "SELECT DISTINCT account_name, account_type FROM raw_contacts");
2690    }
2691
2692    private void upgradeToVersion400(SQLiteDatabase db) {
2693        db.execSQL("ALTER TABLE " + Tables.GROUPS
2694                + " ADD " + Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0;");
2695        db.execSQL("ALTER TABLE " + Tables.GROUPS
2696                + " ADD " + Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0;");
2697    }
2698
2699    private void upgradeToVersion353(SQLiteDatabase db) {
2700        db.execSQL("DELETE FROM contacts " +
2701                "WHERE NOT EXISTS (SELECT 1 FROM raw_contacts WHERE contact_id=contacts._id)");
2702    }
2703
2704    private void rebuildNameLookup(SQLiteDatabase db) {
2705        db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2706        insertNameLookup(db);
2707        createContactsIndexes(db);
2708    }
2709
2710    /**
2711     * Regenerates all locale-sensitive data: nickname_lookup, name_lookup and sort keys.
2712     */
2713    public void setLocale(ContactsProvider2 provider, Locale locale) {
2714        Log.i(TAG, "Switching to locale " + locale);
2715
2716        long start = SystemClock.uptimeMillis();
2717        SQLiteDatabase db = getWritableDatabase();
2718        db.setLocale(locale);
2719        db.beginTransaction();
2720        try {
2721            db.execSQL("DROP INDEX raw_contact_sort_key1_index");
2722            db.execSQL("DROP INDEX raw_contact_sort_key2_index");
2723            db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
2724
2725            loadNicknameLookupTable(db);
2726            insertNameLookup(db);
2727            rebuildSortKeys(db, provider);
2728            createContactsIndexes(db);
2729            db.setTransactionSuccessful();
2730        } finally {
2731            db.endTransaction();
2732        }
2733
2734        Log.i(TAG, "Locale change completed in " + (SystemClock.uptimeMillis() - start) + "ms");
2735    }
2736
2737    /**
2738     * Regenerates sort keys for all contacts.
2739     */
2740    private void rebuildSortKeys(SQLiteDatabase db, ContactsProvider2 provider) {
2741        Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID},
2742                null, null, null, null, null);
2743        try {
2744            while (cursor.moveToNext()) {
2745                long rawContactId = cursor.getLong(0);
2746                updateRawContactDisplayName(db, rawContactId);
2747            }
2748        } finally {
2749            cursor.close();
2750        }
2751    }
2752
2753    private void insertNameLookup(SQLiteDatabase db) {
2754        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP);
2755
2756        SQLiteStatement nameLookupInsert = db.compileStatement(
2757                "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
2758                        + NameLookupColumns.RAW_CONTACT_ID + ","
2759                        + NameLookupColumns.DATA_ID + ","
2760                        + NameLookupColumns.NAME_TYPE + ","
2761                        + NameLookupColumns.NORMALIZED_NAME +
2762                ") VALUES (?,?,?,?)");
2763
2764        try {
2765            insertStructuredNameLookup(db, nameLookupInsert);
2766            insertEmailLookup(db, nameLookupInsert);
2767            insertNicknameLookup(db, nameLookupInsert);
2768        } finally {
2769            nameLookupInsert.close();
2770        }
2771    }
2772
2773    private static final class StructuredNameQuery {
2774        public static final String TABLE = Tables.DATA;
2775
2776        public static final String SELECTION =
2777                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2778
2779        public static final String COLUMNS[] = {
2780                StructuredName._ID,
2781                StructuredName.RAW_CONTACT_ID,
2782                StructuredName.DISPLAY_NAME,
2783        };
2784
2785        public static final int ID = 0;
2786        public static final int RAW_CONTACT_ID = 1;
2787        public static final int DISPLAY_NAME = 2;
2788    }
2789
2790    private class StructuredNameLookupBuilder extends NameLookupBuilder {
2791
2792        private final SQLiteStatement mNameLookupInsert;
2793        private final CommonNicknameCache mCommonNicknameCache;
2794
2795        public StructuredNameLookupBuilder(NameSplitter splitter,
2796                CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) {
2797            super(splitter);
2798            this.mCommonNicknameCache = commonNicknameCache;
2799            this.mNameLookupInsert = nameLookupInsert;
2800        }
2801
2802        @Override
2803        protected void insertNameLookup(long rawContactId, long dataId, int lookupType,
2804                String name) {
2805            if (!TextUtils.isEmpty(name)) {
2806                ContactsDatabaseHelper.this.insertNormalizedNameLookup(mNameLookupInsert,
2807                        rawContactId, dataId, lookupType, name);
2808            }
2809        }
2810
2811        @Override
2812        protected String[] getCommonNicknameClusters(String normalizedName) {
2813            return mCommonNicknameCache.getCommonNicknameClusters(normalizedName);
2814        }
2815    }
2816
2817    /**
2818     * Inserts name lookup rows for all structured names in the database.
2819     */
2820    private void insertStructuredNameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2821        NameSplitter nameSplitter = createNameSplitter();
2822        NameLookupBuilder nameLookupBuilder = new StructuredNameLookupBuilder(nameSplitter,
2823                new CommonNicknameCache(db), nameLookupInsert);
2824        final long mimeTypeId = lookupMimeTypeId(db, StructuredName.CONTENT_ITEM_TYPE);
2825        Cursor cursor = db.query(StructuredNameQuery.TABLE, StructuredNameQuery.COLUMNS,
2826                StructuredNameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2827                null, null, null);
2828        try {
2829            while (cursor.moveToNext()) {
2830                long dataId = cursor.getLong(StructuredNameQuery.ID);
2831                long rawContactId = cursor.getLong(StructuredNameQuery.RAW_CONTACT_ID);
2832                String name = cursor.getString(StructuredNameQuery.DISPLAY_NAME);
2833                int fullNameStyle = nameSplitter.guessFullNameStyle(name);
2834                fullNameStyle = nameSplitter.getAdjustedFullNameStyle(fullNameStyle);
2835                nameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle);
2836            }
2837        } finally {
2838            cursor.close();
2839        }
2840    }
2841
2842    private static final class OrganizationQuery {
2843        public static final String TABLE = Tables.DATA;
2844
2845        public static final String SELECTION =
2846                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2847
2848        public static final String COLUMNS[] = {
2849                Organization._ID,
2850                Organization.RAW_CONTACT_ID,
2851                Organization.COMPANY,
2852                Organization.TITLE,
2853        };
2854
2855        public static final int ID = 0;
2856        public static final int RAW_CONTACT_ID = 1;
2857        public static final int COMPANY = 2;
2858        public static final int TITLE = 3;
2859    }
2860
2861    private static final class EmailQuery {
2862        public static final String TABLE = Tables.DATA;
2863
2864        public static final String SELECTION =
2865                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2866
2867        public static final String COLUMNS[] = {
2868                Email._ID,
2869                Email.RAW_CONTACT_ID,
2870                Email.ADDRESS,
2871        };
2872
2873        public static final int ID = 0;
2874        public static final int RAW_CONTACT_ID = 1;
2875        public static final int ADDRESS = 2;
2876    }
2877
2878    /**
2879     * Inserts name lookup rows for all email addresses in the database.
2880     */
2881    private void insertEmailLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2882        final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
2883        Cursor cursor = db.query(EmailQuery.TABLE, EmailQuery.COLUMNS,
2884                EmailQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2885                null, null, null);
2886        try {
2887            while (cursor.moveToNext()) {
2888                long dataId = cursor.getLong(EmailQuery.ID);
2889                long rawContactId = cursor.getLong(EmailQuery.RAW_CONTACT_ID);
2890                String address = cursor.getString(EmailQuery.ADDRESS);
2891                address = extractHandleFromEmailAddress(address);
2892                insertNameLookup(nameLookupInsert, rawContactId, dataId,
2893                        NameLookupType.EMAIL_BASED_NICKNAME, address);
2894            }
2895        } finally {
2896            cursor.close();
2897        }
2898    }
2899
2900    private static final class NicknameQuery {
2901        public static final String TABLE = Tables.DATA;
2902
2903        public static final String SELECTION =
2904                DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
2905
2906        public static final String COLUMNS[] = {
2907                Nickname._ID,
2908                Nickname.RAW_CONTACT_ID,
2909                Nickname.NAME,
2910        };
2911
2912        public static final int ID = 0;
2913        public static final int RAW_CONTACT_ID = 1;
2914        public static final int NAME = 2;
2915    }
2916
2917    /**
2918     * Inserts name lookup rows for all nicknames in the database.
2919     */
2920    private void insertNicknameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
2921        final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
2922        Cursor cursor = db.query(NicknameQuery.TABLE, NicknameQuery.COLUMNS,
2923                NicknameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
2924                null, null, null);
2925        try {
2926            while (cursor.moveToNext()) {
2927                long dataId = cursor.getLong(NicknameQuery.ID);
2928                long rawContactId = cursor.getLong(NicknameQuery.RAW_CONTACT_ID);
2929                String nickname = cursor.getString(NicknameQuery.NAME);
2930                insertNameLookup(nameLookupInsert, rawContactId, dataId,
2931                        NameLookupType.NICKNAME, nickname);
2932            }
2933        } finally {
2934            cursor.close();
2935        }
2936    }
2937
2938    /**
2939     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
2940     */
2941    public void insertNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
2942            int lookupType, String name) {
2943        if (TextUtils.isEmpty(name)) {
2944            return;
2945        }
2946
2947        String normalized = NameNormalizer.normalize(name);
2948        if (TextUtils.isEmpty(normalized)) {
2949            return;
2950        }
2951
2952        insertNormalizedNameLookup(stmt, rawContactId, dataId, lookupType, normalized);
2953    }
2954
2955    private void insertNormalizedNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
2956            int lookupType, String normalizedName) {
2957        stmt.bindLong(1, rawContactId);
2958        stmt.bindLong(2, dataId);
2959        stmt.bindLong(3, lookupType);
2960        stmt.bindString(4, normalizedName);
2961        stmt.executeInsert();
2962    }
2963
2964    /**
2965     * Changing the VISIBLE bit from a field on both RawContacts and Contacts to a separate table.
2966     */
2967    private void upgradeToVersion401(SQLiteDatabase db) {
2968        db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" +
2969                Contacts._ID + " INTEGER PRIMARY KEY" +
2970        ");");
2971        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
2972                " SELECT " + Contacts._ID +
2973                " FROM " + Tables.CONTACTS +
2974                " WHERE " + Contacts.IN_VISIBLE_GROUP + "!=0");
2975        db.execSQL("DROP INDEX contacts_visible_index");
2976    }
2977
2978    /**
2979     * Introducing a new table: directories.
2980     */
2981    private void upgradeToVersion402(SQLiteDatabase db) {
2982        createDirectoriesTable(db);
2983    }
2984
2985    private void upgradeToVersion403(SQLiteDatabase db) {
2986        db.execSQL("DROP TABLE IF EXISTS directories;");
2987        createDirectoriesTable(db);
2988
2989        db.execSQL("ALTER TABLE raw_contacts"
2990                + " ADD raw_contact_is_read_only INTEGER NOT NULL DEFAULT 0;");
2991
2992        db.execSQL("ALTER TABLE data"
2993                + " ADD is_read_only INTEGER NOT NULL DEFAULT 0;");
2994    }
2995
2996    private void upgradeToVersion405(SQLiteDatabase db) {
2997        db.execSQL("DROP TABLE IF EXISTS phone_lookup;");
2998        // Private phone numbers table used for lookup
2999        db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
3000                PhoneLookupColumns.DATA_ID
3001                + " INTEGER REFERENCES data(_id) NOT NULL," +
3002                PhoneLookupColumns.RAW_CONTACT_ID
3003                + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
3004                PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
3005                PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
3006        ");");
3007
3008        db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
3009                PhoneLookupColumns.NORMALIZED_NUMBER + "," +
3010                PhoneLookupColumns.RAW_CONTACT_ID + "," +
3011                PhoneLookupColumns.DATA_ID +
3012        ");");
3013
3014        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
3015                PhoneLookupColumns.MIN_MATCH + "," +
3016                PhoneLookupColumns.RAW_CONTACT_ID + "," +
3017                PhoneLookupColumns.DATA_ID +
3018        ");");
3019
3020        final long mimeTypeId = lookupMimeTypeId(db, Phone.CONTENT_ITEM_TYPE);
3021        if (mimeTypeId == -1) {
3022            return;
3023        }
3024
3025        Cursor cursor = db.rawQuery(
3026                    "SELECT _id, " + Phone.RAW_CONTACT_ID + ", " + Phone.NUMBER +
3027                    " FROM " + Tables.DATA +
3028                    " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimeTypeId
3029                            + " AND " + Phone.NUMBER + " NOT NULL", null);
3030
3031        ContentValues phoneValues = new ContentValues();
3032        try {
3033            while (cursor.moveToNext()) {
3034                long dataID = cursor.getLong(0);
3035                long rawContactID = cursor.getLong(1);
3036                String number = cursor.getString(2);
3037                String normalizedNumber = PhoneNumberUtils.normalizeNumber(number);
3038                if (!TextUtils.isEmpty(normalizedNumber)) {
3039                    phoneValues.clear();
3040                    phoneValues.put(PhoneLookupColumns.RAW_CONTACT_ID, rawContactID);
3041                    phoneValues.put(PhoneLookupColumns.DATA_ID, dataID);
3042                    phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, normalizedNumber);
3043                    phoneValues.put(PhoneLookupColumns.MIN_MATCH,
3044                            PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber));
3045                    db.insert(Tables.PHONE_LOOKUP, null, phoneValues);
3046                }
3047            }
3048        } finally {
3049            cursor.close();
3050        }
3051    }
3052
3053    private void upgradeToVersion406(SQLiteDatabase db) {
3054        db.execSQL("ALTER TABLE calls ADD countryiso TEXT;");
3055    }
3056
3057    private void upgradeToVersion409(SQLiteDatabase db) {
3058        db.execSQL("DROP TABLE IF EXISTS directories;");
3059        createDirectoriesTable(db);
3060    }
3061
3062    /**
3063     * Adding DEFAULT_DIRECTORY table.
3064     */
3065    private void upgradeToVersion411(SQLiteDatabase db) {
3066        db.execSQL("DROP TABLE IF EXISTS " + Tables.DEFAULT_DIRECTORY);
3067        db.execSQL("CREATE TABLE " + Tables.DEFAULT_DIRECTORY + " (" +
3068                Contacts._ID + " INTEGER PRIMARY KEY" +
3069        ");");
3070
3071        // Process contacts without an account
3072        db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
3073                " SELECT " + RawContacts.CONTACT_ID +
3074                " FROM " + Tables.RAW_CONTACTS +
3075                " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " +
3076                "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL ");
3077
3078        // Process accounts that don't have a default group (e.g. Exchange)
3079        db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
3080                " SELECT " + RawContacts.CONTACT_ID +
3081                " FROM " + Tables.RAW_CONTACTS +
3082                " WHERE NOT EXISTS" +
3083                " (SELECT " + Groups._ID +
3084                "  FROM " + Tables.GROUPS +
3085                "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
3086                        + GroupsColumns.CONCRETE_ACCOUNT_NAME +
3087                "    AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
3088                        + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
3089                "    AND " + Groups.AUTO_ADD + " != 0" +
3090                ")");
3091
3092        long mimetype = lookupMimeTypeId(db, GroupMembership.CONTENT_ITEM_TYPE);
3093
3094        // Process accounts that do have a default group (e.g. Google)
3095        db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY +
3096                " SELECT " + RawContacts.CONTACT_ID +
3097                " FROM " + Tables.RAW_CONTACTS +
3098                " JOIN " + Tables.DATA +
3099                "   ON (" + RawContactsColumns.CONCRETE_ID + "=" + Data.RAW_CONTACT_ID + ")" +
3100                " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimetype +
3101                " AND EXISTS" +
3102                " (SELECT " + Groups._ID +
3103                "  FROM " + Tables.GROUPS +
3104                "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
3105                        + GroupsColumns.CONCRETE_ACCOUNT_NAME +
3106                "    AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
3107                        + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
3108                "    AND " + Groups.AUTO_ADD + " != 0" +
3109                ")");
3110    }
3111
3112    private void upgradeToVersion413(SQLiteDatabase db) {
3113        db.execSQL("DROP TABLE IF EXISTS directories;");
3114        createDirectoriesTable(db);
3115    }
3116
3117    private void upgradeToVersion415(SQLiteDatabase db) {
3118        db.execSQL(
3119                "ALTER TABLE " + Tables.GROUPS +
3120                " ADD " + Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0");
3121        db.execSQL(
3122                "UPDATE " + Tables.GROUPS +
3123                "   SET " + Groups.GROUP_IS_READ_ONLY + "=1" +
3124                " WHERE " + Groups.SYSTEM_ID + " NOT NULL");
3125    }
3126
3127    private void upgradeToVersion416(SQLiteDatabase db) {
3128        db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP +
3129                " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");");
3130    }
3131
3132    private void upgradeToVersion501(SQLiteDatabase db) {
3133        // Remove organization rows from the name lookup, we now use search index for that
3134        db.execSQL("DELETE FROM name_lookup WHERE name_type=5");
3135    }
3136
3137    private void upgradeToVersion502(SQLiteDatabase db) {
3138        // Remove Chinese and Korean name lookup - this data is now in the search index
3139        db.execSQL("DELETE FROM name_lookup WHERE name_type IN (6, 7)");
3140    }
3141
3142    private void upgradeToVersion504(SQLiteDatabase db) {
3143        populateMimeTypeCache(db);
3144
3145        // Find all names with prefixes and recreate display name
3146        Cursor cursor = db.rawQuery(
3147                "SELECT " + StructuredName.RAW_CONTACT_ID +
3148                " FROM " + Tables.DATA +
3149                " WHERE " + DataColumns.MIMETYPE_ID + "=?"
3150                        + " AND " + StructuredName.PREFIX + " NOT NULL",
3151                new String[]{ String.valueOf(mMimeTypeIdStructuredName) });
3152
3153        try {
3154            while(cursor.moveToNext()) {
3155                long rawContactId = cursor.getLong(0);
3156                updateRawContactDisplayName(db, rawContactId);
3157            }
3158
3159        } finally {
3160            cursor.close();
3161        }
3162    }
3163
3164    private void upgradeToVersion600(SQLiteDatabase db) {
3165        // Add a column to the Accounts table to track which raw contact ID (if any) represents that
3166        // account's contribution to the user's profile Contact.
3167        db.execSQL("ALTER TABLE accounts" +
3168                " ADD profile_raw_contact_id INTEGER");
3169        db.execSQL("CREATE INDEX accounts_profile_raw_contact_id_index ON accounts" +
3170                " (profile_raw_contact_id);");
3171    }
3172
3173    private void upgradeToVersion601(SQLiteDatabase db) {
3174        db.execSQL("CREATE TABLE data_usage_stat(" +
3175                "stat_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3176                "data_id INTEGER NOT NULL, " +
3177                "usage_type INTEGER NOT NULL DEFAULT 0, " +
3178                "times_used INTEGER NOT NULL DEFAULT 0, " +
3179                "last_time_used INTERGER NOT NULL DEFAULT 0, " +
3180                "FOREIGN KEY(data_id) REFERENCES data(_id));");
3181        db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " +
3182                "data_usage_stat (data_id, usage_type)");
3183    }
3184
3185    private void upgradeToVersion602(SQLiteDatabase db) {
3186        db.execSQL("ALTER TABLE calls ADD voicemail_uri TEXT;");
3187        db.execSQL("ALTER TABLE calls ADD _data TEXT;");
3188        db.execSQL("ALTER TABLE calls ADD has_content INTEGER;");
3189        db.execSQL("ALTER TABLE calls ADD mime_type TEXT;");
3190        db.execSQL("ALTER TABLE calls ADD source_data TEXT;");
3191        db.execSQL("ALTER TABLE calls ADD source_package TEXT;");
3192        db.execSQL("ALTER TABLE calls ADD state INTEGER;");
3193    }
3194
3195    private void upgradeToVersion604(SQLiteDatabase db) {
3196        db.execSQL("CREATE TABLE voicemail_status (" +
3197                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
3198                "source_package TEXT UNIQUE NOT NULL," +
3199                "settings_uri TEXT," +
3200                "voicemail_access_uri TEXT," +
3201                "configuration_state INTEGER," +
3202                "data_channel_state INTEGER," +
3203                "notification_channel_state INTEGER" +
3204        ");");
3205    }
3206
3207    private void upgradeToVersion605(SQLiteDatabase db) {
3208        // This version used to create the stream item and stream item photos tables, but a newer
3209        // version of those tables is created in version 609 below.  So omitting the creation in
3210        // this upgrade step to avoid a create->drop->create.
3211    }
3212
3213    private void upgradeToVersion606(SQLiteDatabase db) {
3214        db.execSQL("DROP VIEW IF EXISTS view_contacts_restricted;");
3215        db.execSQL("DROP VIEW IF EXISTS view_data_restricted;");
3216        db.execSQL("DROP VIEW IF EXISTS view_raw_contacts_restricted;");
3217        db.execSQL("DROP VIEW IF EXISTS view_raw_entities_restricted;");
3218        db.execSQL("DROP VIEW IF EXISTS view_entities_restricted;");
3219        db.execSQL("DROP VIEW IF EXISTS view_data_usage_stat_restricted;");
3220        db.execSQL("DROP INDEX IF EXISTS contacts_restricted_index");
3221
3222        // We should remove the restricted columns here as well, but unfortunately SQLite doesn't
3223        // provide ALTER TABLE DROP COLUMN. As they have DEFAULT 0, we can keep but ignore them
3224    }
3225
3226    private void upgradeToVersion607(SQLiteDatabase db) {
3227        db.execSQL("ALTER TABLE groups ADD COLUMN action TEXT");
3228        db.execSQL("ALTER TABLE groups ADD COLUMN action_uri TEXT");
3229    }
3230
3231    private void upgradeToVersion608(SQLiteDatabase db) {
3232        db.execSQL("ALTER TABLE contacts ADD photo_file_id INTEGER REFERENCES photo_files(_id);");
3233
3234        db.execSQL("CREATE TABLE photo_files(" +
3235                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3236                "height INTEGER NOT NULL, " +
3237                "width INTEGER NOT NULL, " +
3238                "filesize INTEGER NOT NULL);");
3239    }
3240
3241    private void upgradeToVersion609(SQLiteDatabase db) {
3242        // The stream item and stream item photos APIs were not in-use by anyone in the time
3243        // between their initial creation (in v605) and this update.  So we're just dropping
3244        // and re-creating them to get appropriate columns.  The delta is as follows:
3245        // - In stream_items, package_id was replaced by res_package.
3246        // - In stream_item_photos, picture was replaced by photo_file_id.
3247
3248        db.execSQL("DROP TABLE IF EXISTS stream_items");
3249        db.execSQL("DROP TABLE IF EXISTS stream_item_photos");
3250
3251        db.execSQL("CREATE TABLE stream_items(" +
3252                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3253                "raw_contact_id INTEGER NOT NULL, " +
3254                "res_package TEXT, " +
3255                "icon INTEGER, " +
3256                "label INTEGER, " +
3257                "text TEXT NOT NULL, " +
3258                "timestamp INTEGER NOT NULL, " +
3259                "comments TEXT NOT NULL, " +
3260                "action TEXT, " +
3261                "action_uri TEXT, " +
3262                "FOREIGN KEY(raw_contact_id) REFERENCES raw_contacts(_id));");
3263
3264        db.execSQL("CREATE TABLE stream_item_photos(" +
3265                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
3266                "stream_item_id INTEGER NOT NULL, " +
3267                "sort_index INTEGER, " +
3268                "photo_file_id INTEGER NOT NULL, " +
3269                "action TEXT, " +
3270                "action_uri TEXT, " +
3271                "FOREIGN KEY(stream_item_id) REFERENCES stream_items(_id));");
3272    }
3273
3274    private void upgradeToVersion610(SQLiteDatabase db) {
3275        db.execSQL("ALTER TABLE calls ADD is_read INTEGER;");
3276    }
3277
3278    private void upgradeToVersion611(SQLiteDatabase db) {
3279        db.execSQL("ALTER TABLE raw_contacts ADD data_set TEXT DEFAULT NULL;");
3280        db.execSQL("ALTER TABLE groups ADD data_set TEXT DEFAULT NULL;");
3281        db.execSQL("ALTER TABLE accounts ADD data_set TEXT DEFAULT NULL;");
3282
3283        db.execSQL("CREATE INDEX raw_contacts_source_id_data_set_index ON raw_contacts " +
3284                "(sourceid, account_type, account_name, data_set);");
3285
3286        db.execSQL("CREATE INDEX groups_source_id_data_set_index ON groups " +
3287                "(sourceid, account_type, account_name, data_set);");
3288    }
3289
3290    private void upgradeToVersion612(SQLiteDatabase db) {
3291        db.execSQL("ALTER TABLE calls ADD geocoded_location TEXT DEFAULT NULL;");
3292        // Old calls will not have a geocoded location; new calls will get it when inserted.
3293    }
3294
3295    public String extractHandleFromEmailAddress(String email) {
3296        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
3297        if (tokens.length == 0) {
3298            return null;
3299        }
3300
3301        String address = tokens[0].getAddress();
3302        int at = address.indexOf('@');
3303        if (at != -1) {
3304            return address.substring(0, at);
3305        }
3306        return null;
3307    }
3308
3309    public String extractAddressFromEmailAddress(String email) {
3310        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
3311        if (tokens.length == 0) {
3312            return null;
3313        }
3314
3315        return tokens[0].getAddress().trim();
3316    }
3317
3318    private long lookupMimeTypeId(SQLiteDatabase db, String mimeType) {
3319        try {
3320            return DatabaseUtils.longForQuery(db,
3321                    "SELECT " + MimetypesColumns._ID +
3322                    " FROM " + Tables.MIMETYPES +
3323                    " WHERE " + MimetypesColumns.MIMETYPE
3324                            + "='" + mimeType + "'", null);
3325        } catch (SQLiteDoneException e) {
3326            // No rows of this type in the database
3327            return -1;
3328        }
3329    }
3330
3331    private void bindString(SQLiteStatement stmt, int index, String value) {
3332        if (value == null) {
3333            stmt.bindNull(index);
3334        } else {
3335            stmt.bindString(index, value);
3336        }
3337    }
3338
3339    private void bindLong(SQLiteStatement stmt, int index, Number value) {
3340        if (value == null) {
3341            stmt.bindNull(index);
3342        } else {
3343            stmt.bindLong(index, value.longValue());
3344        }
3345    }
3346
3347    /**
3348     * Adds index stats into the SQLite database to force it to always use the lookup indexes.
3349     */
3350    private void updateSqliteStats(SQLiteDatabase db) {
3351
3352        // Specific stats strings are based on an actual large database after running ANALYZE
3353        try {
3354            updateIndexStats(db, Tables.CONTACTS,
3355                    "contacts_has_phone_index", "10000 500");
3356
3357            updateIndexStats(db, Tables.RAW_CONTACTS,
3358                    "raw_contacts_source_id_index", "10000 1 1 1");
3359            updateIndexStats(db, Tables.RAW_CONTACTS,
3360                    "raw_contacts_contact_id_index", "10000 2");
3361
3362            updateIndexStats(db, Tables.NAME_LOOKUP,
3363                    "name_lookup_raw_contact_id_index", "10000 3");
3364            updateIndexStats(db, Tables.NAME_LOOKUP,
3365                    "name_lookup_index", "10000 3 2 2 1");
3366            updateIndexStats(db, Tables.NAME_LOOKUP,
3367                    "sqlite_autoindex_name_lookup_1", "10000 3 2 1");
3368
3369            updateIndexStats(db, Tables.PHONE_LOOKUP,
3370                    "phone_lookup_index", "10000 2 2 1");
3371            updateIndexStats(db, Tables.PHONE_LOOKUP,
3372                    "phone_lookup_min_match_index", "10000 2 2 1");
3373
3374            updateIndexStats(db, Tables.DATA,
3375                    "data_mimetype_data1_index", "60000 5000 2");
3376            updateIndexStats(db, Tables.DATA,
3377                    "data_raw_contact_id", "60000 10");
3378
3379            updateIndexStats(db, Tables.GROUPS,
3380                    "groups_source_id_index", "50 1 1 1");
3381
3382            updateIndexStats(db, Tables.NICKNAME_LOOKUP,
3383                    "sqlite_autoindex_name_lookup_1", "500 2 1");
3384
3385        } catch (SQLException e) {
3386            Log.e(TAG, "Could not update index stats", e);
3387        }
3388    }
3389
3390    /**
3391     * Stores statistics for a given index.
3392     *
3393     * @param stats has the following structure: the first index is the expected size of
3394     * the table.  The following integer(s) are the expected number of records selected with the
3395     * index.  There should be one integer per indexed column.
3396     */
3397    private void updateIndexStats(SQLiteDatabase db, String table, String index,
3398            String stats) {
3399        db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl='" + table + "' AND idx='" + index + "';");
3400        db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat)"
3401                + " VALUES ('" + table + "','" + index + "','" + stats + "');");
3402    }
3403
3404    @Override
3405    public synchronized SQLiteDatabase getWritableDatabase() {
3406        SQLiteDatabase db = super.getWritableDatabase();
3407        if (mReopenDatabase) {
3408            mReopenDatabase = false;
3409            close();
3410            db = super.getWritableDatabase();
3411        }
3412        return db;
3413    }
3414
3415    /**
3416     * Wipes all data except mime type and package lookup tables.
3417     */
3418    public void wipeData() {
3419        SQLiteDatabase db = getWritableDatabase();
3420
3421        db.execSQL("DELETE FROM " + Tables.ACCOUNTS + ";");
3422        db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL, NULL, NULL)");
3423
3424        db.execSQL("DELETE FROM " + Tables.CONTACTS + ";");
3425        db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";");
3426        db.execSQL("DELETE FROM " + Tables.STREAM_ITEMS + ";");
3427        db.execSQL("DELETE FROM " + Tables.STREAM_ITEM_PHOTOS + ";");
3428        db.execSQL("DELETE FROM " + Tables.PHOTO_FILES + ";");
3429        db.execSQL("DELETE FROM " + Tables.DATA + ";");
3430        db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";");
3431        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";");
3432        db.execSQL("DELETE FROM " + Tables.GROUPS + ";");
3433        db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";");
3434        db.execSQL("DELETE FROM " + Tables.SETTINGS + ";");
3435        db.execSQL("DELETE FROM " + Tables.ACTIVITIES + ";");
3436        db.execSQL("DELETE FROM " + Tables.CALLS + ";");
3437        db.execSQL("DELETE FROM " + Tables.DIRECTORIES + ";");
3438        db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + ";");
3439
3440        // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP
3441    }
3442
3443    public NameSplitter createNameSplitter() {
3444        mNameSplitter = new NameSplitter(
3445                mContext.getString(com.android.internal.R.string.common_name_prefixes),
3446                mContext.getString(com.android.internal.R.string.common_last_name_prefixes),
3447                mContext.getString(com.android.internal.R.string.common_name_suffixes),
3448                mContext.getString(com.android.internal.R.string.common_name_conjunctions),
3449                Locale.getDefault());
3450        return mNameSplitter;
3451    }
3452
3453    /**
3454     * Return the {@link ApplicationInfo#uid} for the given package name.
3455     */
3456    public static int getUidForPackageName(PackageManager pm, String packageName) {
3457        try {
3458            ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */);
3459            return clientInfo.uid;
3460        } catch (NameNotFoundException e) {
3461            throw new RuntimeException(e);
3462        }
3463    }
3464
3465    /**
3466     * Perform an internal string-to-integer lookup using the compiled
3467     * {@link SQLiteStatement} provided, using the in-memory cache to speed up
3468     * lookups. If a mapping isn't found in cache or database, it will be
3469     * created. All new, uncached answers are added to the cache automatically.
3470     *
3471     * @param query Compiled statement used to query for the mapping.
3472     * @param insert Compiled statement used to insert a new mapping when no
3473     *            existing one is found in cache or from query.
3474     * @param value Value to find mapping for.
3475     * @param cache In-memory cache of previous answers.
3476     * @return An unique integer mapping for the given value.
3477     */
3478    private long getCachedId(SQLiteStatement query, SQLiteStatement insert,
3479            String value, HashMap<String, Long> cache) {
3480        // Try an in-memory cache lookup
3481        if (cache.containsKey(value)) {
3482            return cache.get(value);
3483        }
3484
3485        synchronized (query) {
3486            long id = -1;
3487            try {
3488                // Try searching database for mapping
3489                DatabaseUtils.bindObjectToProgram(query, 1, value);
3490                id = query.simpleQueryForLong();
3491            } catch (SQLiteDoneException e) {
3492                // Nothing found, so try inserting new mapping
3493                DatabaseUtils.bindObjectToProgram(insert, 1, value);
3494                id = insert.executeInsert();
3495            }
3496            if (id != -1) {
3497                // Cache and return the new answer
3498                cache.put(value, id);
3499                return id;
3500            } else {
3501                // Otherwise throw if no mapping found or created
3502                throw new IllegalStateException("Couldn't find or create internal "
3503                        + "lookup table entry for value " + value);
3504            }
3505        }
3506    }
3507
3508    /**
3509     * Convert a package name into an integer, using {@link Tables#PACKAGES} for
3510     * lookups and possible allocation of new IDs as needed.
3511     */
3512    public long getPackageId(String packageName) {
3513        if (mPackageQuery == null) {
3514            mPackageQuery = getWritableDatabase().compileStatement(
3515                    "SELECT " + PackagesColumns._ID +
3516                    " FROM " + Tables.PACKAGES +
3517                    " WHERE " + PackagesColumns.PACKAGE + "=?");
3518
3519        }
3520        if (mPackageInsert == null) {
3521            mPackageInsert = getWritableDatabase().compileStatement(
3522                    "INSERT INTO " + Tables.PACKAGES + "("
3523                            + PackagesColumns.PACKAGE +
3524                    ") VALUES (?)");
3525        }
3526        return getCachedId(mPackageQuery, mPackageInsert, packageName, mPackageCache);
3527    }
3528
3529    /**
3530     * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for
3531     * lookups and possible allocation of new IDs as needed.
3532     */
3533    public long getMimeTypeId(String mimetype) {
3534        return getCachedId(mMimetypeQuery, mMimetypeInsert, mimetype, mMimetypeCache);
3535    }
3536
3537    public long getMimeTypeIdForStructuredName() {
3538        return mMimeTypeIdStructuredName;
3539    }
3540
3541    public long getMimeTypeIdForOrganization() {
3542        return mMimeTypeIdOrganization;
3543    }
3544
3545    public long getMimeTypeIdForIm() {
3546        return mMimeTypeIdIm;
3547    }
3548
3549    public long getMimeTypeIdForEmail() {
3550        return mMimeTypeIdEmail;
3551    }
3552
3553    public long getMimeTypeIdForSip() {
3554        return mMimeTypeIdSip;
3555    }
3556
3557    public int getDisplayNameSourceForMimeTypeId(int mimeTypeId) {
3558        if (mimeTypeId == mMimeTypeIdStructuredName) {
3559            return DisplayNameSources.STRUCTURED_NAME;
3560        } else if (mimeTypeId == mMimeTypeIdEmail) {
3561            return DisplayNameSources.EMAIL;
3562        } else if (mimeTypeId == mMimeTypeIdPhone) {
3563            return DisplayNameSources.PHONE;
3564        } else if (mimeTypeId == mMimeTypeIdOrganization) {
3565            return DisplayNameSources.ORGANIZATION;
3566        } else if (mimeTypeId == mMimeTypeIdNickname) {
3567            return DisplayNameSources.NICKNAME;
3568        } else {
3569            return DisplayNameSources.UNDEFINED;
3570        }
3571    }
3572
3573    /**
3574     * Find the mimetype for the given {@link Data#_ID}.
3575     */
3576    public String getDataMimeType(long dataId) {
3577        if (mDataMimetypeQuery == null) {
3578            mDataMimetypeQuery = getWritableDatabase().compileStatement(
3579                    "SELECT " + MimetypesColumns.MIMETYPE +
3580                    " FROM " + Tables.DATA_JOIN_MIMETYPES +
3581                    " WHERE " + Tables.DATA + "." + Data._ID + "=?");
3582        }
3583        try {
3584            // Try database query to find mimetype
3585            DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId);
3586            String mimetype = mDataMimetypeQuery.simpleQueryForString();
3587            return mimetype;
3588        } catch (SQLiteDoneException e) {
3589            // No valid mapping found, so return null
3590            return null;
3591        }
3592    }
3593
3594    /**
3595     * Find the mime-type for the given {@link Activities#_ID}.
3596     */
3597    public String getActivityMimeType(long activityId) {
3598        if (mActivitiesMimetypeQuery == null) {
3599            mActivitiesMimetypeQuery = getWritableDatabase().compileStatement(
3600                    "SELECT " + MimetypesColumns.MIMETYPE +
3601                    " FROM " + Tables.ACTIVITIES_JOIN_MIMETYPES +
3602                    " WHERE " + Tables.ACTIVITIES + "." + Activities._ID + "=?");
3603        }
3604        try {
3605            // Try database query to find mimetype
3606            DatabaseUtils.bindObjectToProgram(mActivitiesMimetypeQuery, 1, activityId);
3607            String mimetype = mActivitiesMimetypeQuery.simpleQueryForString();
3608            return mimetype;
3609        } catch (SQLiteDoneException e) {
3610            // No valid mapping found, so return null
3611            return null;
3612        }
3613    }
3614
3615    /**
3616     * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts.
3617     */
3618    public void updateAllVisible() {
3619        updateCustomContactVisibility(getWritableDatabase(), "");
3620    }
3621
3622    /**
3623     * Updates contact visibility and return true iff the visibility was actually changed.
3624     */
3625    public boolean updateContactVisibleOnlyIfChanged(TransactionContext txContext, long contactId) {
3626        return updateContactVisible(txContext, contactId, true);
3627    }
3628
3629    /**
3630     * Update {@link Contacts#IN_VISIBLE_GROUP} and
3631     * {@link Tables#DEFAULT_DIRECTORY} for a specific contact.
3632     */
3633    public void updateContactVisible(TransactionContext txContext, long contactId) {
3634        updateContactVisible(txContext, contactId, false);
3635    }
3636
3637    public boolean updateContactVisible(
3638            TransactionContext txContext, long contactId, boolean onlyIfChanged) {
3639        SQLiteDatabase db = getWritableDatabase();
3640        updateCustomContactVisibility(db, " AND " + Contacts._ID + "=" + contactId);
3641
3642        String contactIdAsString = String.valueOf(contactId);
3643        long mimetype = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3644
3645        // The contact will be included in the default directory if contains
3646        // a raw contact that is in any group or in an account that
3647        // does not have any AUTO_ADD groups.
3648        boolean newVisibility = DatabaseUtils.longForQuery(db,
3649                "SELECT EXISTS (" +
3650                    "SELECT " + RawContacts.CONTACT_ID +
3651                    " FROM " + Tables.RAW_CONTACTS +
3652                    " JOIN " + Tables.DATA +
3653                    "   ON (" + RawContactsColumns.CONCRETE_ID + "="
3654                            + Data.RAW_CONTACT_ID + ")" +
3655                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3656                    "   AND " + DataColumns.MIMETYPE_ID + "=?" +
3657                ") OR EXISTS (" +
3658                    "SELECT " + RawContacts._ID +
3659                    " FROM " + Tables.RAW_CONTACTS +
3660                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3661                    "   AND NOT EXISTS" +
3662                        " (SELECT " + Groups._ID +
3663                        "  FROM " + Tables.GROUPS +
3664                        "  WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = "
3665                                + GroupsColumns.CONCRETE_ACCOUNT_NAME +
3666                        "  AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = "
3667                                + GroupsColumns.CONCRETE_ACCOUNT_TYPE +
3668                        "  AND (" + RawContactsColumns.CONCRETE_DATA_SET + " = "
3669                                + GroupsColumns.CONCRETE_DATA_SET
3670                                + " OR " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL AND "
3671                                + GroupsColumns.CONCRETE_DATA_SET + " IS NULL)" +
3672                        "  AND " + Groups.AUTO_ADD + " != 0" +
3673                        ")" +
3674                ") OR EXISTS (" +
3675                    "SELECT " + RawContacts._ID +
3676                    " FROM " + Tables.RAW_CONTACTS +
3677                    " WHERE " + RawContacts.CONTACT_ID + "=?" +
3678                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " +
3679                    "   AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL" +
3680                    "   AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL" +
3681                ")",
3682                new String[] {
3683                    contactIdAsString,
3684                    String.valueOf(mimetype),
3685                    contactIdAsString,
3686                    contactIdAsString
3687                }) != 0;
3688
3689        if (onlyIfChanged) {
3690            boolean oldVisibility = isContactInDefaultDirectory(db, contactId);
3691            if (oldVisibility == newVisibility) {
3692                return false;
3693            }
3694        }
3695
3696        if (newVisibility) {
3697            db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " VALUES(?)",
3698                    new String[] { contactIdAsString });
3699            txContext.invalidateSearchIndexForContact(contactId);
3700        } else {
3701            db.execSQL("DELETE FROM " + Tables.DEFAULT_DIRECTORY +
3702                        " WHERE " + Contacts._ID + "=?",
3703                    new String[] { contactIdAsString });
3704            db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX +
3705                        " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
3706                    new String[] { contactIdAsString });
3707        }
3708        return true;
3709    }
3710
3711    public boolean isContactInDefaultDirectory(SQLiteDatabase db, long contactId) {
3712        if (mContactInDefaultDirectoryQuery == null) {
3713            mContactInDefaultDirectoryQuery = db.compileStatement(
3714                    "SELECT EXISTS (" +
3715                            "SELECT 1 FROM " + Tables.DEFAULT_DIRECTORY +
3716                            " WHERE " + Contacts._ID + "=?)");
3717        }
3718        mContactInDefaultDirectoryQuery.bindLong(1, contactId);
3719        return mContactInDefaultDirectoryQuery.simpleQueryForLong() != 0;
3720    }
3721
3722    private void updateCustomContactVisibility(SQLiteDatabase db, String selection) {
3723        final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
3724        String[] selectionArgs = new String[]{String.valueOf(groupMembershipMimetypeId)};
3725
3726        // First delete what needs to be deleted, then insert what needs to be added.
3727        // Since flash writes are very expensive, this approach is much better than
3728        // delete-all-insert-all.
3729        db.execSQL("DELETE FROM " + Tables.VISIBLE_CONTACTS +
3730                   " WHERE " + "_id NOT IN" +
3731                        "(SELECT " + Contacts._ID +
3732                        " FROM " + Tables.CONTACTS +
3733                        " WHERE (" + Clauses.CONTACT_IS_VISIBLE + ")=1) " + selection,
3734                selectionArgs);
3735
3736        db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS +
3737                   " SELECT " + Contacts._ID +
3738                   " FROM " + Tables.CONTACTS +
3739                   " WHERE " + Contacts._ID +
3740                   " NOT IN " + Tables.VISIBLE_CONTACTS +
3741                           " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=1 " + selection,
3742                selectionArgs);
3743    }
3744
3745    /**
3746     * Returns contact ID for the given contact or zero if it is NULL.
3747     */
3748    public long getContactId(long rawContactId) {
3749        if (mContactIdQuery == null) {
3750            mContactIdQuery = getWritableDatabase().compileStatement(
3751                    "SELECT " + RawContacts.CONTACT_ID +
3752                    " FROM " + Tables.RAW_CONTACTS +
3753                    " WHERE " + RawContacts._ID + "=?");
3754        }
3755        try {
3756            DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId);
3757            return mContactIdQuery.simpleQueryForLong();
3758        } catch (SQLiteDoneException e) {
3759            // No valid mapping found, so return 0
3760            return 0;
3761        }
3762    }
3763
3764    public int getAggregationMode(long rawContactId) {
3765        if (mAggregationModeQuery == null) {
3766            mAggregationModeQuery = getWritableDatabase().compileStatement(
3767                    "SELECT " + RawContacts.AGGREGATION_MODE +
3768                    " FROM " + Tables.RAW_CONTACTS +
3769                    " WHERE " + RawContacts._ID + "=?");
3770        }
3771        try {
3772            DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId);
3773            return (int)mAggregationModeQuery.simpleQueryForLong();
3774        } catch (SQLiteDoneException e) {
3775            // No valid row found, so return "disabled"
3776            return RawContacts.AGGREGATION_MODE_DISABLED;
3777        }
3778    }
3779
3780    public void buildPhoneLookupAndContactQuery(
3781            SQLiteQueryBuilder qb, String normalizedNumber, String numberE164) {
3782        String minMatch = PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber);
3783        StringBuilder sb = new StringBuilder();
3784        appendPhoneLookupTables(sb, minMatch, true);
3785        qb.setTables(sb.toString());
3786
3787        sb = new StringBuilder();
3788        appendPhoneLookupSelection(sb, normalizedNumber, numberE164);
3789        qb.appendWhere(sb.toString());
3790    }
3791
3792    public String buildPhoneLookupAsNestedQuery(String number) {
3793        StringBuilder sb = new StringBuilder();
3794        final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
3795        sb.append("(SELECT DISTINCT raw_contact_id" + " FROM ");
3796        appendPhoneLookupTables(sb, minMatch, false);
3797        sb.append(" WHERE ");
3798        appendPhoneLookupSelection(sb, number, null);
3799        sb.append(")");
3800        return sb.toString();
3801    }
3802
3803    private void appendPhoneLookupTables(StringBuilder sb, final String minMatch,
3804            boolean joinContacts) {
3805        sb.append(Tables.RAW_CONTACTS);
3806        if (joinContacts) {
3807            sb.append(" JOIN " + Views.CONTACTS + " contacts_view"
3808                    + " ON (contacts_view._id = raw_contacts.contact_id)");
3809        }
3810        sb.append(", (SELECT data_id, normalized_number, length(normalized_number) as len "
3811                + " FROM phone_lookup " + " WHERE (" + Tables.PHONE_LOOKUP + "."
3812                + PhoneLookupColumns.MIN_MATCH + " = '");
3813        sb.append(minMatch);
3814        sb.append("')) AS lookup, " + Tables.DATA);
3815    }
3816
3817    private void appendPhoneLookupSelection(StringBuilder sb, String number, String numberE164) {
3818        sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id");
3819        boolean hasNumberE164 = !TextUtils.isEmpty(numberE164);
3820        boolean hasNumber = !TextUtils.isEmpty(number);
3821        if (hasNumberE164 || hasNumber) {
3822            sb.append(" AND ( ");
3823            if (hasNumberE164) {
3824                sb.append(" lookup.normalized_number = ");
3825                DatabaseUtils.appendEscapedSQLString(sb, numberE164);
3826            }
3827            if (hasNumberE164 && hasNumber) {
3828                sb.append(" OR ");
3829            }
3830            if (hasNumber) {
3831                int numberLen = number.length();
3832                sb.append(" lookup.len <= ");
3833                sb.append(numberLen);
3834                sb.append(" AND substr(");
3835                DatabaseUtils.appendEscapedSQLString(sb, number);
3836                sb.append(',');
3837                sb.append(numberLen);
3838                sb.append(" - lookup.len + 1) = lookup.normalized_number");
3839            }
3840            sb.append(')');
3841        }
3842    }
3843
3844    public String getUseStrictPhoneNumberComparisonParameter() {
3845        return mUseStrictPhoneNumberComparison ? "1" : "0";
3846    }
3847
3848    /**
3849     * Loads common nickname mappings into the database.
3850     */
3851    private void loadNicknameLookupTable(SQLiteDatabase db) {
3852        db.execSQL("DELETE FROM " + Tables.NICKNAME_LOOKUP);
3853
3854        String[] strings = mContext.getResources().getStringArray(
3855                com.android.internal.R.array.common_nicknames);
3856        if (strings == null || strings.length == 0) {
3857            return;
3858        }
3859
3860        SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO "
3861                + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + ","
3862                + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)");
3863
3864        try {
3865            for (int clusterId = 0; clusterId < strings.length; clusterId++) {
3866                String[] names = strings[clusterId].split(",");
3867                for (int j = 0; j < names.length; j++) {
3868                    String name = NameNormalizer.normalize(names[j]);
3869                    try {
3870                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name);
3871                        DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2,
3872                                String.valueOf(clusterId));
3873                        nicknameLookupInsert.executeInsert();
3874                    } catch (SQLiteException e) {
3875
3876                        // Print the exception and keep going - this is not a fatal error
3877                        Log.e(TAG, "Cannot insert nickname: " + names[j], e);
3878                    }
3879                }
3880            }
3881        } finally {
3882            nicknameLookupInsert.close();
3883        }
3884    }
3885
3886    public static void copyStringValue(ContentValues toValues, String toKey,
3887            ContentValues fromValues, String fromKey) {
3888        if (fromValues.containsKey(fromKey)) {
3889            toValues.put(toKey, fromValues.getAsString(fromKey));
3890        }
3891    }
3892
3893    public static void copyLongValue(ContentValues toValues, String toKey,
3894            ContentValues fromValues, String fromKey) {
3895        if (fromValues.containsKey(fromKey)) {
3896            long longValue;
3897            Object value = fromValues.get(fromKey);
3898            if (value instanceof Boolean) {
3899                if ((Boolean)value) {
3900                    longValue = 1;
3901                } else {
3902                    longValue = 0;
3903                }
3904            } else if (value instanceof String) {
3905                longValue = Long.parseLong((String)value);
3906            } else {
3907                longValue = ((Number)value).longValue();
3908            }
3909            toValues.put(toKey, longValue);
3910        }
3911    }
3912
3913    public SyncStateContentProviderHelper getSyncState() {
3914        return mSyncState;
3915    }
3916
3917    /**
3918     * Delete the aggregate contact if it has no constituent raw contacts other
3919     * than the supplied one.
3920     */
3921    public void removeContactIfSingleton(long rawContactId) {
3922        SQLiteDatabase db = getWritableDatabase();
3923
3924        // Obtain contact ID from the supplied raw contact ID
3925        String contactIdFromRawContactId = "(SELECT " + RawContacts.CONTACT_ID + " FROM "
3926                + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=" + rawContactId + ")";
3927
3928        // Find other raw contacts in the same aggregate contact
3929        String otherRawContacts = "(SELECT contacts1." + RawContacts._ID + " FROM "
3930                + Tables.RAW_CONTACTS + " contacts1 JOIN " + Tables.RAW_CONTACTS + " contacts2 ON ("
3931                + "contacts1." + RawContacts.CONTACT_ID + "=contacts2." + RawContacts.CONTACT_ID
3932                + ") WHERE contacts1." + RawContacts._ID + "!=" + rawContactId + ""
3933                + " AND contacts2." + RawContacts._ID + "=" + rawContactId + ")";
3934
3935        db.execSQL("DELETE FROM " + Tables.CONTACTS
3936                + " WHERE " + Contacts._ID + "=" + contactIdFromRawContactId
3937                + " AND NOT EXISTS " + otherRawContacts + ";");
3938    }
3939
3940    /**
3941     * Returns the value from the {@link Tables#PROPERTIES} table.
3942     */
3943    public String getProperty(String key, String defaultValue) {
3944        Cursor cursor = getReadableDatabase().query(Tables.PROPERTIES,
3945                new String[]{PropertiesColumns.PROPERTY_VALUE},
3946                PropertiesColumns.PROPERTY_KEY + "=?",
3947                new String[]{key}, null, null, null);
3948        String value = null;
3949        try {
3950            if (cursor.moveToFirst()) {
3951                value = cursor.getString(0);
3952            }
3953        } finally {
3954            cursor.close();
3955        }
3956
3957        return value != null ? value : defaultValue;
3958    }
3959
3960    /**
3961     * Stores a key-value pair in the {@link Tables#PROPERTIES} table.
3962     */
3963    public void setProperty(String key, String value) {
3964        setProperty(getWritableDatabase(), key, value);
3965    }
3966
3967    private void setProperty(SQLiteDatabase db, String key, String value) {
3968        ContentValues values = new ContentValues();
3969        values.put(PropertiesColumns.PROPERTY_KEY, key);
3970        values.put(PropertiesColumns.PROPERTY_VALUE, value);
3971        db.replace(Tables.PROPERTIES, null, values);
3972    }
3973
3974    /**
3975     * Test if any of the columns appear in the given projection.
3976     */
3977    public boolean isInProjection(String[] projection, String... columns) {
3978        if (projection == null) {
3979            return true;
3980        }
3981
3982        // Optimized for a single-column test
3983        if (columns.length == 1) {
3984            String column = columns[0];
3985            for (String test : projection) {
3986                if (column.equals(test)) {
3987                    return true;
3988                }
3989            }
3990        } else {
3991            for (String test : projection) {
3992                for (String column : columns) {
3993                    if (column.equals(test)) {
3994                        return true;
3995                    }
3996                }
3997            }
3998        }
3999        return false;
4000    }
4001
4002    /**
4003     * Returns a detailed exception message for the supplied URI.  It includes the calling
4004     * user and calling package(s).
4005     */
4006    public String exceptionMessage(Uri uri) {
4007        return exceptionMessage(null, uri);
4008    }
4009
4010    /**
4011     * Returns a detailed exception message for the supplied URI.  It includes the calling
4012     * user and calling package(s).
4013     */
4014    public String exceptionMessage(String message, Uri uri) {
4015        StringBuilder sb = new StringBuilder();
4016        if (message != null) {
4017            sb.append(message).append("; ");
4018        }
4019        sb.append("URI: ").append(uri);
4020        final PackageManager pm = mContext.getPackageManager();
4021        int callingUid = Binder.getCallingUid();
4022        sb.append(", calling user: ");
4023        String userName = pm.getNameForUid(callingUid);
4024        if (userName != null) {
4025            sb.append(userName);
4026        } else {
4027            sb.append(callingUid);
4028        }
4029
4030        final String[] callerPackages = pm.getPackagesForUid(callingUid);
4031        if (callerPackages != null && callerPackages.length > 0) {
4032            if (callerPackages.length == 1) {
4033                sb.append(", calling package:");
4034                sb.append(callerPackages[0]);
4035            } else {
4036                sb.append(", calling package is one of: [");
4037                for (int i = 0; i < callerPackages.length; i++) {
4038                    if (i != 0) {
4039                        sb.append(", ");
4040                    }
4041                    sb.append(callerPackages[i]);
4042                }
4043                sb.append("]");
4044            }
4045        }
4046
4047        return sb.toString();
4048    }
4049
4050    protected String getCountryIso() {
4051        CountryDetector detector =
4052            (CountryDetector) mContext.getSystemService(Context.COUNTRY_DETECTOR);
4053        return detector.detectCountry().getCountryIso();
4054    }
4055
4056    public void deleteStatusUpdate(long dataId) {
4057        if (mStatusUpdateDelete == null) {
4058            mStatusUpdateDelete = getWritableDatabase().compileStatement(
4059                    "DELETE FROM " + Tables.STATUS_UPDATES +
4060                    " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
4061        }
4062        mStatusUpdateDelete.bindLong(1, dataId);
4063        mStatusUpdateDelete.execute();
4064    }
4065
4066    public void replaceStatusUpdate(Long dataId, long timestamp, String status, String resPackage,
4067            Long iconResource, Integer labelResource) {
4068        if (mStatusUpdateReplace == null) {
4069            mStatusUpdateReplace = getWritableDatabase().compileStatement(
4070                    "INSERT OR REPLACE INTO " + Tables.STATUS_UPDATES + "("
4071                            + StatusUpdatesColumns.DATA_ID + ", "
4072                            + StatusUpdates.STATUS_TIMESTAMP + ","
4073                            + StatusUpdates.STATUS + ","
4074                            + StatusUpdates.STATUS_RES_PACKAGE + ","
4075                            + StatusUpdates.STATUS_ICON + ","
4076                            + StatusUpdates.STATUS_LABEL + ")" +
4077                    " VALUES (?,?,?,?,?,?)");
4078        }
4079        mStatusUpdateReplace.bindLong(1, dataId);
4080        mStatusUpdateReplace.bindLong(2, timestamp);
4081        bindString(mStatusUpdateReplace, 3, status);
4082        bindString(mStatusUpdateReplace, 4, resPackage);
4083        bindLong(mStatusUpdateReplace, 5, iconResource);
4084        bindLong(mStatusUpdateReplace, 6, labelResource);
4085        mStatusUpdateReplace.execute();
4086    }
4087
4088    public void insertStatusUpdate(Long dataId, String status, String resPackage, Long iconResource,
4089            Integer labelResource) {
4090        if (mStatusUpdateInsert == null) {
4091            mStatusUpdateInsert = getWritableDatabase().compileStatement(
4092                    "INSERT INTO " + Tables.STATUS_UPDATES + "("
4093                            + StatusUpdatesColumns.DATA_ID + ", "
4094                            + StatusUpdates.STATUS + ","
4095                            + StatusUpdates.STATUS_RES_PACKAGE + ","
4096                            + StatusUpdates.STATUS_ICON + ","
4097                            + StatusUpdates.STATUS_LABEL + ")" +
4098                    " VALUES (?,?,?,?,?)");
4099        }
4100        try {
4101            mStatusUpdateInsert.bindLong(1, dataId);
4102            bindString(mStatusUpdateInsert, 2, status);
4103            bindString(mStatusUpdateInsert, 3, resPackage);
4104            bindLong(mStatusUpdateInsert, 4, iconResource);
4105            bindLong(mStatusUpdateInsert, 5, labelResource);
4106            mStatusUpdateInsert.executeInsert();
4107        } catch (SQLiteConstraintException e) {
4108            // The row already exists - update it
4109            if (mStatusUpdateAutoTimestamp == null) {
4110                mStatusUpdateAutoTimestamp = getWritableDatabase().compileStatement(
4111                        "UPDATE " + Tables.STATUS_UPDATES +
4112                        " SET " + StatusUpdates.STATUS_TIMESTAMP + "=?,"
4113                                + StatusUpdates.STATUS + "=?" +
4114                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"
4115                                + " AND " + StatusUpdates.STATUS + "!=?");
4116            }
4117
4118            long timestamp = System.currentTimeMillis();
4119            mStatusUpdateAutoTimestamp.bindLong(1, timestamp);
4120            bindString(mStatusUpdateAutoTimestamp, 2, status);
4121            mStatusUpdateAutoTimestamp.bindLong(3, dataId);
4122            bindString(mStatusUpdateAutoTimestamp, 4, status);
4123            mStatusUpdateAutoTimestamp.execute();
4124
4125            if (mStatusAttributionUpdate == null) {
4126                mStatusAttributionUpdate = getWritableDatabase().compileStatement(
4127                        "UPDATE " + Tables.STATUS_UPDATES +
4128                        " SET " + StatusUpdates.STATUS_RES_PACKAGE + "=?,"
4129                                + StatusUpdates.STATUS_ICON + "=?,"
4130                                + StatusUpdates.STATUS_LABEL + "=?" +
4131                        " WHERE " + StatusUpdatesColumns.DATA_ID + "=?");
4132            }
4133            bindString(mStatusAttributionUpdate, 1, resPackage);
4134            bindLong(mStatusAttributionUpdate, 2, iconResource);
4135            bindLong(mStatusAttributionUpdate, 3, labelResource);
4136            mStatusAttributionUpdate.bindLong(4, dataId);
4137            mStatusAttributionUpdate.execute();
4138        }
4139    }
4140
4141    /**
4142     * Resets the {@link RawContacts#NAME_VERIFIED} flag to 0 on all other raw
4143     * contacts in the same aggregate
4144     */
4145    public void resetNameVerifiedForOtherRawContacts(long rawContactId) {
4146        if (mResetNameVerifiedForOtherRawContacts == null) {
4147            mResetNameVerifiedForOtherRawContacts = getWritableDatabase().compileStatement(
4148                    "UPDATE " + Tables.RAW_CONTACTS +
4149                    " SET " + RawContacts.NAME_VERIFIED + "=0" +
4150                    " WHERE " + RawContacts.CONTACT_ID + "=(" +
4151                            "SELECT " + RawContacts.CONTACT_ID +
4152                            " FROM " + Tables.RAW_CONTACTS +
4153                            " WHERE " + RawContacts._ID + "=?)" +
4154                    " AND " + RawContacts._ID + "!=?");
4155        }
4156        mResetNameVerifiedForOtherRawContacts.bindLong(1, rawContactId);
4157        mResetNameVerifiedForOtherRawContacts.bindLong(2, rawContactId);
4158        mResetNameVerifiedForOtherRawContacts.execute();
4159    }
4160
4161    private interface RawContactNameQuery {
4162        public static final String RAW_SQL =
4163                "SELECT "
4164                        + DataColumns.MIMETYPE_ID + ","
4165                        + Data.IS_PRIMARY + ","
4166                        + Data.DATA1 + ","
4167                        + Data.DATA2 + ","
4168                        + Data.DATA3 + ","
4169                        + Data.DATA4 + ","
4170                        + Data.DATA5 + ","
4171                        + Data.DATA6 + ","
4172                        + Data.DATA7 + ","
4173                        + Data.DATA8 + ","
4174                        + Data.DATA9 + ","
4175                        + Data.DATA10 + ","
4176                        + Data.DATA11 +
4177                " FROM " + Tables.DATA +
4178                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
4179                        " AND (" + Data.DATA1 + " NOT NULL OR " +
4180                                Organization.TITLE + " NOT NULL)";
4181
4182        public static final int MIMETYPE = 0;
4183        public static final int IS_PRIMARY = 1;
4184        public static final int DATA1 = 2;
4185        public static final int GIVEN_NAME = 3;                         // data2
4186        public static final int FAMILY_NAME = 4;                        // data3
4187        public static final int PREFIX = 5;                             // data4
4188        public static final int TITLE = 5;                              // data4
4189        public static final int MIDDLE_NAME = 6;                        // data5
4190        public static final int SUFFIX = 7;                             // data6
4191        public static final int PHONETIC_GIVEN_NAME = 8;                // data7
4192        public static final int PHONETIC_MIDDLE_NAME = 9;               // data8
4193        public static final int ORGANIZATION_PHONETIC_NAME = 9;         // data8
4194        public static final int PHONETIC_FAMILY_NAME = 10;              // data9
4195        public static final int FULL_NAME_STYLE = 11;                   // data10
4196        public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11;  // data10
4197        public static final int PHONETIC_NAME_STYLE = 12;               // data11
4198    }
4199
4200    /**
4201     * Updates a raw contact display name based on data rows, e.g. structured name,
4202     * organization, email etc.
4203     */
4204    public void updateRawContactDisplayName(SQLiteDatabase db, long rawContactId) {
4205        if (mNameSplitter == null) {
4206            createNameSplitter();
4207        }
4208
4209        int bestDisplayNameSource = DisplayNameSources.UNDEFINED;
4210        NameSplitter.Name bestName = null;
4211        String bestDisplayName = null;
4212        String bestPhoneticName = null;
4213        int bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4214
4215        mSelectionArgs1[0] = String.valueOf(rawContactId);
4216        Cursor c = db.rawQuery(RawContactNameQuery.RAW_SQL, mSelectionArgs1);
4217        try {
4218            while (c.moveToNext()) {
4219                int mimeType = c.getInt(RawContactNameQuery.MIMETYPE);
4220                int source = getDisplayNameSourceForMimeTypeId(mimeType);
4221                if (source < bestDisplayNameSource || source == DisplayNameSources.UNDEFINED) {
4222                    continue;
4223                }
4224
4225                if (source == bestDisplayNameSource
4226                        && c.getInt(RawContactNameQuery.IS_PRIMARY) == 0) {
4227                    continue;
4228                }
4229
4230                if (mimeType == getMimeTypeIdForStructuredName()) {
4231                    NameSplitter.Name name;
4232                    if (bestName != null) {
4233                        name = new NameSplitter.Name();
4234                    } else {
4235                        name = mName;
4236                        name.clear();
4237                    }
4238                    name.prefix = c.getString(RawContactNameQuery.PREFIX);
4239                    name.givenNames = c.getString(RawContactNameQuery.GIVEN_NAME);
4240                    name.middleName = c.getString(RawContactNameQuery.MIDDLE_NAME);
4241                    name.familyName = c.getString(RawContactNameQuery.FAMILY_NAME);
4242                    name.suffix = c.getString(RawContactNameQuery.SUFFIX);
4243                    name.fullNameStyle = c.isNull(RawContactNameQuery.FULL_NAME_STYLE)
4244                            ? FullNameStyle.UNDEFINED
4245                            : c.getInt(RawContactNameQuery.FULL_NAME_STYLE);
4246                    name.phoneticFamilyName = c.getString(RawContactNameQuery.PHONETIC_FAMILY_NAME);
4247                    name.phoneticMiddleName = c.getString(RawContactNameQuery.PHONETIC_MIDDLE_NAME);
4248                    name.phoneticGivenName = c.getString(RawContactNameQuery.PHONETIC_GIVEN_NAME);
4249                    name.phoneticNameStyle = c.isNull(RawContactNameQuery.PHONETIC_NAME_STYLE)
4250                            ? PhoneticNameStyle.UNDEFINED
4251                            : c.getInt(RawContactNameQuery.PHONETIC_NAME_STYLE);
4252                    if (!name.isEmpty()) {
4253                        bestDisplayNameSource = source;
4254                        bestName = name;
4255                    }
4256                } else if (mimeType == getMimeTypeIdForOrganization()) {
4257                    mCharArrayBuffer.sizeCopied = 0;
4258                    c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer);
4259                    if (mCharArrayBuffer.sizeCopied != 0) {
4260                        bestDisplayNameSource = source;
4261                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
4262                                mCharArrayBuffer.sizeCopied);
4263                        bestPhoneticName = c.getString(
4264                                RawContactNameQuery.ORGANIZATION_PHONETIC_NAME);
4265                        bestPhoneticNameStyle =
4266                                c.isNull(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE)
4267                                   ? PhoneticNameStyle.UNDEFINED
4268                                   : c.getInt(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE);
4269                    } else {
4270                        c.copyStringToBuffer(RawContactNameQuery.TITLE, mCharArrayBuffer);
4271                        if (mCharArrayBuffer.sizeCopied != 0) {
4272                            bestDisplayNameSource = source;
4273                            bestDisplayName = new String(mCharArrayBuffer.data, 0,
4274                                    mCharArrayBuffer.sizeCopied);
4275                            bestPhoneticName = null;
4276                            bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4277                        }
4278                    }
4279                } else {
4280                    // Display name is at DATA1 in all other types.
4281                    // This is ensured in the constructor.
4282
4283                    mCharArrayBuffer.sizeCopied = 0;
4284                    c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer);
4285                    if (mCharArrayBuffer.sizeCopied != 0) {
4286                        bestDisplayNameSource = source;
4287                        bestDisplayName = new String(mCharArrayBuffer.data, 0,
4288                                mCharArrayBuffer.sizeCopied);
4289                        bestPhoneticName = null;
4290                        bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED;
4291                    }
4292                }
4293            }
4294
4295        } finally {
4296            c.close();
4297        }
4298
4299        String displayNamePrimary;
4300        String displayNameAlternative;
4301        String sortNamePrimary;
4302        String sortNameAlternative;
4303        String sortKeyPrimary = null;
4304        String sortKeyAlternative = null;
4305        int displayNameStyle = FullNameStyle.UNDEFINED;
4306
4307        if (bestDisplayNameSource == DisplayNameSources.STRUCTURED_NAME) {
4308            displayNameStyle = bestName.fullNameStyle;
4309            if (displayNameStyle == FullNameStyle.CJK
4310                    || displayNameStyle == FullNameStyle.UNDEFINED) {
4311                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
4312                bestName.fullNameStyle = displayNameStyle;
4313            }
4314
4315            displayNamePrimary = mNameSplitter.join(bestName, true, true);
4316            displayNameAlternative = mNameSplitter.join(bestName, false, true);
4317
4318            if (TextUtils.isEmpty(bestName.prefix)) {
4319                sortNamePrimary = displayNamePrimary;
4320                sortNameAlternative = displayNameAlternative;
4321            } else {
4322                sortNamePrimary = mNameSplitter.join(bestName, true, false);
4323                sortNameAlternative = mNameSplitter.join(bestName, false, false);
4324            }
4325
4326            bestPhoneticName = mNameSplitter.joinPhoneticName(bestName);
4327            bestPhoneticNameStyle = bestName.phoneticNameStyle;
4328        } else {
4329            displayNamePrimary = displayNameAlternative = bestDisplayName;
4330            sortNamePrimary = sortNameAlternative = bestDisplayName;
4331        }
4332
4333        if (bestPhoneticName != null) {
4334            sortKeyPrimary = sortKeyAlternative = bestPhoneticName;
4335            if (bestPhoneticNameStyle == PhoneticNameStyle.UNDEFINED) {
4336                bestPhoneticNameStyle = mNameSplitter.guessPhoneticNameStyle(bestPhoneticName);
4337            }
4338        } else {
4339            if (displayNameStyle == FullNameStyle.UNDEFINED) {
4340                displayNameStyle = mNameSplitter.guessFullNameStyle(bestDisplayName);
4341                if (displayNameStyle == FullNameStyle.UNDEFINED
4342                        || displayNameStyle == FullNameStyle.CJK) {
4343                    displayNameStyle = mNameSplitter.getAdjustedNameStyleBasedOnPhoneticNameStyle(
4344                            displayNameStyle, bestPhoneticNameStyle);
4345                }
4346                displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle);
4347            }
4348            if (displayNameStyle == FullNameStyle.CHINESE ||
4349                    displayNameStyle == FullNameStyle.CJK) {
4350                sortKeyPrimary = sortKeyAlternative =
4351                        ContactLocaleUtils.getIntance().getSortKey(
4352                                sortNamePrimary, displayNameStyle);
4353            }
4354        }
4355
4356        if (sortKeyPrimary == null) {
4357            sortKeyPrimary = sortNamePrimary;
4358            sortKeyAlternative = sortNameAlternative;
4359        }
4360
4361        if (mRawContactDisplayNameUpdate == null) {
4362            mRawContactDisplayNameUpdate = db.compileStatement(
4363                    "UPDATE " + Tables.RAW_CONTACTS +
4364                    " SET " +
4365                            RawContacts.DISPLAY_NAME_SOURCE + "=?," +
4366                            RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
4367                            RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
4368                            RawContacts.PHONETIC_NAME + "=?," +
4369                            RawContacts.PHONETIC_NAME_STYLE + "=?," +
4370                            RawContacts.SORT_KEY_PRIMARY + "=?," +
4371                            RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
4372                    " WHERE " + RawContacts._ID + "=?");
4373        }
4374
4375        mRawContactDisplayNameUpdate.bindLong(1, bestDisplayNameSource);
4376        bindString(mRawContactDisplayNameUpdate, 2, displayNamePrimary);
4377        bindString(mRawContactDisplayNameUpdate, 3, displayNameAlternative);
4378        bindString(mRawContactDisplayNameUpdate, 4, bestPhoneticName);
4379        mRawContactDisplayNameUpdate.bindLong(5, bestPhoneticNameStyle);
4380        bindString(mRawContactDisplayNameUpdate, 6, sortKeyPrimary);
4381        bindString(mRawContactDisplayNameUpdate, 7, sortKeyAlternative);
4382        mRawContactDisplayNameUpdate.bindLong(8, rawContactId);
4383        mRawContactDisplayNameUpdate.execute();
4384    }
4385
4386    /*
4387     * Sets the given dataId record in the "data" table to primary, and resets all data records of
4388     * the same mimetype and under the same contact to not be primary.
4389     *
4390     * @param dataId the id of the data record to be set to primary. Pass -1 to clear the primary
4391     * flag of all data items of this raw contacts
4392     */
4393    public void setIsPrimary(long rawContactId, long dataId, long mimeTypeId) {
4394        if (mSetPrimaryStatement == null) {
4395            mSetPrimaryStatement = getWritableDatabase().compileStatement(
4396                    "UPDATE " + Tables.DATA +
4397                    " SET " + Data.IS_PRIMARY + "=(_id=?)" +
4398                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4399                    "   AND " + Data.RAW_CONTACT_ID + "=?");
4400        }
4401        mSetPrimaryStatement.bindLong(1, dataId);
4402        mSetPrimaryStatement.bindLong(2, mimeTypeId);
4403        mSetPrimaryStatement.bindLong(3, rawContactId);
4404        mSetPrimaryStatement.execute();
4405    }
4406
4407    /*
4408     * Clears the super primary of all data items of the given raw contact. does not touch
4409     * other raw contacts of the same joined aggregate
4410     */
4411    public void clearSuperPrimary(long rawContactId, long mimeTypeId) {
4412        if (mClearSuperPrimaryStatement == null) {
4413            mClearSuperPrimaryStatement = getWritableDatabase().compileStatement(
4414                    "UPDATE " + Tables.DATA +
4415                    " SET " + Data.IS_SUPER_PRIMARY + "=0" +
4416                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4417                    "   AND " + Data.RAW_CONTACT_ID + "=?");
4418        }
4419        mClearSuperPrimaryStatement.bindLong(1, mimeTypeId);
4420        mClearSuperPrimaryStatement.bindLong(2, rawContactId);
4421        mClearSuperPrimaryStatement.execute();
4422    }
4423
4424    /*
4425     * Sets the given dataId record in the "data" table to "super primary", and resets all data
4426     * records of the same mimetype and under the same aggregate to not be "super primary".
4427     *
4428     * @param dataId the id of the data record to be set to primary.
4429     */
4430    public void setIsSuperPrimary(long rawContactId, long dataId, long mimeTypeId) {
4431        if (mSetSuperPrimaryStatement == null) {
4432            mSetSuperPrimaryStatement = getWritableDatabase().compileStatement(
4433                    "UPDATE " + Tables.DATA +
4434                    " SET " + Data.IS_SUPER_PRIMARY + "=(" + Data._ID + "=?)" +
4435                    " WHERE " + DataColumns.MIMETYPE_ID + "=?" +
4436                    "   AND " + Data.RAW_CONTACT_ID + " IN (" +
4437                            "SELECT " + RawContacts._ID +
4438                            " FROM " + Tables.RAW_CONTACTS +
4439                            " WHERE " + RawContacts.CONTACT_ID + " =(" +
4440                                    "SELECT " + RawContacts.CONTACT_ID +
4441                                    " FROM " + Tables.RAW_CONTACTS +
4442                                    " WHERE " + RawContacts._ID + "=?))");
4443        }
4444        mSetSuperPrimaryStatement.bindLong(1, dataId);
4445        mSetSuperPrimaryStatement.bindLong(2, mimeTypeId);
4446        mSetSuperPrimaryStatement.bindLong(3, rawContactId);
4447        mSetSuperPrimaryStatement.execute();
4448    }
4449
4450    /**
4451     * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
4452     */
4453    public void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) {
4454        if (TextUtils.isEmpty(name)) {
4455            return;
4456        }
4457
4458        if (mNameLookupInsert == null) {
4459            mNameLookupInsert = getWritableDatabase().compileStatement(
4460                    "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
4461                            + NameLookupColumns.RAW_CONTACT_ID + ","
4462                            + NameLookupColumns.DATA_ID + ","
4463                            + NameLookupColumns.NAME_TYPE + ","
4464                            + NameLookupColumns.NORMALIZED_NAME
4465                    + ") VALUES (?,?,?,?)");
4466        }
4467        mNameLookupInsert.bindLong(1, rawContactId);
4468        mNameLookupInsert.bindLong(2, dataId);
4469        mNameLookupInsert.bindLong(3, lookupType);
4470        bindString(mNameLookupInsert, 4, name);
4471        mNameLookupInsert.executeInsert();
4472    }
4473
4474    /**
4475     * Deletes all {@link Tables#NAME_LOOKUP} table rows associated with the specified data element.
4476     */
4477    public void deleteNameLookup(long dataId) {
4478        if (mNameLookupDelete == null) {
4479            mNameLookupDelete = getWritableDatabase().compileStatement(
4480                    "DELETE FROM " + Tables.NAME_LOOKUP +
4481                    " WHERE " + NameLookupColumns.DATA_ID + "=?");
4482        }
4483        mNameLookupDelete.bindLong(1, dataId);
4484        mNameLookupDelete.execute();
4485    }
4486
4487    public String insertNameLookupForEmail(long rawContactId, long dataId, String email) {
4488        if (TextUtils.isEmpty(email)) {
4489            return null;
4490        }
4491
4492        String address = extractHandleFromEmailAddress(email);
4493        if (address == null) {
4494            return null;
4495        }
4496
4497        insertNameLookup(rawContactId, dataId,
4498                NameLookupType.EMAIL_BASED_NICKNAME, NameNormalizer.normalize(address));
4499        return address;
4500    }
4501
4502    /**
4503     * Normalizes the nickname and inserts it in the name lookup table.
4504     */
4505    public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) {
4506        if (TextUtils.isEmpty(nickname)) {
4507            return;
4508        }
4509
4510        insertNameLookup(rawContactId, dataId,
4511                NameLookupType.NICKNAME, NameNormalizer.normalize(nickname));
4512    }
4513
4514    public void insertNameLookupForPhoneticName(long rawContactId, long dataId, String familyName,
4515            String middleName, String givenName) {
4516        mSb.setLength(0);
4517        if (familyName != null) {
4518            mSb.append(familyName.trim());
4519        }
4520        if (middleName != null) {
4521            mSb.append(middleName.trim());
4522        }
4523        if (givenName != null) {
4524            mSb.append(givenName.trim());
4525        }
4526
4527        if (mSb.length() > 0) {
4528            insertNameLookup(rawContactId, dataId, NameLookupType.NAME_COLLATION_KEY,
4529                    NameNormalizer.normalize(mSb.toString()));
4530        }
4531    }
4532
4533    /**
4534     * Performs a query and returns true if any Data item of the raw contact with the given
4535     * id and mimetype is marked as super-primary
4536     */
4537    public boolean rawContactHasSuperPrimary(long rawContactId, long mimeTypeId) {
4538        final Cursor existsCursor = getReadableDatabase().rawQuery(
4539                "SELECT EXISTS(SELECT 1 FROM " + Tables.DATA +
4540                " WHERE " + Data.RAW_CONTACT_ID + "=?" +
4541                " AND " + DataColumns.MIMETYPE_ID + "=?" +
4542                " AND " + Data.IS_SUPER_PRIMARY + "<>0)",
4543                new String[] { String.valueOf(rawContactId), String.valueOf(mimeTypeId) });
4544        try {
4545            if (!existsCursor.moveToFirst()) throw new IllegalStateException();
4546            return existsCursor.getInt(0) != 0;
4547        } finally {
4548            existsCursor.close();
4549        }
4550    }
4551
4552    public String getCurrentCountryIso() {
4553        return mCountryMonitor.getCountryIso();
4554    }
4555
4556    /* package */ String querySearchIndexContentForTest(long contactId) {
4557        return DatabaseUtils.stringForQuery(getReadableDatabase(),
4558                "SELECT " + SearchIndexColumns.CONTENT +
4559                " FROM " + Tables.SEARCH_INDEX +
4560                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
4561                new String[] { String.valueOf(contactId) });
4562    }
4563
4564    /* package */ String querySearchIndexTokensForTest(long contactId) {
4565        return DatabaseUtils.stringForQuery(getReadableDatabase(),
4566                "SELECT " + SearchIndexColumns.TOKENS +
4567                " FROM " + Tables.SEARCH_INDEX +
4568                " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)",
4569                new String[] { String.valueOf(contactId) });
4570    }
4571}
4572