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