ContactsDatabaseHelper.java revision 08e50780099971e8927b258ef2ae93d44f98668c
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.internal.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.Cursor;
29import android.database.DatabaseUtils;
30import android.database.SQLException;
31import android.database.sqlite.SQLiteDatabase;
32import android.database.sqlite.SQLiteDoneException;
33import android.database.sqlite.SQLiteException;
34import android.database.sqlite.SQLiteOpenHelper;
35import android.database.sqlite.SQLiteQueryBuilder;
36import android.database.sqlite.SQLiteStatement;
37import android.os.Binder;
38import android.os.Bundle;
39import android.provider.BaseColumns;
40import android.provider.ContactsContract;
41import android.provider.CallLog.Calls;
42import android.provider.ContactsContract.AggregationExceptions;
43import android.provider.ContactsContract.Contacts;
44import android.provider.ContactsContract.Data;
45import android.provider.ContactsContract.DisplayNameSources;
46import android.provider.ContactsContract.FullNameStyle;
47import android.provider.ContactsContract.Groups;
48import android.provider.ContactsContract.RawContacts;
49import android.provider.ContactsContract.Settings;
50import android.provider.ContactsContract.StatusUpdates;
51import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
52import android.provider.ContactsContract.CommonDataKinds.Organization;
53import android.provider.ContactsContract.CommonDataKinds.Phone;
54import android.provider.ContactsContract.CommonDataKinds.StructuredName;
55import android.provider.SocialContract.Activities;
56import android.telephony.PhoneNumberUtils;
57import android.text.TextUtils;
58import android.util.Log;
59
60import java.util.HashMap;
61import java.util.Locale;
62
63/**
64 * Database helper for contacts. Designed as a singleton to make sure that all
65 * {@link android.content.ContentProvider} users get the same reference.
66 * Provides handy methods for maintaining package and mime-type lookup tables.
67 */
68/* package */ class ContactsDatabaseHelper extends SQLiteOpenHelper {
69    private static final String TAG = "ContactsDatabaseHelper";
70
71    private static final int DATABASE_VERSION = 205;
72
73    private static final String DATABASE_NAME = "contacts2.db";
74    private static final String DATABASE_PRESENCE = "presence_db";
75
76    /** size of the compiled-sql statement cache mainatained by {@link SQLiteDatabase} */
77    private static final int MAX_CACHE_SIZE_FOR_CONTACTS_DB = 250;
78
79    public interface Tables {
80        public static final String CONTACTS = "contacts";
81        public static final String RAW_CONTACTS = "raw_contacts";
82        public static final String PACKAGES = "packages";
83        public static final String MIMETYPES = "mimetypes";
84        public static final String PHONE_LOOKUP = "phone_lookup";
85        public static final String NAME_LOOKUP = "name_lookup";
86        public static final String AGGREGATION_EXCEPTIONS = "agg_exceptions";
87        public static final String SETTINGS = "settings";
88        public static final String DATA = "data";
89        public static final String GROUPS = "groups";
90        public static final String PRESENCE = "presence";
91        public static final String AGGREGATED_PRESENCE = "agg_presence";
92        public static final String NICKNAME_LOOKUP = "nickname_lookup";
93        public static final String CALLS = "calls";
94        public static final String CONTACT_ENTITIES = "contact_entities_view";
95        public static final String CONTACT_ENTITIES_RESTRICTED = "contact_entities_view_restricted";
96        public static final String STATUS_UPDATES = "status_updates";
97
98        public static final String DATA_JOIN_MIMETYPES = "data "
99                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id)";
100
101        public static final String DATA_JOIN_RAW_CONTACTS = "data "
102                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
103
104        public static final String DATA_JOIN_MIMETYPE_RAW_CONTACTS = "data "
105                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
106                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
107
108        // NOTE: This requires late binding of GroupMembership MIME-type
109        public static final String RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS = "raw_contacts "
110                + "LEFT OUTER JOIN settings ON ("
111                    + "raw_contacts.account_name = settings.account_name AND "
112                    + "raw_contacts.account_type = settings.account_type) "
113                + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND "
114                    + "data.raw_contact_id = raw_contacts._id) "
115                + "LEFT OUTER JOIN groups ON (groups._id = data." + GroupMembership.GROUP_ROW_ID
116                + ")";
117
118        // NOTE: This requires late binding of GroupMembership MIME-type
119        public static final String SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS = "settings "
120                + "LEFT OUTER JOIN raw_contacts ON ("
121                    + "raw_contacts.account_name = settings.account_name AND "
122                    + "raw_contacts.account_type = settings.account_type) "
123                + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND "
124                    + "data.raw_contact_id = raw_contacts._id) "
125                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
126
127        public static final String DATA_JOIN_MIMETYPES_RAW_CONTACTS_CONTACTS = "data "
128                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
129                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
130                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
131
132        public static final String DATA_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_GROUPS = "data "
133                + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
134                + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
135                + "LEFT OUTER JOIN packages ON (data.package_id = packages._id) "
136                + "LEFT OUTER JOIN groups "
137                + "  ON (mimetypes.mimetype='" + GroupMembership.CONTENT_ITEM_TYPE + "' "
138                + "      AND groups._id = data." + GroupMembership.GROUP_ROW_ID + ") ";
139
140        public static final String GROUPS_JOIN_PACKAGES = "groups "
141                + "LEFT OUTER JOIN packages ON (groups.package_id = packages._id)";
142
143        public static final String ACTIVITIES = "activities";
144
145        public static final String ACTIVITIES_JOIN_MIMETYPES = "activities "
146                + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id)";
147
148        public static final String ACTIVITIES_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_CONTACTS =
149                "activities "
150                + "LEFT OUTER JOIN packages ON (activities.package_id = packages._id) "
151                + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id) "
152                + "LEFT OUTER JOIN raw_contacts ON (activities.author_contact_id = " +
153                        "raw_contacts._id) "
154                + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
155
156        public static final String NAME_LOOKUP_JOIN_RAW_CONTACTS = "name_lookup "
157                + "INNER JOIN raw_contacts ON (name_lookup.raw_contact_id = raw_contacts._id)";
158    }
159
160    public interface Views {
161        public static final String DATA_ALL = "view_data";
162        public static final String DATA_RESTRICTED = "view_data_restricted";
163
164        public static final String RAW_CONTACTS_ALL = "view_raw_contacts";
165        public static final String RAW_CONTACTS_RESTRICTED = "view_raw_contacts_restricted";
166
167        public static final String CONTACTS_ALL = "view_contacts";
168        public static final String CONTACTS_RESTRICTED = "view_contacts_restricted";
169
170        public static final String GROUPS_ALL = "view_groups";
171    }
172
173    public interface Clauses {
174        final String MIMETYPE_IS_GROUP_MEMBERSHIP = MimetypesColumns.CONCRETE_MIMETYPE + "='"
175                + GroupMembership.CONTENT_ITEM_TYPE + "'";
176
177        final String BELONGS_TO_GROUP = DataColumns.CONCRETE_GROUP_ID + "="
178                + GroupsColumns.CONCRETE_ID;
179
180        final String HAVING_NO_GROUPS = "COUNT(" + DataColumns.CONCRETE_GROUP_ID + ") == 0";
181
182        final String GROUP_BY_ACCOUNT_CONTACT_ID = SettingsColumns.CONCRETE_ACCOUNT_NAME + ","
183                + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "," + RawContacts.CONTACT_ID;
184
185        final String RAW_CONTACT_IS_LOCAL = RawContactsColumns.CONCRETE_ACCOUNT_NAME
186                + " IS NULL AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL";
187
188        final String ZERO_GROUP_MEMBERSHIPS = "COUNT(" + GroupsColumns.CONCRETE_ID + ")=0";
189
190        final String OUTER_RAW_CONTACTS = "outer_raw_contacts";
191        final String OUTER_RAW_CONTACTS_ID = OUTER_RAW_CONTACTS + "." + RawContacts._ID;
192
193        final String CONTACT_IS_VISIBLE =
194                "SELECT " +
195                    "MAX((SELECT (CASE WHEN " +
196                        "(CASE" +
197                            " WHEN " + RAW_CONTACT_IS_LOCAL +
198                            " THEN 1 " +
199                            " WHEN " + ZERO_GROUP_MEMBERSHIPS +
200                            " THEN " + Settings.UNGROUPED_VISIBLE +
201                            " ELSE MAX(" + Groups.GROUP_VISIBLE + ")" +
202                         "END)=1 THEN 1 ELSE 0 END)" +
203                " FROM " + Tables.RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS +
204                " WHERE " + RawContactsColumns.CONCRETE_ID + "=" + OUTER_RAW_CONTACTS_ID + "))" +
205                " FROM " + Tables.RAW_CONTACTS + " AS " + OUTER_RAW_CONTACTS +
206                " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
207                " GROUP BY " + RawContacts.CONTACT_ID;
208
209        final String GROUP_HAS_ACCOUNT_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND "
210                + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?";
211    }
212
213    public interface ContactsColumns {
214        /**
215         * This flag is set for a contact if it has only one constituent raw contact and
216         * it is restricted.
217         */
218        public static final String SINGLE_IS_RESTRICTED = "single_is_restricted";
219
220        public static final String LAST_STATUS_UPDATE_ID = "status_update_id";
221
222        public static final String CONCRETE_ID = Tables.CONTACTS + "." + BaseColumns._ID;
223
224        public static final String CONCRETE_TIMES_CONTACTED = Tables.CONTACTS + "."
225                + Contacts.TIMES_CONTACTED;
226        public static final String CONCRETE_LAST_TIME_CONTACTED = Tables.CONTACTS + "."
227                + Contacts.LAST_TIME_CONTACTED;
228        public static final String CONCRETE_STARRED = Tables.CONTACTS + "." + Contacts.STARRED;
229        public static final String CONCRETE_CUSTOM_RINGTONE = Tables.CONTACTS + "."
230                + Contacts.CUSTOM_RINGTONE;
231        public static final String CONCRETE_SEND_TO_VOICEMAIL = Tables.CONTACTS + "."
232                + Contacts.SEND_TO_VOICEMAIL;
233        public static final String CONCRETE_LOOKUP_KEY = Tables.CONTACTS + "."
234                + Contacts.LOOKUP_KEY;
235    }
236
237    public interface RawContactsColumns {
238        public static final String CONCRETE_ID =
239                Tables.RAW_CONTACTS + "." + BaseColumns._ID;
240        public static final String CONCRETE_ACCOUNT_NAME =
241                Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_NAME;
242        public static final String CONCRETE_ACCOUNT_TYPE =
243                Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE;
244        public static final String CONCRETE_SOURCE_ID =
245                Tables.RAW_CONTACTS + "." + RawContacts.SOURCE_ID;
246        public static final String CONCRETE_VERSION =
247                Tables.RAW_CONTACTS + "." + RawContacts.VERSION;
248        public static final String CONCRETE_DIRTY =
249                Tables.RAW_CONTACTS + "." + RawContacts.DIRTY;
250        public static final String CONCRETE_DELETED =
251                Tables.RAW_CONTACTS + "." + RawContacts.DELETED;
252        public static final String CONCRETE_SYNC1 =
253                Tables.RAW_CONTACTS + "." + RawContacts.SYNC1;
254        public static final String CONCRETE_SYNC2 =
255                Tables.RAW_CONTACTS + "." + RawContacts.SYNC2;
256        public static final String CONCRETE_SYNC3 =
257                Tables.RAW_CONTACTS + "." + RawContacts.SYNC3;
258        public static final String CONCRETE_SYNC4 =
259                Tables.RAW_CONTACTS + "." + RawContacts.SYNC4;
260        public static final String CONCRETE_STARRED =
261                Tables.RAW_CONTACTS + "." + RawContacts.STARRED;
262        public static final String CONCRETE_IS_RESTRICTED =
263                Tables.RAW_CONTACTS + "." + RawContacts.IS_RESTRICTED;
264
265        public static final String DISPLAY_NAME = RawContacts.DISPLAY_NAME_PRIMARY;
266        public static final String DISPLAY_NAME_SOURCE = RawContacts.DISPLAY_NAME_SOURCE;
267        public static final String AGGREGATION_NEEDED = "aggregation_needed";
268        public static final String CONTACT_IN_VISIBLE_GROUP = "contact_in_visible_group";
269
270        public static final String CONCRETE_DISPLAY_NAME =
271                Tables.RAW_CONTACTS + "." + DISPLAY_NAME;
272        public static final String CONCRETE_CONTACT_ID =
273                Tables.RAW_CONTACTS + "." + RawContacts.CONTACT_ID;
274    }
275
276    public interface DataColumns {
277        public static final String PACKAGE_ID = "package_id";
278        public static final String MIMETYPE_ID = "mimetype_id";
279
280        public static final String CONCRETE_ID = Tables.DATA + "." + BaseColumns._ID;
281        public static final String CONCRETE_MIMETYPE_ID = Tables.DATA + "." + MIMETYPE_ID;
282        public static final String CONCRETE_RAW_CONTACT_ID = Tables.DATA + "."
283                + Data.RAW_CONTACT_ID;
284        public static final String CONCRETE_GROUP_ID = Tables.DATA + "."
285                + GroupMembership.GROUP_ROW_ID;
286
287        public static final String CONCRETE_DATA1 = Tables.DATA + "." + Data.DATA1;
288        public static final String CONCRETE_DATA2 = Tables.DATA + "." + Data.DATA2;
289        public static final String CONCRETE_DATA3 = Tables.DATA + "." + Data.DATA3;
290        public static final String CONCRETE_DATA4 = Tables.DATA + "." + Data.DATA4;
291        public static final String CONCRETE_DATA5 = Tables.DATA + "." + Data.DATA5;
292        public static final String CONCRETE_DATA6 = Tables.DATA + "." + Data.DATA6;
293        public static final String CONCRETE_DATA7 = Tables.DATA + "." + Data.DATA7;
294        public static final String CONCRETE_DATA8 = Tables.DATA + "." + Data.DATA8;
295        public static final String CONCRETE_DATA9 = Tables.DATA + "." + Data.DATA9;
296        public static final String CONCRETE_DATA10 = Tables.DATA + "." + Data.DATA10;
297        public static final String CONCRETE_DATA11 = Tables.DATA + "." + Data.DATA11;
298        public static final String CONCRETE_DATA12 = Tables.DATA + "." + Data.DATA12;
299        public static final String CONCRETE_DATA13 = Tables.DATA + "." + Data.DATA13;
300        public static final String CONCRETE_DATA14 = Tables.DATA + "." + Data.DATA14;
301        public static final String CONCRETE_DATA15 = Tables.DATA + "." + Data.DATA15;
302        public static final String CONCRETE_IS_PRIMARY = Tables.DATA + "." + Data.IS_PRIMARY;
303        public static final String CONCRETE_PACKAGE_ID = Tables.DATA + "." + PACKAGE_ID;
304    }
305
306    // Used only for legacy API support
307    public interface ExtensionsColumns {
308        public static final String NAME = Data.DATA1;
309        public static final String VALUE = Data.DATA2;
310    }
311
312    public interface GroupMembershipColumns {
313        public static final String RAW_CONTACT_ID = Data.RAW_CONTACT_ID;
314        public static final String GROUP_ROW_ID = GroupMembership.GROUP_ROW_ID;
315    }
316
317    public interface PhoneColumns {
318        public static final String NORMALIZED_NUMBER = Data.DATA4;
319        public static final String CONCRETE_NORMALIZED_NUMBER = DataColumns.CONCRETE_DATA4;
320    }
321
322    public interface GroupsColumns {
323        public static final String PACKAGE_ID = "package_id";
324
325        public static final String CONCRETE_ID = Tables.GROUPS + "." + BaseColumns._ID;
326        public static final String CONCRETE_SOURCE_ID = Tables.GROUPS + "." + Groups.SOURCE_ID;
327        public static final String CONCRETE_ACCOUNT_NAME = Tables.GROUPS + "." + Groups.ACCOUNT_NAME;
328        public static final String CONCRETE_ACCOUNT_TYPE = Tables.GROUPS + "." + Groups.ACCOUNT_TYPE;
329    }
330
331    public interface ActivitiesColumns {
332        public static final String PACKAGE_ID = "package_id";
333        public static final String MIMETYPE_ID = "mimetype_id";
334    }
335
336    public interface PhoneLookupColumns {
337        public static final String _ID = BaseColumns._ID;
338        public static final String DATA_ID = "data_id";
339        public static final String RAW_CONTACT_ID = "raw_contact_id";
340        public static final String NORMALIZED_NUMBER = "normalized_number";
341        public static final String MIN_MATCH = "min_match";
342    }
343
344    public interface NameLookupColumns {
345        public static final String RAW_CONTACT_ID = "raw_contact_id";
346        public static final String DATA_ID = "data_id";
347        public static final String NORMALIZED_NAME = "normalized_name";
348        public static final String NAME_TYPE = "name_type";
349    }
350
351    public final static class NameLookupType {
352        public static final int NAME_EXACT = 0;
353        public static final int NAME_VARIANT = 1;
354        public static final int NAME_COLLATION_KEY = 2;
355        public static final int NICKNAME = 3;
356        public static final int EMAIL_BASED_NICKNAME = 4;
357        public static final int ORGANIZATION = 5;
358
359        // This is the highest name lookup type code plus one
360        public static final int TYPE_COUNT = 6;
361
362        public static boolean isBasedOnStructuredName(int nameLookupType) {
363            return nameLookupType == NameLookupType.NAME_EXACT
364                    || nameLookupType == NameLookupType.NAME_VARIANT
365                    || nameLookupType == NameLookupType.NAME_COLLATION_KEY;
366        }
367    }
368
369    public interface PackagesColumns {
370        public static final String _ID = BaseColumns._ID;
371        public static final String PACKAGE = "package";
372
373        public static final String CONCRETE_ID = Tables.PACKAGES + "." + _ID;
374    }
375
376    public interface MimetypesColumns {
377        public static final String _ID = BaseColumns._ID;
378        public static final String MIMETYPE = "mimetype";
379
380        public static final String CONCRETE_ID = Tables.MIMETYPES + "." + BaseColumns._ID;
381        public static final String CONCRETE_MIMETYPE = Tables.MIMETYPES + "." + MIMETYPE;
382    }
383
384    public interface AggregationExceptionColumns {
385        public static final String _ID = BaseColumns._ID;
386    }
387
388    public interface NicknameLookupColumns {
389        public static final String NAME = "name";
390        public static final String CLUSTER = "cluster";
391    }
392
393    public interface SettingsColumns {
394        public static final String CONCRETE_ACCOUNT_NAME = Tables.SETTINGS + "."
395                + Settings.ACCOUNT_NAME;
396        public static final String CONCRETE_ACCOUNT_TYPE = Tables.SETTINGS + "."
397                + Settings.ACCOUNT_TYPE;
398    }
399
400    public interface PresenceColumns {
401        String RAW_CONTACT_ID = "presence_raw_contact_id";
402        String CONTACT_ID = "presence_contact_id";
403    }
404
405    public interface AggregatedPresenceColumns {
406        String CONTACT_ID = "presence_contact_id";
407
408        String CONCRETE_CONTACT_ID = Tables.AGGREGATED_PRESENCE + "." + CONTACT_ID;
409    }
410
411    public interface StatusUpdatesColumns {
412        String DATA_ID = "status_update_data_id";
413
414        String CONCRETE_DATA_ID = Tables.STATUS_UPDATES + "." + DATA_ID;
415
416        String CONCRETE_PRESENCE = Tables.STATUS_UPDATES + "." + StatusUpdates.PRESENCE;
417        String CONCRETE_STATUS = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS;
418        String CONCRETE_STATUS_TIMESTAMP = Tables.STATUS_UPDATES + "."
419                + StatusUpdates.STATUS_TIMESTAMP;
420        String CONCRETE_STATUS_RES_PACKAGE = Tables.STATUS_UPDATES + "."
421                + StatusUpdates.STATUS_RES_PACKAGE;
422        String CONCRETE_STATUS_LABEL = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_LABEL;
423        String CONCRETE_STATUS_ICON = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_ICON;
424    }
425
426    public interface ContactsStatusUpdatesColumns {
427        String ALIAS = "contacts_" + Tables.STATUS_UPDATES;
428
429        String CONCRETE_DATA_ID = ALIAS + "." + StatusUpdatesColumns.DATA_ID;
430
431        String CONCRETE_PRESENCE = ALIAS + "." + StatusUpdates.PRESENCE;
432        String CONCRETE_STATUS = ALIAS + "." + StatusUpdates.STATUS;
433        String CONCRETE_STATUS_TIMESTAMP = ALIAS + "." + StatusUpdates.STATUS_TIMESTAMP;
434        String CONCRETE_STATUS_RES_PACKAGE = ALIAS + "." + StatusUpdates.STATUS_RES_PACKAGE;
435        String CONCRETE_STATUS_LABEL = ALIAS + "." + StatusUpdates.STATUS_LABEL;
436        String CONCRETE_STATUS_ICON = ALIAS + "." + StatusUpdates.STATUS_ICON;
437    }
438
439    /** In-memory cache of previously found MIME-type mappings */
440    private final HashMap<String, Long> mMimetypeCache = new HashMap<String, Long>();
441    /** In-memory cache of previously found package name mappings */
442    private final HashMap<String, Long> mPackageCache = new HashMap<String, Long>();
443
444
445    /** Compiled statements for querying and inserting mappings */
446    private SQLiteStatement mMimetypeQuery;
447    private SQLiteStatement mPackageQuery;
448    private SQLiteStatement mContactIdQuery;
449    private SQLiteStatement mAggregationModeQuery;
450    private SQLiteStatement mMimetypeInsert;
451    private SQLiteStatement mPackageInsert;
452    private SQLiteStatement mDataMimetypeQuery;
453    private SQLiteStatement mActivitiesMimetypeQuery;
454
455    private final Context mContext;
456    private final SyncStateContentProviderHelper mSyncState;
457
458
459    /** Compiled statements for updating {@link Contacts#IN_VISIBLE_GROUP}. */
460    private SQLiteStatement mVisibleUpdate;
461    private SQLiteStatement mVisibleSpecificUpdate;
462    private SQLiteStatement mVisibleUpdateRawContacts;
463    private SQLiteStatement mVisibleSpecificUpdateRawContacts;
464
465    private boolean mReopenDatabase = false;
466
467    private static ContactsDatabaseHelper sSingleton = null;
468
469    private boolean mUseStrictPhoneNumberComparison;
470
471    /**
472     * List of package names with access to {@link RawContacts#IS_RESTRICTED} data.
473     */
474    private String[] mUnrestrictedPackages;
475
476    public static synchronized ContactsDatabaseHelper getInstance(Context context) {
477        if (sSingleton == null) {
478            sSingleton = new ContactsDatabaseHelper(context);
479        }
480        return sSingleton;
481    }
482
483    /**
484     * Private constructor, callers except unit tests should obtain an instance through
485     * {@link #getInstance(android.content.Context)} instead.
486     */
487    ContactsDatabaseHelper(Context context) {
488        super(context, DATABASE_NAME, null, DATABASE_VERSION);
489        if (false) Log.i(TAG, "Creating OpenHelper");
490        Resources resources = context.getResources();
491
492        mContext = context;
493        mSyncState = new SyncStateContentProviderHelper();
494        mUseStrictPhoneNumberComparison =
495                resources.getBoolean(
496                        com.android.internal.R.bool.config_use_strict_phone_number_comparation);
497        int resourceId = resources.getIdentifier("unrestricted_packages", "array",
498                context.getPackageName());
499        if (resourceId != 0) {
500            mUnrestrictedPackages = resources.getStringArray(resourceId);
501        } else {
502            mUnrestrictedPackages = new String[0];
503        }
504    }
505
506    @Override
507    public void onOpen(SQLiteDatabase db) {
508        mSyncState.onDatabaseOpened(db);
509
510        // Create compiled statements for package and mimetype lookups
511        mMimetypeQuery = db.compileStatement("SELECT " + MimetypesColumns._ID + " FROM "
512                + Tables.MIMETYPES + " WHERE " + MimetypesColumns.MIMETYPE + "=?");
513        mPackageQuery = db.compileStatement("SELECT " + PackagesColumns._ID + " FROM "
514                + Tables.PACKAGES + " WHERE " + PackagesColumns.PACKAGE + "=?");
515        mContactIdQuery = db.compileStatement("SELECT " + RawContacts.CONTACT_ID + " FROM "
516                + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=?");
517        mAggregationModeQuery = db.compileStatement("SELECT " + RawContacts.AGGREGATION_MODE
518                + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=?");
519        mMimetypeInsert = db.compileStatement("INSERT INTO " + Tables.MIMETYPES + "("
520                + MimetypesColumns.MIMETYPE + ") VALUES (?)");
521        mPackageInsert = db.compileStatement("INSERT INTO " + Tables.PACKAGES + "("
522                + PackagesColumns.PACKAGE + ") VALUES (?)");
523
524        mDataMimetypeQuery = db.compileStatement("SELECT " + MimetypesColumns.MIMETYPE + " FROM "
525                + Tables.DATA_JOIN_MIMETYPES + " WHERE " + Tables.DATA + "." + Data._ID + "=?");
526        mActivitiesMimetypeQuery = db.compileStatement("SELECT " + MimetypesColumns.MIMETYPE
527                + " FROM " + Tables.ACTIVITIES_JOIN_MIMETYPES + " WHERE " + Tables.ACTIVITIES + "."
528                + Activities._ID + "=?");
529
530        // Compile statements for updating visibility
531        final String visibleUpdate = "UPDATE " + Tables.CONTACTS + " SET "
532                + Contacts.IN_VISIBLE_GROUP + "=(" + Clauses.CONTACT_IS_VISIBLE + ")";
533
534        mVisibleUpdate = db.compileStatement(visibleUpdate);
535        mVisibleSpecificUpdate = db.compileStatement(visibleUpdate + " WHERE "
536                + ContactsColumns.CONCRETE_ID + "=?");
537
538        String visibleUpdateRawContacts =
539                "UPDATE " + Tables.RAW_CONTACTS +
540                " SET " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "=(" +
541                        "SELECT " + Contacts.IN_VISIBLE_GROUP +
542                        " FROM " + Tables.CONTACTS +
543                        " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" +
544                " WHERE " + RawContacts.DELETED + "=0";
545
546        mVisibleUpdateRawContacts = db.compileStatement(visibleUpdateRawContacts);
547        mVisibleSpecificUpdateRawContacts = db.compileStatement(visibleUpdateRawContacts +
548                    " AND " + RawContacts.CONTACT_ID + "=?");
549
550        db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";");
551        db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_PRESENCE + "." + Tables.PRESENCE + " ("+
552                StatusUpdates.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
553                StatusUpdates.PROTOCOL + " INTEGER NOT NULL," +
554                StatusUpdates.CUSTOM_PROTOCOL + " TEXT," +
555                StatusUpdates.IM_HANDLE + " TEXT," +
556                StatusUpdates.IM_ACCOUNT + " TEXT," +
557                PresenceColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
558                PresenceColumns.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
559                StatusUpdates.PRESENCE + " INTEGER," +
560                "UNIQUE(" + StatusUpdates.PROTOCOL + ", " + StatusUpdates.CUSTOM_PROTOCOL
561                    + ", " + StatusUpdates.IM_HANDLE + ", " + StatusUpdates.IM_ACCOUNT + ")" +
562        ");");
563
564        db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex" + " ON "
565                + Tables.PRESENCE + " (" + PresenceColumns.RAW_CONTACT_ID + ");");
566
567        db.execSQL("CREATE TABLE IF NOT EXISTS "
568                        + DATABASE_PRESENCE + "." + Tables.AGGREGATED_PRESENCE + " ("+
569                AggregatedPresenceColumns.CONTACT_ID
570                        + " INTEGER PRIMARY KEY REFERENCES contacts(_id)," +
571                StatusUpdates.PRESENCE_STATUS + " INTEGER" +
572        ");");
573
574
575        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_deleted"
576                + " BEFORE DELETE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
577                + " BEGIN "
578                + "   DELETE FROM " + Tables.AGGREGATED_PRESENCE
579                + "     WHERE " + AggregatedPresenceColumns.CONTACT_ID + " = " +
580                        "(SELECT " + PresenceColumns.CONTACT_ID +
581                        " FROM " + Tables.PRESENCE +
582                        " WHERE " + PresenceColumns.RAW_CONTACT_ID
583                                + "=OLD." + PresenceColumns.RAW_CONTACT_ID +
584                        " AND NOT EXISTS" +
585                                "(SELECT " + PresenceColumns.RAW_CONTACT_ID +
586                                " FROM " + Tables.PRESENCE +
587                                " WHERE " + PresenceColumns.CONTACT_ID
588                                        + "=OLD." + PresenceColumns.CONTACT_ID +
589                                " AND " + PresenceColumns.RAW_CONTACT_ID
590                                        + "!=OLD." + PresenceColumns.RAW_CONTACT_ID + "));"
591                + " END");
592
593        String replaceAggregatePresenceSql =
594            "INSERT OR REPLACE INTO " + Tables.AGGREGATED_PRESENCE + "("
595                    + AggregatedPresenceColumns.CONTACT_ID + ", "
596                    + StatusUpdates.PRESENCE_STATUS + ")" +
597            " SELECT " + PresenceColumns.CONTACT_ID + ","
598                        + "MAX(" + StatusUpdates.PRESENCE_STATUS + ")" +
599                    " FROM " + Tables.PRESENCE +
600                    " WHERE " + PresenceColumns.CONTACT_ID
601                        + "=NEW." + PresenceColumns.CONTACT_ID + ";";
602
603        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_inserted"
604                + " AFTER INSERT ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
605                + " BEGIN "
606                + replaceAggregatePresenceSql
607                + " END");
608
609        db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_updated"
610                + " AFTER UPDATE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
611                + " BEGIN "
612                + replaceAggregatePresenceSql
613                + " END");
614    }
615
616    @Override
617    public void onCreate(SQLiteDatabase db) {
618        Log.i(TAG, "Bootstrapping database");
619
620        mSyncState.createDatabase(db);
621
622        // One row per group of contacts corresponding to the same person
623        db.execSQL("CREATE TABLE " + Tables.CONTACTS + " (" +
624                BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
625                Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
626                Contacts.PHOTO_ID + " INTEGER REFERENCES data(_id)," +
627                Contacts.CUSTOM_RINGTONE + " TEXT," +
628                Contacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
629                Contacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
630                Contacts.LAST_TIME_CONTACTED + " INTEGER," +
631                Contacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
632                Contacts.IN_VISIBLE_GROUP + " INTEGER NOT NULL DEFAULT 1," +
633                Contacts.HAS_PHONE_NUMBER + " INTEGER NOT NULL DEFAULT 0," +
634                Contacts.LOOKUP_KEY + " TEXT," +
635                ContactsColumns.LAST_STATUS_UPDATE_ID + " INTEGER REFERENCES data(_id)," +
636                ContactsColumns.SINGLE_IS_RESTRICTED + " INTEGER NOT NULL DEFAULT 0" +
637        ");");
638
639        db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
640                Contacts.IN_VISIBLE_GROUP +
641        ");");
642
643        db.execSQL("CREATE INDEX contacts_has_phone_index ON " + Tables.CONTACTS + " (" +
644                Contacts.HAS_PHONE_NUMBER +
645        ");");
646
647        db.execSQL("CREATE INDEX contacts_restricted_index ON " + Tables.CONTACTS + " (" +
648                ContactsColumns.SINGLE_IS_RESTRICTED +
649        ");");
650
651        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
652                Contacts.NAME_RAW_CONTACT_ID +
653        ");");
654
655        // Contacts table
656        db.execSQL("CREATE TABLE " + Tables.RAW_CONTACTS + " (" +
657                RawContacts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
658                RawContacts.IS_RESTRICTED + " INTEGER DEFAULT 0," +
659                RawContacts.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
660                RawContacts.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
661                RawContacts.SOURCE_ID + " TEXT," +
662                RawContacts.VERSION + " INTEGER NOT NULL DEFAULT 1," +
663                RawContacts.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
664                RawContacts.DELETED + " INTEGER NOT NULL DEFAULT 0," +
665                RawContacts.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
666                RawContacts.AGGREGATION_MODE + " INTEGER NOT NULL DEFAULT " +
667                        RawContacts.AGGREGATION_MODE_DEFAULT + "," +
668                RawContactsColumns.AGGREGATION_NEEDED + " INTEGER NOT NULL DEFAULT 1," +
669                RawContacts.CUSTOM_RINGTONE + " TEXT," +
670                RawContacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
671                RawContacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
672                RawContacts.LAST_TIME_CONTACTED + " INTEGER," +
673                RawContacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
674                RawContacts.DISPLAY_NAME_PRIMARY + " TEXT," +
675                RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT," +
676                RawContacts.DISPLAY_NAME_SOURCE + " INTEGER NOT NULL DEFAULT " +
677                        DisplayNameSources.UNDEFINED + "," +
678                RawContacts.PHONETIC_NAME + " TEXT," +
679                RawContacts.PHONETIC_NAME_STYLE + " TEXT," +
680                RawContacts.SORT_KEY_PRIMARY + " TEXT COLLATE LOCALIZED," +
681                RawContacts.SORT_KEY_ALTERNATIVE + " TEXT COLLATE LOCALIZED," +
682                RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + " INTEGER NOT NULL DEFAULT 0," +
683                RawContacts.SYNC1 + " TEXT, " +
684                RawContacts.SYNC2 + " TEXT, " +
685                RawContacts.SYNC3 + " TEXT, " +
686                RawContacts.SYNC4 + " TEXT " +
687        ");");
688
689        db.execSQL("CREATE INDEX raw_contacts_contact_id_index ON " + Tables.RAW_CONTACTS + " (" +
690                RawContacts.CONTACT_ID +
691        ");");
692
693        db.execSQL("CREATE INDEX raw_contacts_source_id_index ON " + Tables.RAW_CONTACTS + " (" +
694                RawContacts.SOURCE_ID + ", " +
695                RawContacts.ACCOUNT_TYPE + ", " +
696                RawContacts.ACCOUNT_NAME +
697        ");");
698
699        // TODO readd the index and investigate a controlled use of it
700//        db.execSQL("CREATE INDEX raw_contacts_agg_index ON " + Tables.RAW_CONTACTS + " (" +
701//                RawContactsColumns.AGGREGATION_NEEDED +
702//        ");");
703
704        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
705                RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
706                RawContacts.SORT_KEY_PRIMARY +
707        ");");
708
709        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
710                RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
711                RawContacts.SORT_KEY_ALTERNATIVE +
712        ");");
713
714        // Package name mapping table
715        db.execSQL("CREATE TABLE " + Tables.PACKAGES + " (" +
716                PackagesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
717                PackagesColumns.PACKAGE + " TEXT NOT NULL" +
718        ");");
719
720        // Mimetype mapping table
721        db.execSQL("CREATE TABLE " + Tables.MIMETYPES + " (" +
722                MimetypesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
723                MimetypesColumns.MIMETYPE + " TEXT NOT NULL" +
724        ");");
725
726        // Public generic data table
727        db.execSQL("CREATE TABLE " + Tables.DATA + " (" +
728                Data._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
729                DataColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
730                DataColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
731                Data.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
732                Data.IS_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
733                Data.IS_SUPER_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
734                Data.DATA_VERSION + " INTEGER NOT NULL DEFAULT 0," +
735                Data.DATA1 + " TEXT," +
736                Data.DATA2 + " TEXT," +
737                Data.DATA3 + " TEXT," +
738                Data.DATA4 + " TEXT," +
739                Data.DATA5 + " TEXT," +
740                Data.DATA6 + " TEXT," +
741                Data.DATA7 + " TEXT," +
742                Data.DATA8 + " TEXT," +
743                Data.DATA9 + " TEXT," +
744                Data.DATA10 + " TEXT," +
745                Data.DATA11 + " TEXT," +
746                Data.DATA12 + " TEXT," +
747                Data.DATA13 + " TEXT," +
748                Data.DATA14 + " TEXT," +
749                Data.DATA15 + " TEXT," +
750                Data.SYNC1 + " TEXT, " +
751                Data.SYNC2 + " TEXT, " +
752                Data.SYNC3 + " TEXT, " +
753                Data.SYNC4 + " TEXT " +
754        ");");
755
756        db.execSQL("CREATE INDEX data_raw_contact_id ON " + Tables.DATA + " (" +
757                Data.RAW_CONTACT_ID +
758        ");");
759
760        /**
761         * For email lookup and similar queries.
762         */
763        db.execSQL("CREATE INDEX data_mimetype_data1_index ON " + Tables.DATA + " (" +
764                DataColumns.MIMETYPE_ID + "," +
765                Data.DATA1 +
766        ");");
767
768        // Private phone numbers table used for lookup
769        db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
770                PhoneLookupColumns.DATA_ID
771                        + " INTEGER PRIMARY KEY REFERENCES data(_id) NOT NULL," +
772                PhoneLookupColumns.RAW_CONTACT_ID
773                        + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
774                PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
775                PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
776        ");");
777
778        db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
779                PhoneLookupColumns.NORMALIZED_NUMBER + "," +
780                PhoneLookupColumns.RAW_CONTACT_ID + "," +
781                PhoneLookupColumns.DATA_ID +
782        ");");
783
784        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
785                PhoneLookupColumns.MIN_MATCH + "," +
786                PhoneLookupColumns.RAW_CONTACT_ID + "," +
787                PhoneLookupColumns.DATA_ID +
788        ");");
789
790        // Private name/nickname table used for lookup
791        db.execSQL("CREATE TABLE " + Tables.NAME_LOOKUP + " (" +
792                NameLookupColumns.DATA_ID
793                        + " INTEGER REFERENCES data(_id) NOT NULL," +
794                NameLookupColumns.RAW_CONTACT_ID
795                        + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
796                NameLookupColumns.NORMALIZED_NAME + " TEXT NOT NULL," +
797                NameLookupColumns.NAME_TYPE + " INTEGER NOT NULL," +
798                "PRIMARY KEY ("
799                        + NameLookupColumns.DATA_ID + ", "
800                        + NameLookupColumns.NORMALIZED_NAME + ", "
801                        + NameLookupColumns.NAME_TYPE + ")" +
802        ");");
803
804        db.execSQL("CREATE INDEX name_lookup_index ON " + Tables.NAME_LOOKUP + " (" +
805                NameLookupColumns.NORMALIZED_NAME + "," +
806                NameLookupColumns.NAME_TYPE + ", " +
807                NameLookupColumns.RAW_CONTACT_ID +
808        ");");
809
810        db.execSQL("CREATE INDEX name_lookup_raw_contact_id_index ON " + Tables.NAME_LOOKUP + " (" +
811                NameLookupColumns.RAW_CONTACT_ID +
812        ");");
813
814        db.execSQL("CREATE TABLE " + Tables.NICKNAME_LOOKUP + " (" +
815                NicknameLookupColumns.NAME + " TEXT," +
816                NicknameLookupColumns.CLUSTER + " TEXT" +
817        ");");
818
819        db.execSQL("CREATE UNIQUE INDEX nickname_lookup_index ON " + Tables.NICKNAME_LOOKUP + " (" +
820                NicknameLookupColumns.NAME + ", " +
821                NicknameLookupColumns.CLUSTER +
822        ");");
823
824        // Groups table
825        db.execSQL("CREATE TABLE " + Tables.GROUPS + " (" +
826                Groups._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
827                GroupsColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
828                Groups.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
829                Groups.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
830                Groups.SOURCE_ID + " TEXT," +
831                Groups.VERSION + " INTEGER NOT NULL DEFAULT 1," +
832                Groups.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
833                Groups.TITLE + " TEXT," +
834                Groups.TITLE_RES + " INTEGER," +
835                Groups.NOTES + " TEXT," +
836                Groups.SYSTEM_ID + " TEXT," +
837                Groups.DELETED + " INTEGER NOT NULL DEFAULT 0," +
838                Groups.GROUP_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
839                Groups.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1," +
840                Groups.SYNC1 + " TEXT, " +
841                Groups.SYNC2 + " TEXT, " +
842                Groups.SYNC3 + " TEXT, " +
843                Groups.SYNC4 + " TEXT " +
844        ");");
845
846        db.execSQL("CREATE INDEX groups_source_id_index ON " + Tables.GROUPS + " (" +
847                Groups.SOURCE_ID + ", " +
848                Groups.ACCOUNT_TYPE + ", " +
849                Groups.ACCOUNT_NAME +
850        ");");
851
852        db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.AGGREGATION_EXCEPTIONS + " (" +
853                AggregationExceptionColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
854                AggregationExceptions.TYPE + " INTEGER NOT NULL, " +
855                AggregationExceptions.RAW_CONTACT_ID1
856                        + " INTEGER REFERENCES raw_contacts(_id), " +
857                AggregationExceptions.RAW_CONTACT_ID2
858                        + " INTEGER REFERENCES raw_contacts(_id)" +
859        ");");
860
861        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index1 ON " +
862                Tables.AGGREGATION_EXCEPTIONS + " (" +
863                AggregationExceptions.RAW_CONTACT_ID1 + ", " +
864                AggregationExceptions.RAW_CONTACT_ID2 +
865        ");");
866
867        db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index2 ON " +
868                Tables.AGGREGATION_EXCEPTIONS + " (" +
869                AggregationExceptions.RAW_CONTACT_ID2 + ", " +
870                AggregationExceptions.RAW_CONTACT_ID1 +
871        ");");
872
873        db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.SETTINGS + " (" +
874                Settings.ACCOUNT_NAME + " STRING NOT NULL," +
875                Settings.ACCOUNT_TYPE + " STRING NOT NULL," +
876                Settings.UNGROUPED_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
877                Settings.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1, " +
878                "PRIMARY KEY (" + Settings.ACCOUNT_NAME + ", " +
879                    Settings.ACCOUNT_TYPE + ") ON CONFLICT REPLACE" +
880        ");");
881
882        // The table for recent calls is here so we can do table joins
883        // on people, phones, and calls all in one place.
884        db.execSQL("CREATE TABLE " + Tables.CALLS + " (" +
885                Calls._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
886                Calls.NUMBER + " TEXT," +
887                Calls.DATE + " INTEGER," +
888                Calls.DURATION + " INTEGER," +
889                Calls.TYPE + " INTEGER," +
890                Calls.NEW + " INTEGER," +
891                Calls.CACHED_NAME + " TEXT," +
892                Calls.CACHED_NUMBER_TYPE + " INTEGER," +
893                Calls.CACHED_NUMBER_LABEL + " TEXT" +
894        ");");
895
896        // Activities table
897        db.execSQL("CREATE TABLE " + Tables.ACTIVITIES + " (" +
898                Activities._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
899                ActivitiesColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
900                ActivitiesColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
901                Activities.RAW_ID + " TEXT," +
902                Activities.IN_REPLY_TO + " TEXT," +
903                Activities.AUTHOR_CONTACT_ID +  " INTEGER REFERENCES raw_contacts(_id)," +
904                Activities.TARGET_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
905                Activities.PUBLISHED + " INTEGER NOT NULL," +
906                Activities.THREAD_PUBLISHED + " INTEGER NOT NULL," +
907                Activities.TITLE + " TEXT NOT NULL," +
908                Activities.SUMMARY + " TEXT," +
909                Activities.LINK + " TEXT, " +
910                Activities.THUMBNAIL + " BLOB" +
911        ");");
912
913        db.execSQL("CREATE TABLE " + Tables.STATUS_UPDATES + " (" +
914                StatusUpdatesColumns.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
915                StatusUpdates.STATUS + " TEXT," +
916                StatusUpdates.STATUS_TIMESTAMP + " INTEGER," +
917                StatusUpdates.STATUS_RES_PACKAGE + " TEXT, " +
918                StatusUpdates.STATUS_LABEL + " INTEGER, " +
919                StatusUpdates.STATUS_ICON + " INTEGER" +
920        ");");
921
922        createContactsViews(db);
923        createGroupsView(db);
924        createContactEntitiesView(db);
925        createContactsTriggers(db);
926
927        loadNicknameLookupTable(db);
928
929        // Add the legacy API support views, etc
930        LegacyApiSupport.createDatabase(db);
931
932        // This will create a sqlite_stat1 table that is used for query optimization
933        db.execSQL("ANALYZE;");
934
935        updateSqliteStats(db);
936
937        // We need to close and reopen the database connection so that the stats are
938        // taken into account. Make a note of it and do the actual reopening in the
939        // getWritableDatabase method.
940        mReopenDatabase = true;
941
942        ContentResolver.requestSync(null /* all accounts */,
943                ContactsContract.AUTHORITY, new Bundle());
944    }
945
946    private void createContactsTriggers(SQLiteDatabase db) {
947
948        /*
949         * Automatically delete Data rows when a raw contact is deleted.
950         */
951        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;");
952        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted "
953                + "   BEFORE DELETE ON " + Tables.RAW_CONTACTS
954                + " BEGIN "
955                + "   DELETE FROM " + Tables.DATA
956                + "     WHERE " + Data.RAW_CONTACT_ID
957                                + "=OLD." + RawContacts._ID + ";"
958                + "   DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS
959                + "     WHERE " + AggregationExceptions.RAW_CONTACT_ID1
960                                + "=OLD." + RawContacts._ID
961                + "        OR " + AggregationExceptions.RAW_CONTACT_ID2
962                                + "=OLD." + RawContacts._ID + ";"
963                + "   DELETE FROM " + Tables.CONTACTS
964                + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
965                + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
966                + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
967                + "           )=1;"
968                + " END");
969
970
971        db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;");
972
973        /*
974         * Triggers that update {@link RawContacts#VERSION} when the contact is
975         * marked for deletion or any time a data row is inserted, updated or
976         * deleted.
977         */
978        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;");
979        db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted "
980                + "   AFTER UPDATE ON " + Tables.RAW_CONTACTS
981                + " BEGIN "
982                + "   UPDATE " + Tables.RAW_CONTACTS
983                + "     SET "
984                +         RawContacts.VERSION + "=OLD." + RawContacts.VERSION + "+1 "
985                + "     WHERE " + RawContacts._ID + "=OLD." + RawContacts._ID
986                + "       AND NEW." + RawContacts.DELETED + "!= OLD." + RawContacts.DELETED + ";"
987                + " END");
988
989        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_updated;");
990        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_updated AFTER UPDATE ON " + Tables.DATA
991                + " BEGIN "
992                + "   UPDATE " + Tables.DATA
993                + "     SET " + Data.DATA_VERSION + "=OLD." + Data.DATA_VERSION + "+1 "
994                + "     WHERE " + Data._ID + "=OLD." + Data._ID + ";"
995                + "   UPDATE " + Tables.RAW_CONTACTS
996                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
997                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
998                + " END");
999
1000        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_deleted;");
1001        db.execSQL("CREATE TRIGGER " + Tables.DATA + "_deleted BEFORE DELETE ON " + Tables.DATA
1002                + " BEGIN "
1003                + "   UPDATE " + Tables.RAW_CONTACTS
1004                + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
1005                + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
1006                + "   DELETE FROM " + Tables.PHONE_LOOKUP
1007                + "     WHERE " + PhoneLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1008                + "   DELETE FROM " + Tables.STATUS_UPDATES
1009                + "     WHERE " + StatusUpdatesColumns.DATA_ID + "=OLD." + Data._ID + ";"
1010                + "   DELETE FROM " + Tables.NAME_LOOKUP
1011                + "     WHERE " + NameLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
1012                + " END");
1013
1014
1015        db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_updated1;");
1016        db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_updated1 "
1017                + "   AFTER UPDATE ON " + Tables.GROUPS
1018                + " BEGIN "
1019                + "   UPDATE " + Tables.GROUPS
1020                + "     SET "
1021                +         Groups.VERSION + "=OLD." + Groups.VERSION + "+1"
1022                + "     WHERE " + Groups._ID + "=OLD." + Groups._ID + ";"
1023                + " END");
1024    }
1025
1026    private static void createContactsViews(SQLiteDatabase db) {
1027        db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS_ALL + ";");
1028        db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS_RESTRICTED + ";");
1029        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_ALL + ";");
1030        db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_RESTRICTED + ";");
1031        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS_ALL + ";");
1032        db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS_RESTRICTED + ";");
1033
1034        String dataColumns =
1035                Data.IS_PRIMARY + ", "
1036                + Data.IS_SUPER_PRIMARY + ", "
1037                + Data.DATA_VERSION + ", "
1038                + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + ","
1039                + MimetypesColumns.MIMETYPE + " AS " + Data.MIMETYPE + ", "
1040                + Data.DATA1 + ", "
1041                + Data.DATA2 + ", "
1042                + Data.DATA3 + ", "
1043                + Data.DATA4 + ", "
1044                + Data.DATA5 + ", "
1045                + Data.DATA6 + ", "
1046                + Data.DATA7 + ", "
1047                + Data.DATA8 + ", "
1048                + Data.DATA9 + ", "
1049                + Data.DATA10 + ", "
1050                + Data.DATA11 + ", "
1051                + Data.DATA12 + ", "
1052                + Data.DATA13 + ", "
1053                + Data.DATA14 + ", "
1054                + Data.DATA15 + ", "
1055                + Data.SYNC1 + ", "
1056                + Data.SYNC2 + ", "
1057                + Data.SYNC3 + ", "
1058                + Data.SYNC4;
1059
1060        String syncColumns =
1061                RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ","
1062                + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ","
1063                + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + ","
1064                + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + ","
1065                + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + ","
1066                + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + ","
1067                + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + ","
1068                + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + ","
1069                + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4;
1070
1071        String contactOptionColumns =
1072                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1073                        + " AS " + RawContacts.CUSTOM_RINGTONE + ","
1074                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1075                        + " AS " + RawContacts.SEND_TO_VOICEMAIL + ","
1076                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1077                        + " AS " + RawContacts.LAST_TIME_CONTACTED + ","
1078                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1079                        + " AS " + RawContacts.TIMES_CONTACTED + ","
1080                + ContactsColumns.CONCRETE_STARRED
1081                        + " AS " + RawContacts.STARRED;
1082
1083        String contactNameColumns =
1084                "name_raw_contact." + RawContacts.DISPLAY_NAME_SOURCE
1085                        + " AS " + Contacts.DISPLAY_NAME_SOURCE + ", "
1086                + "name_raw_contact." + RawContacts.DISPLAY_NAME_PRIMARY
1087                        + " AS " + Contacts.DISPLAY_NAME_PRIMARY + ", "
1088                + "name_raw_contact." + RawContacts.DISPLAY_NAME_ALTERNATIVE
1089                        + " AS " + Contacts.DISPLAY_NAME_ALTERNATIVE + ", "
1090                + "name_raw_contact." + RawContacts.PHONETIC_NAME
1091                        + " AS " + Contacts.PHONETIC_NAME + ", "
1092                + "name_raw_contact." + RawContacts.PHONETIC_NAME_STYLE
1093                        + " AS " + Contacts.PHONETIC_NAME_STYLE + ", "
1094                + "name_raw_contact." + RawContacts.SORT_KEY_PRIMARY
1095                        + " AS " + Contacts.SORT_KEY_PRIMARY + ", "
1096                + "name_raw_contact." + RawContacts.SORT_KEY_ALTERNATIVE
1097                        + " AS " + Contacts.SORT_KEY_ALTERNATIVE + ", "
1098                + "name_raw_contact." + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP
1099                        + " AS " + Contacts.IN_VISIBLE_GROUP;
1100
1101        String dataSelect = "SELECT "
1102                + DataColumns.CONCRETE_ID + " AS " + Data._ID + ","
1103                + Data.RAW_CONTACT_ID + ", "
1104                + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
1105                + syncColumns + ", "
1106                + dataColumns + ", "
1107                + contactOptionColumns + ", "
1108                + contactNameColumns + ", "
1109                + Contacts.LOOKUP_KEY + ", "
1110                + Contacts.PHOTO_ID + ", "
1111                + ContactsColumns.LAST_STATUS_UPDATE_ID + ", "
1112                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1113                + " FROM " + Tables.DATA
1114                + " JOIN " + Tables.MIMETYPES + " ON ("
1115                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1116                + " JOIN " + Tables.RAW_CONTACTS + " ON ("
1117                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1118                + " JOIN " + Tables.CONTACTS + " ON ("
1119                +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
1120                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1121                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
1122                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1123                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1124                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1125                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1126                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1127                        + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1128
1129        db.execSQL("CREATE VIEW " + Views.DATA_ALL + " AS " + dataSelect);
1130        db.execSQL("CREATE VIEW " + Views.DATA_RESTRICTED + " AS " + dataSelect + " WHERE "
1131                + RawContactsColumns.CONCRETE_IS_RESTRICTED + "=0");
1132
1133        String rawContactOptionColumns =
1134                RawContacts.CUSTOM_RINGTONE + ","
1135                + RawContacts.SEND_TO_VOICEMAIL + ","
1136                + RawContacts.LAST_TIME_CONTACTED + ","
1137                + RawContacts.TIMES_CONTACTED + ","
1138                + RawContacts.STARRED;
1139
1140        String rawContactsSelect = "SELECT "
1141                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ","
1142                + RawContacts.CONTACT_ID + ", "
1143                + RawContacts.AGGREGATION_MODE + ", "
1144                + RawContacts.DELETED + ", "
1145                + RawContacts.DISPLAY_NAME_SOURCE  + ", "
1146                + RawContacts.DISPLAY_NAME_PRIMARY  + ", "
1147                + RawContacts.DISPLAY_NAME_ALTERNATIVE  + ", "
1148                + RawContacts.PHONETIC_NAME  + ", "
1149                + RawContacts.PHONETIC_NAME_STYLE  + ", "
1150                + RawContacts.SORT_KEY_PRIMARY  + ", "
1151                + RawContacts.SORT_KEY_ALTERNATIVE + ", "
1152                + rawContactOptionColumns + ", "
1153                + syncColumns
1154                + " FROM " + Tables.RAW_CONTACTS;
1155
1156        db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS_ALL + " AS " + rawContactsSelect);
1157        db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS_RESTRICTED + " AS " + rawContactsSelect
1158                + " WHERE " + RawContacts.IS_RESTRICTED + "=0");
1159
1160        String contactsColumns =
1161                ContactsColumns.CONCRETE_CUSTOM_RINGTONE
1162                        + " AS " + Contacts.CUSTOM_RINGTONE + ", "
1163                + contactNameColumns + ", "
1164                + Contacts.HAS_PHONE_NUMBER + ", "
1165                + Contacts.LOOKUP_KEY + ", "
1166                + Contacts.PHOTO_ID + ", "
1167                + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
1168                        + " AS " + Contacts.LAST_TIME_CONTACTED + ", "
1169                + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
1170                        + " AS " + Contacts.SEND_TO_VOICEMAIL + ", "
1171                + ContactsColumns.CONCRETE_STARRED
1172                        + " AS " + Contacts.STARRED + ", "
1173                + ContactsColumns.CONCRETE_TIMES_CONTACTED
1174                        + " AS " + Contacts.TIMES_CONTACTED + ", "
1175                + ContactsColumns.LAST_STATUS_UPDATE_ID;
1176
1177        String contactsSelect = "SELECT "
1178                + ContactsColumns.CONCRETE_ID + " AS " + Contacts._ID + ","
1179                + contactsColumns
1180                + " FROM " + Tables.CONTACTS
1181                + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
1182                +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")";
1183
1184        db.execSQL("CREATE VIEW " + Views.CONTACTS_ALL + " AS " + contactsSelect);
1185        db.execSQL("CREATE VIEW " + Views.CONTACTS_RESTRICTED + " AS " + contactsSelect
1186                + " WHERE " + ContactsColumns.SINGLE_IS_RESTRICTED + "=0");
1187    }
1188
1189    private static void createGroupsView(SQLiteDatabase db) {
1190        db.execSQL("DROP VIEW IF EXISTS " + Views.GROUPS_ALL + ";");
1191        String groupsColumns =
1192                Groups.ACCOUNT_NAME + ","
1193                + Groups.ACCOUNT_TYPE + ","
1194                + Groups.SOURCE_ID + ","
1195                + Groups.VERSION + ","
1196                + Groups.DIRTY + ","
1197                + Groups.TITLE + ","
1198                + Groups.TITLE_RES + ","
1199                + Groups.NOTES + ","
1200                + Groups.SYSTEM_ID + ","
1201                + Groups.DELETED + ","
1202                + Groups.GROUP_VISIBLE + ","
1203                + Groups.SHOULD_SYNC + ","
1204                + Groups.SYNC1 + ","
1205                + Groups.SYNC2 + ","
1206                + Groups.SYNC3 + ","
1207                + Groups.SYNC4 + ","
1208                + PackagesColumns.PACKAGE + " AS " + Groups.RES_PACKAGE;
1209
1210        String groupsSelect = "SELECT "
1211                + GroupsColumns.CONCRETE_ID + " AS " + Groups._ID + ","
1212                + groupsColumns
1213                + " FROM " + Tables.GROUPS_JOIN_PACKAGES;
1214
1215        db.execSQL("CREATE VIEW " + Views.GROUPS_ALL + " AS " + groupsSelect);
1216    }
1217
1218    private static void createContactEntitiesView(SQLiteDatabase db) {
1219        db.execSQL("DROP VIEW IF EXISTS " + Tables.CONTACT_ENTITIES + ";");
1220        db.execSQL("DROP VIEW IF EXISTS " + Tables.CONTACT_ENTITIES_RESTRICTED + ";");
1221
1222        String contactEntitiesSelect = "SELECT "
1223                + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ","
1224                + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ","
1225                + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + ","
1226                + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + ","
1227                + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + ","
1228                + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
1229                + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + ","
1230                + RawContacts.CONTACT_ID + ", "
1231                + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + ", "
1232                + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + ", "
1233                + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + ", "
1234                + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4 + ", "
1235                + Data.MIMETYPE + ", "
1236                + Data.DATA1 + ", "
1237                + Data.DATA2 + ", "
1238                + Data.DATA3 + ", "
1239                + Data.DATA4 + ", "
1240                + Data.DATA5 + ", "
1241                + Data.DATA6 + ", "
1242                + Data.DATA7 + ", "
1243                + Data.DATA8 + ", "
1244                + Data.DATA9 + ", "
1245                + Data.DATA10 + ", "
1246                + Data.DATA11 + ", "
1247                + Data.DATA12 + ", "
1248                + Data.DATA13 + ", "
1249                + Data.DATA14 + ", "
1250                + Data.DATA15 + ", "
1251                + Data.SYNC1 + ", "
1252                + Data.SYNC2 + ", "
1253                + Data.SYNC3 + ", "
1254                + Data.SYNC4 + ", "
1255                + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ", "
1256                + Data.IS_PRIMARY + ", "
1257                + Data.IS_SUPER_PRIMARY + ", "
1258                + Data.DATA_VERSION + ", "
1259                + DataColumns.CONCRETE_ID + " AS " + RawContacts.Entity.DATA_ID + ","
1260                + RawContactsColumns.CONCRETE_STARRED + " AS " + RawContacts.STARRED + ","
1261                + RawContactsColumns.CONCRETE_IS_RESTRICTED + " AS "
1262                        + RawContacts.IS_RESTRICTED + ","
1263                + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
1264                + " FROM " + Tables.RAW_CONTACTS
1265                + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
1266                +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
1267                + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
1268                +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
1269                + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
1270                +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
1271                + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
1272                +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
1273                +   "' AND " + GroupsColumns.CONCRETE_ID + "="
1274                + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
1275
1276        db.execSQL("CREATE VIEW " + Tables.CONTACT_ENTITIES + " AS "
1277                + contactEntitiesSelect);
1278        db.execSQL("CREATE VIEW " + Tables.CONTACT_ENTITIES_RESTRICTED + " AS "
1279                + contactEntitiesSelect + " WHERE " + RawContacts.IS_RESTRICTED + "=0");
1280    }
1281
1282    @Override
1283    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1284        if (oldVersion < 99) {
1285            Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion
1286                    + ", data will be lost!");
1287
1288            db.execSQL("DROP TABLE IF EXISTS " + Tables.CONTACTS + ";");
1289            db.execSQL("DROP TABLE IF EXISTS " + Tables.RAW_CONTACTS + ";");
1290            db.execSQL("DROP TABLE IF EXISTS " + Tables.PACKAGES + ";");
1291            db.execSQL("DROP TABLE IF EXISTS " + Tables.MIMETYPES + ";");
1292            db.execSQL("DROP TABLE IF EXISTS " + Tables.DATA + ";");
1293            db.execSQL("DROP TABLE IF EXISTS " + Tables.PHONE_LOOKUP + ";");
1294            db.execSQL("DROP TABLE IF EXISTS " + Tables.NAME_LOOKUP + ";");
1295            db.execSQL("DROP TABLE IF EXISTS " + Tables.NICKNAME_LOOKUP + ";");
1296            db.execSQL("DROP TABLE IF EXISTS " + Tables.GROUPS + ";");
1297            db.execSQL("DROP TABLE IF EXISTS " + Tables.ACTIVITIES + ";");
1298            db.execSQL("DROP TABLE IF EXISTS " + Tables.CALLS + ";");
1299            db.execSQL("DROP TABLE IF EXISTS " + Tables.SETTINGS + ";");
1300            db.execSQL("DROP TABLE IF EXISTS " + Tables.STATUS_UPDATES + ";");
1301
1302            // TODO: we should not be dropping agg_exceptions and contact_options. In case that
1303            // table's schema changes, we should try to preserve the data, because it was entered
1304            // by the user and has never been synched to the server.
1305            db.execSQL("DROP TABLE IF EXISTS " + Tables.AGGREGATION_EXCEPTIONS + ";");
1306
1307            onCreate(db);
1308            return;
1309        }
1310
1311        Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion);
1312
1313        boolean upgradeViewsAndTriggers = false;
1314
1315        if (oldVersion == 99) {
1316            upgradeViewsAndTriggers = true;
1317            oldVersion++;
1318        }
1319
1320        if (oldVersion == 100) {
1321            db.execSQL("CREATE INDEX IF NOT EXISTS mimetypes_mimetype_index ON "
1322                    + Tables.MIMETYPES + " ("
1323                            + MimetypesColumns.MIMETYPE + ","
1324                            + MimetypesColumns._ID + ");");
1325            updateIndexStats(db, Tables.MIMETYPES,
1326                    "mimetypes_mimetype_index", "50 1 1");
1327
1328            upgradeViewsAndTriggers = true;
1329            oldVersion++;
1330        }
1331
1332        if (oldVersion == 101) {
1333            upgradeViewsAndTriggers = true;
1334            oldVersion++;
1335        }
1336
1337        if (oldVersion == 102) {
1338            upgradeViewsAndTriggers = true;
1339            oldVersion++;
1340        }
1341
1342        if (oldVersion == 103) {
1343            upgradeViewsAndTriggers = true;
1344            oldVersion++;
1345        }
1346
1347        if (oldVersion == 104 || oldVersion == 201) {
1348            LegacyApiSupport.createSettingsTable(db);
1349            upgradeViewsAndTriggers = true;
1350            oldVersion++;
1351        }
1352
1353        if (oldVersion == 105) {
1354            upgradeToVersion202(db);
1355            oldVersion = 202;
1356        }
1357
1358        if (oldVersion == 202) {
1359            upgradeToVersion203(db);
1360            upgradeViewsAndTriggers = true;
1361            oldVersion++;
1362        }
1363
1364        if (oldVersion == 203) {
1365            upgradeViewsAndTriggers = true;
1366            oldVersion++;
1367        }
1368
1369        if (oldVersion == 204) {
1370            upgradeToVersion205(db);
1371            upgradeViewsAndTriggers = true;
1372            oldVersion++;
1373        }
1374
1375        if (upgradeViewsAndTriggers) {
1376            createContactsViews(db);
1377            createGroupsView(db);
1378            createContactEntitiesView(db);
1379            createContactsTriggers(db);
1380            LegacyApiSupport.createViews(db);
1381        }
1382
1383        if (oldVersion != newVersion) {
1384            throw new IllegalStateException(
1385                    "error upgrading the database to version " + newVersion);
1386        }
1387    }
1388
1389    private void upgradeToVersion202(SQLiteDatabase db) {
1390        db.execSQL(
1391                "ALTER TABLE " + Tables.PHONE_LOOKUP +
1392                " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;");
1393
1394        db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
1395                PhoneLookupColumns.MIN_MATCH + "," +
1396                PhoneLookupColumns.RAW_CONTACT_ID + "," +
1397                PhoneLookupColumns.DATA_ID +
1398        ");");
1399
1400        updateIndexStats(db, Tables.PHONE_LOOKUP,
1401                "phone_lookup_min_match_index", "10000 2 2 1");
1402
1403        SQLiteStatement update = db.compileStatement(
1404                "UPDATE " + Tables.PHONE_LOOKUP +
1405                " SET " + PhoneLookupColumns.MIN_MATCH + "=?" +
1406                " WHERE " + PhoneLookupColumns.DATA_ID + "=?");
1407
1408        // Populate the new column
1409        Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA +
1410                " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")",
1411                new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null);
1412        try {
1413            while (c.moveToNext()) {
1414                long dataId = c.getLong(0);
1415                String number = c.getString(1);
1416                if (!TextUtils.isEmpty(number)) {
1417                    update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number));
1418                    update.bindLong(2, dataId);
1419                    update.execute();
1420                }
1421            }
1422        } finally {
1423            c.close();
1424        }
1425    }
1426
1427    private void upgradeToVersion203(SQLiteDatabase db) {
1428        db.execSQL(
1429                "ALTER TABLE " + Tables.CONTACTS +
1430                " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)");
1431        db.execSQL(
1432                "ALTER TABLE " + Tables.RAW_CONTACTS +
1433                " ADD " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP
1434                        + " INTEGER NOT NULL DEFAULT 0");
1435
1436        // For each Contact, find the RawContact that contributed the display name
1437        db.execSQL(
1438                "UPDATE " + Tables.CONTACTS +
1439                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
1440                        " SELECT " + RawContacts._ID +
1441                        " FROM " + Tables.RAW_CONTACTS +
1442                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
1443                        " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" +
1444                                Tables.CONTACTS + "." + Contacts.DISPLAY_NAME +
1445                        " ORDER BY " + RawContacts._ID +
1446                        " LIMIT 1)"
1447        );
1448
1449        db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
1450                Contacts.NAME_RAW_CONTACT_ID +
1451        ");");
1452
1453        // If for some unknown reason we missed some names, let's make sure there are
1454        // no contacts without a name, picking a raw contact "at random".
1455        db.execSQL(
1456                "UPDATE " + Tables.CONTACTS +
1457                " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
1458                        " SELECT " + RawContacts._ID +
1459                        " FROM " + Tables.RAW_CONTACTS +
1460                        " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
1461                        " ORDER BY " + RawContacts._ID +
1462                        " LIMIT 1)" +
1463                " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL"
1464        );
1465
1466        // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use.
1467        db.execSQL(
1468                "UPDATE " + Tables.CONTACTS +
1469                " SET " + Contacts.DISPLAY_NAME + "=NULL"
1470        );
1471
1472        // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow
1473        // indexing on (display_name, in_visible_group)
1474        db.execSQL(
1475                "UPDATE " + Tables.RAW_CONTACTS +
1476                " SET " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "=(" +
1477                        "SELECT " + Contacts.IN_VISIBLE_GROUP +
1478                        " FROM " + Tables.CONTACTS +
1479                        " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")"
1480        );
1481
1482        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
1483                RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
1484                RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" +
1485        ");");
1486
1487        db.execSQL("DROP INDEX contacts_visible_index");
1488        db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
1489                Contacts.IN_VISIBLE_GROUP +
1490        ");");
1491    }
1492
1493    private void upgradeToVersion205(SQLiteDatabase db) {
1494        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1495                + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;");
1496        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1497                + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;");
1498        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1499                + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;");
1500        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1501                + " ADD " + RawContacts.SORT_KEY_PRIMARY + " TEXT COLLATE LOCALIZED;");
1502        db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
1503                + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE + " TEXT COLLATE LOCALIZED;");
1504
1505        final Locale locale = Locale.getDefault();
1506
1507        NameSplitter splitter = new NameSplitter(
1508                mContext.getString(com.android.internal.R.string.common_name_prefixes),
1509                mContext.getString(com.android.internal.R.string.common_last_name_prefixes),
1510                mContext.getString(com.android.internal.R.string.common_name_suffixes),
1511                mContext.getString(com.android.internal.R.string.common_name_conjunctions),
1512                locale);
1513
1514        SQLiteStatement rawContactUpdate = db.compileStatement(
1515                "UPDATE " + Tables.RAW_CONTACTS +
1516                " SET " +
1517                        RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
1518                        RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
1519                        RawContacts.PHONETIC_NAME + "=?," +
1520                        RawContacts.PHONETIC_NAME_STYLE + "=?," +
1521                        RawContacts.SORT_KEY_PRIMARY + "=?," +
1522                        RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
1523                " WHERE " + RawContacts._ID + "=?");
1524
1525        upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter);
1526        upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter);
1527
1528        db.execSQL("DROP INDEX raw_contact_sort_key1_index");
1529        db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
1530                RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
1531                RawContacts.SORT_KEY_PRIMARY +
1532        ");");
1533
1534        db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
1535                RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
1536                RawContacts.SORT_KEY_ALTERNATIVE +
1537        ");");
1538    }
1539
1540    private interface StructName205Query {
1541        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
1542
1543        String COLUMNS[] = {
1544                DataColumns.CONCRETE_ID,
1545                Data.RAW_CONTACT_ID,
1546                RawContacts.DISPLAY_NAME_SOURCE,
1547                RawContacts.DISPLAY_NAME_PRIMARY,
1548                StructuredName.PREFIX,
1549                StructuredName.GIVEN_NAME,
1550                StructuredName.MIDDLE_NAME,
1551                StructuredName.FAMILY_NAME,
1552                StructuredName.SUFFIX,
1553                StructuredName.PHONETIC_FAMILY_NAME,
1554                StructuredName.PHONETIC_MIDDLE_NAME,
1555                StructuredName.PHONETIC_GIVEN_NAME,
1556        };
1557
1558        int ID = 0;
1559        int RAW_CONTACT_ID = 1;
1560        int DISPLAY_NAME_SOURCE = 2;
1561        int DISPLAY_NAME = 3;
1562        int PREFIX = 4;
1563        int GIVEN_NAME = 5;
1564        int MIDDLE_NAME = 6;
1565        int FAMILY_NAME = 7;
1566        int SUFFIX = 8;
1567        int PHONETIC_FAMILY_NAME = 9;
1568        int PHONETIC_MIDDLE_NAME = 10;
1569        int PHONETIC_GIVEN_NAME = 11;
1570    }
1571
1572    private void upgradeStructuredNamesToVersion205(SQLiteDatabase db,
1573            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
1574
1575        // Process structured names to detect the style of the full name and phonetic name
1576
1577        long mMimeType;
1578        try {
1579            mMimeType = DatabaseUtils.longForQuery(db,
1580                    "SELECT " + MimetypesColumns._ID +
1581                    " FROM " + Tables.MIMETYPES +
1582                    " WHERE " + MimetypesColumns.MIMETYPE
1583                            + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null);
1584        } catch (SQLiteDoneException e) {
1585            // No structured names in the database
1586            return;
1587        }
1588
1589        SQLiteStatement structuredNameUpdate = db.compileStatement(
1590                "UPDATE " + Tables.DATA +
1591                " SET " +
1592                        StructuredName.FULL_NAME_STYLE + "=?," +
1593                        StructuredName.DISPLAY_NAME + "=?," +
1594                        StructuredName.PHONETIC_NAME_STYLE + "=?" +
1595                " WHERE " + Data._ID + "=?");
1596
1597        NameSplitter.Name name = new NameSplitter.Name();
1598        StringBuilder sb = new StringBuilder();
1599        Cursor cursor = db.query(StructName205Query.TABLE,
1600                StructName205Query.COLUMNS,
1601                DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null);
1602        try {
1603            while (cursor.moveToNext()) {
1604                long dataId = cursor.getLong(StructName205Query.ID);
1605                long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID);
1606                int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE);
1607                String displayName = cursor.getString(StructName205Query.DISPLAY_NAME);
1608
1609                name.clear();
1610                name.prefix = cursor.getString(StructName205Query.PREFIX);
1611                name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME);
1612                name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME);
1613                name.familyName = cursor.getString(StructName205Query.FAMILY_NAME);
1614                name.suffix = cursor.getString(StructName205Query.SUFFIX);
1615                name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME);
1616                name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME);
1617                name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME);
1618
1619                upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name,
1620                        structuredNameUpdate, rawContactUpdate, splitter, sb);
1621            }
1622        } finally {
1623            cursor.close();
1624        }
1625    }
1626
1627    private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource,
1628            String currentDisplayName, NameSplitter.Name name,
1629            SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate,
1630            NameSplitter splitter, StringBuilder sb) {
1631
1632        splitter.guessNameStyle(name);
1633        name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle);
1634        String displayName = splitter.join(name, true);
1635
1636        structuredNameUpdate.bindLong(1, name.fullNameStyle);
1637        DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName);
1638        structuredNameUpdate.bindLong(3, name.phoneticNameStyle);
1639        structuredNameUpdate.bindLong(4, dataId);
1640        structuredNameUpdate.execute();
1641
1642        if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) {
1643            String displayNameAlternative = splitter.join(name, false);
1644            String phoneticName = splitter.joinPhoneticName(name);
1645            String sortKey = null;
1646            String sortKeyAlternative = null;
1647
1648            if (phoneticName != null) {
1649                sortKey = sortKeyAlternative = phoneticName;
1650            } else if (name.fullNameStyle == FullNameStyle.CHINESE) {
1651                sortKey = sortKeyAlternative = splitter.convertHanziToPinyin(displayName);
1652            }
1653
1654            if (sortKey == null) {
1655                sortKey = displayName;
1656                sortKeyAlternative = displayNameAlternative;
1657            }
1658
1659            updateRawContact205(rawContactUpdate, rawContactId, displayName,
1660                    displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey,
1661                    sortKeyAlternative);
1662        }
1663    }
1664
1665    private interface Organization205Query {
1666        String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
1667
1668        String COLUMNS[] = {
1669                DataColumns.CONCRETE_ID,
1670                Data.RAW_CONTACT_ID,
1671                Organization.COMPANY,
1672                Organization.PHONETIC_NAME,
1673        };
1674
1675        int ID = 0;
1676        int RAW_CONTACT_ID = 1;
1677        int COMPANY = 2;
1678        int PHONETIC_NAME = 3;
1679    }
1680
1681    private void upgradeOrganizationsToVersion205(SQLiteDatabase db,
1682            SQLiteStatement rawContactUpdate, NameSplitter splitter) {
1683
1684        final long mMimeType;
1685        try {
1686            mMimeType = DatabaseUtils.longForQuery(db,
1687                    "SELECT " + MimetypesColumns._ID +
1688                    " FROM " + Tables.MIMETYPES +
1689                    " WHERE " + MimetypesColumns.MIMETYPE
1690                            + "='" + Organization.CONTENT_ITEM_TYPE + "'", null);
1691        } catch (SQLiteDoneException e) {
1692            // No organizations in the database
1693            return;
1694        }
1695
1696        SQLiteStatement organizationUpdate = db.compileStatement(
1697                "UPDATE " + Tables.DATA +
1698                " SET " +
1699                        Organization.PHONETIC_NAME_STYLE + "=?" +
1700                " WHERE " + Data._ID + "=?");
1701
1702        Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS,
1703                DataColumns.MIMETYPE_ID + "=" + mMimeType + " AND "
1704                        + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION,
1705                null, null, null, null);
1706        try {
1707            while (cursor.moveToNext()) {
1708                long dataId = cursor.getLong(Organization205Query.ID);
1709                long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID);
1710                String company = cursor.getString(Organization205Query.COMPANY);
1711                String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME);
1712
1713                int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName);
1714
1715                organizationUpdate.bindLong(1, phoneticNameStyle);
1716                organizationUpdate.bindLong(2, dataId);
1717                organizationUpdate.execute();
1718
1719                String sortKey = null;
1720                if (phoneticName == null && company != null) {
1721                    int nameStyle = splitter.guessFullNameStyle(company);
1722                    nameStyle = splitter.getAdjustedFullNameStyle(nameStyle);
1723                    if (nameStyle == FullNameStyle.CHINESE) {
1724                        sortKey = splitter.convertHanziToPinyin(company);
1725                    }
1726                }
1727
1728                if (sortKey == null) {
1729                    sortKey = company;
1730                }
1731
1732                updateRawContact205(rawContactUpdate, rawContactId, company,
1733                        company, phoneticNameStyle, phoneticName, sortKey, sortKey);
1734            }
1735        } finally {
1736            cursor.close();
1737        }
1738    }
1739
1740    private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId,
1741            String displayName, String displayNameAlternative, int phoneticNameStyle,
1742            String phoneticName, String sortKeyPrimary, String sortKeyAlternative) {
1743        bindString(rawContactUpdate, 1, displayName);
1744        bindString(rawContactUpdate, 2, displayNameAlternative);
1745        bindString(rawContactUpdate, 3, phoneticName);
1746        rawContactUpdate.bindLong(4, phoneticNameStyle);
1747        bindString(rawContactUpdate, 5, sortKeyPrimary);
1748        bindString(rawContactUpdate, 6, sortKeyAlternative);
1749        rawContactUpdate.bindLong(7, rawContactId);
1750        rawContactUpdate.execute();
1751    }
1752
1753    private void bindString(SQLiteStatement stmt, int index, String value) {
1754        if (value == null) {
1755            stmt.bindNull(index);
1756        } else {
1757            stmt.bindString(index, value);
1758        }
1759    }
1760
1761    /**
1762     * Adds index stats into the SQLite database to force it to always use the lookup indexes.
1763     */
1764    private void updateSqliteStats(SQLiteDatabase db) {
1765
1766        // Specific stats strings are based on an actual large database after running ANALYZE
1767        try {
1768            updateIndexStats(db, Tables.CONTACTS,
1769                    "contacts_restricted_index", "10000 9000");
1770            updateIndexStats(db, Tables.CONTACTS,
1771                    "contacts_has_phone_index", "10000 500");
1772            updateIndexStats(db, Tables.CONTACTS,
1773                    "contacts_visible_index", "10000 500 1");
1774
1775            updateIndexStats(db, Tables.RAW_CONTACTS,
1776                    "raw_contacts_source_id_index", "10000 1 1 1");
1777            updateIndexStats(db, Tables.RAW_CONTACTS,
1778                    "raw_contacts_contact_id_index", "10000 2");
1779
1780            updateIndexStats(db, Tables.NAME_LOOKUP,
1781                    "name_lookup_raw_contact_id_index", "10000 3");
1782            updateIndexStats(db, Tables.NAME_LOOKUP,
1783                    "name_lookup_index", "10000 3 2 2");
1784            updateIndexStats(db, Tables.NAME_LOOKUP,
1785                    "sqlite_autoindex_name_lookup_1", "10000 3 2 1");
1786
1787            updateIndexStats(db, Tables.PHONE_LOOKUP,
1788                    "phone_lookup_index", "10000 2 2 1");
1789            updateIndexStats(db, Tables.PHONE_LOOKUP,
1790                    "phone_lookup_min_match_index", "10000 2 2 1");
1791
1792            updateIndexStats(db, Tables.DATA,
1793                    "data_mimetype_data1_index", "60000 5000 2");
1794            updateIndexStats(db, Tables.DATA,
1795                    "data_raw_contact_id", "60000 10");
1796
1797            updateIndexStats(db, Tables.GROUPS,
1798                    "groups_source_id_index", "50 1 1 1");
1799
1800            updateIndexStats(db, Tables.NICKNAME_LOOKUP,
1801                    "sqlite_autoindex_name_lookup_1", "500 2 1");
1802
1803        } catch (SQLException e) {
1804            Log.e(TAG, "Could not update index stats", e);
1805        }
1806    }
1807
1808    /**
1809     * Stores statistics for a given index.
1810     *
1811     * @param stats has the following structure: the first index is the expected size of
1812     * the table.  The following integer(s) are the expected number of records selected with the
1813     * index.  There should be one integer per indexed column.
1814     */
1815    private void updateIndexStats(SQLiteDatabase db, String table, String index,
1816            String stats) {
1817        db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl='" + table + "' AND idx='" + index + "';");
1818        db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat)"
1819                + " VALUES ('" + table + "','" + index + "','" + stats + "');");
1820    }
1821
1822    @Override
1823    public synchronized SQLiteDatabase getWritableDatabase() {
1824        SQLiteDatabase db = super.getWritableDatabase();
1825        if (mReopenDatabase) {
1826            mReopenDatabase = false;
1827            close();
1828            db = super.getWritableDatabase();
1829        }
1830        // let {@link SQLiteDatabase} cache my compiled-sql statements.
1831        db.setMaxSqlCacheSize(MAX_CACHE_SIZE_FOR_CONTACTS_DB);
1832        return db;
1833    }
1834
1835    /**
1836     * Wipes all data except mime type and package lookup tables.
1837     */
1838    public void wipeData() {
1839        SQLiteDatabase db = getWritableDatabase();
1840
1841        db.execSQL("DELETE FROM " + Tables.CONTACTS + ";");
1842        db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";");
1843        db.execSQL("DELETE FROM " + Tables.DATA + ";");
1844        db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";");
1845        db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";");
1846        db.execSQL("DELETE FROM " + Tables.GROUPS + ";");
1847        db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";");
1848        db.execSQL("DELETE FROM " + Tables.SETTINGS + ";");
1849        db.execSQL("DELETE FROM " + Tables.ACTIVITIES + ";");
1850        db.execSQL("DELETE FROM " + Tables.CALLS + ";");
1851
1852        // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP
1853    }
1854
1855    /**
1856     * Return the {@link ApplicationInfo#uid} for the given package name.
1857     */
1858    public static int getUidForPackageName(PackageManager pm, String packageName) {
1859        try {
1860            ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */);
1861            return clientInfo.uid;
1862        } catch (NameNotFoundException e) {
1863            throw new RuntimeException(e);
1864        }
1865    }
1866
1867    /**
1868     * Perform an internal string-to-integer lookup using the compiled
1869     * {@link SQLiteStatement} provided, using the in-memory cache to speed up
1870     * lookups. If a mapping isn't found in cache or database, it will be
1871     * created. All new, uncached answers are added to the cache automatically.
1872     *
1873     * @param query Compiled statement used to query for the mapping.
1874     * @param insert Compiled statement used to insert a new mapping when no
1875     *            existing one is found in cache or from query.
1876     * @param value Value to find mapping for.
1877     * @param cache In-memory cache of previous answers.
1878     * @return An unique integer mapping for the given value.
1879     */
1880    private synchronized long getCachedId(SQLiteStatement query, SQLiteStatement insert,
1881            String value, HashMap<String, Long> cache) {
1882        // Try an in-memory cache lookup
1883        if (cache.containsKey(value)) {
1884            return cache.get(value);
1885        }
1886
1887        long id = -1;
1888        try {
1889            // Try searching database for mapping
1890            DatabaseUtils.bindObjectToProgram(query, 1, value);
1891            id = query.simpleQueryForLong();
1892        } catch (SQLiteDoneException e) {
1893            // Nothing found, so try inserting new mapping
1894            DatabaseUtils.bindObjectToProgram(insert, 1, value);
1895            id = insert.executeInsert();
1896        }
1897
1898        if (id != -1) {
1899            // Cache and return the new answer
1900            cache.put(value, id);
1901            return id;
1902        } else {
1903            // Otherwise throw if no mapping found or created
1904            throw new IllegalStateException("Couldn't find or create internal "
1905                    + "lookup table entry for value " + value);
1906        }
1907    }
1908
1909    /**
1910     * Convert a package name into an integer, using {@link Tables#PACKAGES} for
1911     * lookups and possible allocation of new IDs as needed.
1912     */
1913    public long getPackageId(String packageName) {
1914        // Make sure compiled statements are ready by opening database
1915        getReadableDatabase();
1916        return getCachedId(mPackageQuery, mPackageInsert, packageName, mPackageCache);
1917    }
1918
1919    /**
1920     * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for
1921     * lookups and possible allocation of new IDs as needed.
1922     */
1923    public long getMimeTypeId(String mimetype) {
1924        // Make sure compiled statements are ready by opening database
1925        getReadableDatabase();
1926        return getMimeTypeIdNoDbCheck(mimetype);
1927    }
1928
1929    private long getMimeTypeIdNoDbCheck(String mimetype) {
1930        return getCachedId(mMimetypeQuery, mMimetypeInsert, mimetype, mMimetypeCache);
1931    }
1932
1933    /**
1934     * Find the mimetype for the given {@link Data#_ID}.
1935     */
1936    public String getDataMimeType(long dataId) {
1937        // Make sure compiled statements are ready by opening database
1938        getReadableDatabase();
1939        try {
1940            // Try database query to find mimetype
1941            DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId);
1942            String mimetype = mDataMimetypeQuery.simpleQueryForString();
1943            return mimetype;
1944        } catch (SQLiteDoneException e) {
1945            // No valid mapping found, so return null
1946            return null;
1947        }
1948    }
1949
1950    /**
1951     * Find the mime-type for the given {@link Activities#_ID}.
1952     */
1953    public String getActivityMimeType(long activityId) {
1954        // Make sure compiled statements are ready by opening database
1955        getReadableDatabase();
1956        try {
1957            // Try database query to find mimetype
1958            DatabaseUtils.bindObjectToProgram(mActivitiesMimetypeQuery, 1, activityId);
1959            String mimetype = mActivitiesMimetypeQuery.simpleQueryForString();
1960            return mimetype;
1961        } catch (SQLiteDoneException e) {
1962            // No valid mapping found, so return null
1963            return null;
1964        }
1965    }
1966
1967    /**
1968     * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts.
1969     */
1970    public void updateAllVisible() {
1971        final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
1972        mVisibleUpdate.bindLong(1, groupMembershipMimetypeId);
1973        mVisibleUpdate.execute();
1974        mVisibleUpdateRawContacts.execute();
1975    }
1976
1977    /**
1978     * Update {@link Contacts#IN_VISIBLE_GROUP} for a specific contact.
1979     */
1980    public void updateContactVisible(long contactId) {
1981        final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
1982        mVisibleSpecificUpdate.bindLong(1, groupMembershipMimetypeId);
1983        mVisibleSpecificUpdate.bindLong(2, contactId);
1984        mVisibleSpecificUpdate.execute();
1985
1986        mVisibleSpecificUpdateRawContacts.bindLong(1, contactId);
1987        mVisibleSpecificUpdateRawContacts.execute();
1988    }
1989
1990    /**
1991     * Returns contact ID for the given contact or zero if it is NULL.
1992     */
1993    public long getContactId(long rawContactId) {
1994        getReadableDatabase();
1995        try {
1996            DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId);
1997            return mContactIdQuery.simpleQueryForLong();
1998        } catch (SQLiteDoneException e) {
1999            // No valid mapping found, so return 0
2000            return 0;
2001        }
2002    }
2003
2004    public int getAggregationMode(long rawContactId) {
2005        getReadableDatabase();
2006        try {
2007            DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId);
2008            return (int)mAggregationModeQuery.simpleQueryForLong();
2009        } catch (SQLiteDoneException e) {
2010            // No valid row found, so return "disabled"
2011            return RawContacts.AGGREGATION_MODE_DISABLED;
2012        }
2013    }
2014
2015    public void buildPhoneLookupAndRawContactQuery(SQLiteQueryBuilder qb, String number) {
2016        String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
2017        qb.setTables(Tables.DATA_JOIN_RAW_CONTACTS +
2018                " JOIN " + Tables.PHONE_LOOKUP
2019                + " ON(" + DataColumns.CONCRETE_ID + "=" + PhoneLookupColumns.DATA_ID + ")");
2020
2021        StringBuilder sb = new StringBuilder();
2022        sb.append(PhoneLookupColumns.MIN_MATCH + "='");
2023        sb.append(minMatch);
2024        sb.append("' AND PHONE_NUMBERS_EQUAL(data." + Phone.NUMBER + ", ");
2025        DatabaseUtils.appendEscapedSQLString(sb, number);
2026        sb.append(mUseStrictPhoneNumberComparison ? ", 1)" : ", 0)");
2027
2028        qb.appendWhere(sb.toString());
2029    }
2030
2031    public void buildPhoneLookupAndContactQuery(SQLiteQueryBuilder qb, String number) {
2032        String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
2033        StringBuilder sb = new StringBuilder();
2034        appendPhoneLookupTables(sb, minMatch, true);
2035        qb.setTables(sb.toString());
2036
2037        sb = new StringBuilder();
2038        appendPhoneLookupSelection(sb, number);
2039        qb.appendWhere(sb.toString());
2040    }
2041
2042    public String buildPhoneLookupAsNestedQuery(String number) {
2043        StringBuilder sb = new StringBuilder();
2044        final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
2045        sb.append("(SELECT DISTINCT raw_contact_id" + " FROM ");
2046        appendPhoneLookupTables(sb, minMatch, false);
2047        sb.append(" WHERE ");
2048        appendPhoneLookupSelection(sb, number);
2049        sb.append(")");
2050        return sb.toString();
2051    }
2052
2053    private void appendPhoneLookupTables(StringBuilder sb, final String minMatch,
2054            boolean joinContacts) {
2055        sb.append(Tables.RAW_CONTACTS);
2056        if (joinContacts) {
2057            sb.append(" JOIN " + getContactView() + " contacts_view"
2058                    + " ON (contacts_view._id = raw_contacts.contact_id)");
2059        }
2060        sb.append(", (SELECT data_id FROM phone_lookup "
2061                + "WHERE (" + Tables.PHONE_LOOKUP + "." + PhoneLookupColumns.MIN_MATCH + " = '");
2062        sb.append(minMatch);
2063        sb.append("')) AS lookup, " + Tables.DATA);
2064    }
2065
2066    private void appendPhoneLookupSelection(StringBuilder sb, String number) {
2067        sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id"
2068                + " AND PHONE_NUMBERS_EQUAL(data." + Phone.NUMBER + ", ");
2069        DatabaseUtils.appendEscapedSQLString(sb, number);
2070        sb.append(mUseStrictPhoneNumberComparison ? ", 1)" : ", 0)");
2071    }
2072
2073    public String getUseStrictPhoneNumberComparisonParameter() {
2074        return mUseStrictPhoneNumberComparison ? "1" : "0";
2075    }
2076
2077    /**
2078     * Loads common nickname mappings into the database.
2079     */
2080    private void loadNicknameLookupTable(SQLiteDatabase db) {
2081        String[] strings = mContext.getResources().getStringArray(
2082                com.android.internal.R.array.common_nicknames);
2083        if (strings == null || strings.length == 0) {
2084            return;
2085        }
2086
2087        SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO "
2088                + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + ","
2089                + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)");
2090
2091        for (int clusterId = 0; clusterId < strings.length; clusterId++) {
2092            String[] names = strings[clusterId].split(",");
2093            for (int j = 0; j < names.length; j++) {
2094                String name = NameNormalizer.normalize(names[j]);
2095                try {
2096                    DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name);
2097                    DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2,
2098                            String.valueOf(clusterId));
2099                    nicknameLookupInsert.executeInsert();
2100                } catch (SQLiteException e) {
2101
2102                    // Print the exception and keep going - this is not a fatal error
2103                    Log.e(TAG, "Cannot insert nickname: " + names[j], e);
2104                }
2105            }
2106        }
2107    }
2108
2109    public static void copyStringValue(ContentValues toValues, String toKey,
2110            ContentValues fromValues, String fromKey) {
2111        if (fromValues.containsKey(fromKey)) {
2112            toValues.put(toKey, fromValues.getAsString(fromKey));
2113        }
2114    }
2115
2116    public static void copyLongValue(ContentValues toValues, String toKey,
2117            ContentValues fromValues, String fromKey) {
2118        if (fromValues.containsKey(fromKey)) {
2119            long longValue;
2120            Object value = fromValues.get(fromKey);
2121            if (value instanceof Boolean) {
2122                if ((Boolean)value) {
2123                    longValue = 1;
2124                } else {
2125                    longValue = 0;
2126                }
2127            } else if (value instanceof String) {
2128                longValue = Long.parseLong((String)value);
2129            } else {
2130                longValue = ((Number)value).longValue();
2131            }
2132            toValues.put(toKey, longValue);
2133        }
2134    }
2135
2136    public SyncStateContentProviderHelper getSyncState() {
2137        return mSyncState;
2138    }
2139
2140    /**
2141     * Delete the aggregate contact if it has no constituent raw contacts other
2142     * than the supplied one.
2143     */
2144    public void removeContactIfSingleton(long rawContactId) {
2145        SQLiteDatabase db = getWritableDatabase();
2146
2147        // Obtain contact ID from the supplied raw contact ID
2148        String contactIdFromRawContactId = "(SELECT " + RawContacts.CONTACT_ID + " FROM "
2149                + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=" + rawContactId + ")";
2150
2151        // Find other raw contacts in the same aggregate contact
2152        String otherRawContacts = "(SELECT contacts1." + RawContacts._ID + " FROM "
2153                + Tables.RAW_CONTACTS + " contacts1 JOIN " + Tables.RAW_CONTACTS + " contacts2 ON ("
2154                + "contacts1." + RawContacts.CONTACT_ID + "=contacts2." + RawContacts.CONTACT_ID
2155                + ") WHERE contacts1." + RawContacts._ID + "!=" + rawContactId + ""
2156                + " AND contacts2." + RawContacts._ID + "=" + rawContactId + ")";
2157
2158        db.execSQL("DELETE FROM " + Tables.CONTACTS
2159                + " WHERE " + Contacts._ID + "=" + contactIdFromRawContactId
2160                + " AND NOT EXISTS " + otherRawContacts + ";");
2161    }
2162
2163    /**
2164     * Check if {@link Binder#getCallingUid()} should be allowed access to
2165     * {@link RawContacts#IS_RESTRICTED} data.
2166     */
2167    boolean hasAccessToRestrictedData() {
2168        final PackageManager pm = mContext.getPackageManager();
2169        final String[] callerPackages = pm.getPackagesForUid(Binder.getCallingUid());
2170
2171        // Has restricted access if caller matches any packages
2172        for (String callerPackage : callerPackages) {
2173            if (hasAccessToRestrictedData(callerPackage)) {
2174                return true;
2175            }
2176        }
2177        return false;
2178    }
2179
2180    /**
2181     * Check if requestingPackage should be allowed access to
2182     * {@link RawContacts#IS_RESTRICTED} data.
2183     */
2184    boolean hasAccessToRestrictedData(String requestingPackage) {
2185        if (mUnrestrictedPackages != null) {
2186            for (String allowedPackage : mUnrestrictedPackages) {
2187                if (allowedPackage.equals(requestingPackage)) {
2188                    return true;
2189                }
2190            }
2191        }
2192        return false;
2193    }
2194
2195    public String getDataView() {
2196        return getDataView(false);
2197    }
2198
2199    public String getDataView(boolean requireRestrictedView) {
2200        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
2201                Views.DATA_ALL : Views.DATA_RESTRICTED;
2202    }
2203
2204    public String getRawContactView() {
2205        return getRawContactView(false);
2206    }
2207
2208    public String getRawContactView(boolean requireRestrictedView) {
2209        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
2210                Views.RAW_CONTACTS_ALL : Views.RAW_CONTACTS_RESTRICTED;
2211    }
2212
2213    public String getContactView() {
2214        return getContactView(false);
2215    }
2216
2217    public String getContactView(boolean requireRestrictedView) {
2218        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
2219                Views.CONTACTS_ALL : Views.CONTACTS_RESTRICTED;
2220    }
2221
2222    public String getGroupView() {
2223        return Views.GROUPS_ALL;
2224    }
2225
2226    public String getContactEntitiesView() {
2227        return getContactEntitiesView(false);
2228    }
2229
2230    public String getContactEntitiesView(boolean requireRestrictedView) {
2231        return (hasAccessToRestrictedData() && !requireRestrictedView) ?
2232                Tables.CONTACT_ENTITIES : Tables.CONTACT_ENTITIES_RESTRICTED;
2233    }
2234
2235    /**
2236     * Test if any of the columns appear in the given projection.
2237     */
2238    public boolean isInProjection(String[] projection, String... columns) {
2239        if (projection == null) {
2240            return true;
2241        }
2242
2243        // Optimized for a single-column test
2244        if (columns.length == 1) {
2245            String column = columns[0];
2246            for (String test : projection) {
2247                if (column.equals(test)) {
2248                    return true;
2249                }
2250            }
2251        } else {
2252            for (String test : projection) {
2253                for (String column : columns) {
2254                    if (column.equals(test)) {
2255                        return true;
2256                    }
2257                }
2258            }
2259        }
2260        return false;
2261    }
2262}
2263