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