Home | History | Annotate | Download | only in contacts
      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 
     17 package com.android.providers.contacts;
     18 
     19 import com.android.internal.content.SyncStateContentProviderHelper;
     20 
     21 import android.content.ContentResolver;
     22 import android.content.ContentValues;
     23 import android.content.Context;
     24 import android.content.pm.ApplicationInfo;
     25 import android.content.pm.PackageManager;
     26 import android.content.pm.PackageManager.NameNotFoundException;
     27 import android.content.res.Resources;
     28 import android.database.Cursor;
     29 import android.database.DatabaseUtils;
     30 import android.database.SQLException;
     31 import android.database.sqlite.SQLiteDatabase;
     32 import android.database.sqlite.SQLiteDoneException;
     33 import android.database.sqlite.SQLiteException;
     34 import android.database.sqlite.SQLiteOpenHelper;
     35 import android.database.sqlite.SQLiteQueryBuilder;
     36 import android.database.sqlite.SQLiteStatement;
     37 import android.net.Uri;
     38 import android.os.Binder;
     39 import android.os.Bundle;
     40 import android.os.SystemClock;
     41 import android.provider.BaseColumns;
     42 import android.provider.ContactsContract;
     43 import android.provider.CallLog.Calls;
     44 import android.provider.ContactsContract.AggregationExceptions;
     45 import android.provider.ContactsContract.Contacts;
     46 import android.provider.ContactsContract.Data;
     47 import android.provider.ContactsContract.DisplayNameSources;
     48 import android.provider.ContactsContract.FullNameStyle;
     49 import android.provider.ContactsContract.Groups;
     50 import android.provider.ContactsContract.RawContacts;
     51 import android.provider.ContactsContract.Settings;
     52 import android.provider.ContactsContract.StatusUpdates;
     53 import android.provider.ContactsContract.CommonDataKinds.Email;
     54 import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
     55 import android.provider.ContactsContract.CommonDataKinds.Nickname;
     56 import android.provider.ContactsContract.CommonDataKinds.Organization;
     57 import android.provider.ContactsContract.CommonDataKinds.Phone;
     58 import android.provider.ContactsContract.CommonDataKinds.StructuredName;
     59 import android.provider.SocialContract.Activities;
     60 import android.telephony.PhoneNumberUtils;
     61 import android.text.TextUtils;
     62 import android.text.util.Rfc822Token;
     63 import android.text.util.Rfc822Tokenizer;
     64 import android.util.Log;
     65 
     66 import java.util.HashMap;
     67 import java.util.Locale;
     68 
     69 /**
     70  * Database helper for contacts. Designed as a singleton to make sure that all
     71  * {@link android.content.ContentProvider} users get the same reference.
     72  * Provides handy methods for maintaining package and mime-type lookup tables.
     73  */
     74 /* package */ class ContactsDatabaseHelper extends SQLiteOpenHelper {
     75     private static final String TAG = "ContactsDatabaseHelper";
     76 
     77     static final int DATABASE_VERSION = 309;
     78 
     79     private static final String DATABASE_NAME = "contacts2.db";
     80     private static final String DATABASE_PRESENCE = "presence_db";
     81 
     82     public interface Tables {
     83         public static final String CONTACTS = "contacts";
     84         public static final String RAW_CONTACTS = "raw_contacts";
     85         public static final String PACKAGES = "packages";
     86         public static final String MIMETYPES = "mimetypes";
     87         public static final String PHONE_LOOKUP = "phone_lookup";
     88         public static final String NAME_LOOKUP = "name_lookup";
     89         public static final String AGGREGATION_EXCEPTIONS = "agg_exceptions";
     90         public static final String SETTINGS = "settings";
     91         public static final String DATA = "data";
     92         public static final String GROUPS = "groups";
     93         public static final String PRESENCE = "presence";
     94         public static final String AGGREGATED_PRESENCE = "agg_presence";
     95         public static final String NICKNAME_LOOKUP = "nickname_lookup";
     96         public static final String CALLS = "calls";
     97         public static final String CONTACT_ENTITIES = "contact_entities_view";
     98         public static final String CONTACT_ENTITIES_RESTRICTED = "contact_entities_view_restricted";
     99         public static final String STATUS_UPDATES = "status_updates";
    100         public static final String PROPERTIES = "properties";
    101         public static final String ACCOUNTS = "accounts";
    102 
    103         public static final String DATA_JOIN_MIMETYPES = "data "
    104                 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id)";
    105 
    106         public static final String DATA_JOIN_RAW_CONTACTS = "data "
    107                 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
    108 
    109         public static final String DATA_JOIN_MIMETYPE_RAW_CONTACTS = "data "
    110                 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
    111                 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)";
    112 
    113         // NOTE: This requires late binding of GroupMembership MIME-type
    114         public static final String RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS = "raw_contacts "
    115                 + "LEFT OUTER JOIN settings 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 groups ON (groups._id = data." + GroupMembership.GROUP_ROW_ID
    121                 + ")";
    122 
    123         // NOTE: This requires late binding of GroupMembership MIME-type
    124         public static final String SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS = "settings "
    125                 + "LEFT OUTER JOIN raw_contacts ON ("
    126                     + "raw_contacts.account_name = settings.account_name AND "
    127                     + "raw_contacts.account_type = settings.account_type) "
    128                 + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND "
    129                     + "data.raw_contact_id = raw_contacts._id) "
    130                 + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
    131 
    132         public static final String DATA_JOIN_MIMETYPES_RAW_CONTACTS_CONTACTS = "data "
    133                 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
    134                 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
    135                 + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
    136 
    137         public static final String DATA_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_GROUPS = "data "
    138                 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) "
    139                 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) "
    140                 + "LEFT OUTER JOIN packages ON (data.package_id = packages._id) "
    141                 + "LEFT OUTER JOIN groups "
    142                 + "  ON (mimetypes.mimetype='" + GroupMembership.CONTENT_ITEM_TYPE + "' "
    143                 + "      AND groups._id = data." + GroupMembership.GROUP_ROW_ID + ") ";
    144 
    145         public static final String GROUPS_JOIN_PACKAGES = "groups "
    146                 + "LEFT OUTER JOIN packages ON (groups.package_id = packages._id)";
    147 
    148 
    149         public static final String ACTIVITIES = "activities";
    150 
    151         public static final String ACTIVITIES_JOIN_MIMETYPES = "activities "
    152                 + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id)";
    153 
    154         public static final String ACTIVITIES_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_CONTACTS =
    155                 "activities "
    156                 + "LEFT OUTER JOIN packages ON (activities.package_id = packages._id) "
    157                 + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id) "
    158                 + "LEFT OUTER JOIN raw_contacts ON (activities.author_contact_id = " +
    159                         "raw_contacts._id) "
    160                 + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)";
    161 
    162         public static final String NAME_LOOKUP_JOIN_RAW_CONTACTS = "name_lookup "
    163                 + "INNER JOIN raw_contacts ON (name_lookup.raw_contact_id = raw_contacts._id)";
    164     }
    165 
    166     public interface Views {
    167         public static final String DATA_ALL = "view_data";
    168         public static final String DATA_RESTRICTED = "view_data_restricted";
    169 
    170         public static final String RAW_CONTACTS_ALL = "view_raw_contacts";
    171         public static final String RAW_CONTACTS_RESTRICTED = "view_raw_contacts_restricted";
    172 
    173         public static final String CONTACTS_ALL = "view_contacts";
    174         public static final String CONTACTS_RESTRICTED = "view_contacts_restricted";
    175 
    176         public static final String GROUPS_ALL = "view_groups";
    177     }
    178 
    179     public interface Clauses {
    180         final String MIMETYPE_IS_GROUP_MEMBERSHIP = MimetypesColumns.CONCRETE_MIMETYPE + "='"
    181                 + GroupMembership.CONTENT_ITEM_TYPE + "'";
    182 
    183         final String BELONGS_TO_GROUP = DataColumns.CONCRETE_GROUP_ID + "="
    184                 + GroupsColumns.CONCRETE_ID;
    185 
    186         final String HAVING_NO_GROUPS = "COUNT(" + DataColumns.CONCRETE_GROUP_ID + ") == 0";
    187 
    188         final String GROUP_BY_ACCOUNT_CONTACT_ID = SettingsColumns.CONCRETE_ACCOUNT_NAME + ","
    189                 + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "," + RawContacts.CONTACT_ID;
    190 
    191         final String RAW_CONTACT_IS_LOCAL = RawContactsColumns.CONCRETE_ACCOUNT_NAME
    192                 + " IS NULL AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL";
    193 
    194         final String ZERO_GROUP_MEMBERSHIPS = "COUNT(" + GroupsColumns.CONCRETE_ID + ")=0";
    195 
    196         final String OUTER_RAW_CONTACTS = "outer_raw_contacts";
    197         final String OUTER_RAW_CONTACTS_ID = OUTER_RAW_CONTACTS + "." + RawContacts._ID;
    198 
    199         final String CONTACT_IS_VISIBLE =
    200                 "SELECT " +
    201                     "MAX((SELECT (CASE WHEN " +
    202                         "(CASE" +
    203                             " WHEN " + RAW_CONTACT_IS_LOCAL +
    204                             " THEN 1 " +
    205                             " WHEN " + ZERO_GROUP_MEMBERSHIPS +
    206                             " THEN " + Settings.UNGROUPED_VISIBLE +
    207                             " ELSE MAX(" + Groups.GROUP_VISIBLE + ")" +
    208                          "END)=1 THEN 1 ELSE 0 END)" +
    209                 " FROM " + Tables.RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS +
    210                 " WHERE " + RawContactsColumns.CONCRETE_ID + "=" + OUTER_RAW_CONTACTS_ID + "))" +
    211                 " FROM " + Tables.RAW_CONTACTS + " AS " + OUTER_RAW_CONTACTS +
    212                 " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
    213                 " GROUP BY " + RawContacts.CONTACT_ID;
    214 
    215         final String GROUP_HAS_ACCOUNT_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND "
    216                 + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?";
    217     }
    218 
    219     public interface ContactsColumns {
    220         /**
    221          * This flag is set for a contact if it has only one constituent raw contact and
    222          * it is restricted.
    223          */
    224         public static final String SINGLE_IS_RESTRICTED = "single_is_restricted";
    225 
    226         public static final String LAST_STATUS_UPDATE_ID = "status_update_id";
    227 
    228         public static final String CONCRETE_ID = Tables.CONTACTS + "." + BaseColumns._ID;
    229 
    230         public static final String CONCRETE_TIMES_CONTACTED = Tables.CONTACTS + "."
    231                 + Contacts.TIMES_CONTACTED;
    232         public static final String CONCRETE_LAST_TIME_CONTACTED = Tables.CONTACTS + "."
    233                 + Contacts.LAST_TIME_CONTACTED;
    234         public static final String CONCRETE_STARRED = Tables.CONTACTS + "." + Contacts.STARRED;
    235         public static final String CONCRETE_CUSTOM_RINGTONE = Tables.CONTACTS + "."
    236                 + Contacts.CUSTOM_RINGTONE;
    237         public static final String CONCRETE_SEND_TO_VOICEMAIL = Tables.CONTACTS + "."
    238                 + Contacts.SEND_TO_VOICEMAIL;
    239         public static final String CONCRETE_LOOKUP_KEY = Tables.CONTACTS + "."
    240                 + Contacts.LOOKUP_KEY;
    241     }
    242 
    243     public interface RawContactsColumns {
    244         public static final String CONCRETE_ID =
    245                 Tables.RAW_CONTACTS + "." + BaseColumns._ID;
    246         public static final String CONCRETE_ACCOUNT_NAME =
    247                 Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_NAME;
    248         public static final String CONCRETE_ACCOUNT_TYPE =
    249                 Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE;
    250         public static final String CONCRETE_SOURCE_ID =
    251                 Tables.RAW_CONTACTS + "." + RawContacts.SOURCE_ID;
    252         public static final String CONCRETE_VERSION =
    253                 Tables.RAW_CONTACTS + "." + RawContacts.VERSION;
    254         public static final String CONCRETE_DIRTY =
    255                 Tables.RAW_CONTACTS + "." + RawContacts.DIRTY;
    256         public static final String CONCRETE_DELETED =
    257                 Tables.RAW_CONTACTS + "." + RawContacts.DELETED;
    258         public static final String CONCRETE_SYNC1 =
    259                 Tables.RAW_CONTACTS + "." + RawContacts.SYNC1;
    260         public static final String CONCRETE_SYNC2 =
    261                 Tables.RAW_CONTACTS + "." + RawContacts.SYNC2;
    262         public static final String CONCRETE_SYNC3 =
    263                 Tables.RAW_CONTACTS + "." + RawContacts.SYNC3;
    264         public static final String CONCRETE_SYNC4 =
    265                 Tables.RAW_CONTACTS + "." + RawContacts.SYNC4;
    266         public static final String CONCRETE_STARRED =
    267                 Tables.RAW_CONTACTS + "." + RawContacts.STARRED;
    268         public static final String CONCRETE_IS_RESTRICTED =
    269                 Tables.RAW_CONTACTS + "." + RawContacts.IS_RESTRICTED;
    270 
    271         public static final String DISPLAY_NAME = RawContacts.DISPLAY_NAME_PRIMARY;
    272         public static final String DISPLAY_NAME_SOURCE = RawContacts.DISPLAY_NAME_SOURCE;
    273         public static final String AGGREGATION_NEEDED = "aggregation_needed";
    274         public static final String CONTACT_IN_VISIBLE_GROUP = "contact_in_visible_group";
    275 
    276         public static final String CONCRETE_DISPLAY_NAME =
    277                 Tables.RAW_CONTACTS + "." + DISPLAY_NAME;
    278         public static final String CONCRETE_CONTACT_ID =
    279                 Tables.RAW_CONTACTS + "." + RawContacts.CONTACT_ID;
    280         public static final String CONCRETE_NAME_VERIFIED =
    281                 Tables.RAW_CONTACTS + "." + RawContacts.NAME_VERIFIED;
    282     }
    283 
    284     public interface DataColumns {
    285         public static final String PACKAGE_ID = "package_id";
    286         public static final String MIMETYPE_ID = "mimetype_id";
    287 
    288         public static final String CONCRETE_ID = Tables.DATA + "." + BaseColumns._ID;
    289         public static final String CONCRETE_MIMETYPE_ID = Tables.DATA + "." + MIMETYPE_ID;
    290         public static final String CONCRETE_RAW_CONTACT_ID = Tables.DATA + "."
    291                 + Data.RAW_CONTACT_ID;
    292         public static final String CONCRETE_GROUP_ID = Tables.DATA + "."
    293                 + GroupMembership.GROUP_ROW_ID;
    294 
    295         public static final String CONCRETE_DATA1 = Tables.DATA + "." + Data.DATA1;
    296         public static final String CONCRETE_DATA2 = Tables.DATA + "." + Data.DATA2;
    297         public static final String CONCRETE_DATA3 = Tables.DATA + "." + Data.DATA3;
    298         public static final String CONCRETE_DATA4 = Tables.DATA + "." + Data.DATA4;
    299         public static final String CONCRETE_DATA5 = Tables.DATA + "." + Data.DATA5;
    300         public static final String CONCRETE_DATA6 = Tables.DATA + "." + Data.DATA6;
    301         public static final String CONCRETE_DATA7 = Tables.DATA + "." + Data.DATA7;
    302         public static final String CONCRETE_DATA8 = Tables.DATA + "." + Data.DATA8;
    303         public static final String CONCRETE_DATA9 = Tables.DATA + "." + Data.DATA9;
    304         public static final String CONCRETE_DATA10 = Tables.DATA + "." + Data.DATA10;
    305         public static final String CONCRETE_DATA11 = Tables.DATA + "." + Data.DATA11;
    306         public static final String CONCRETE_DATA12 = Tables.DATA + "." + Data.DATA12;
    307         public static final String CONCRETE_DATA13 = Tables.DATA + "." + Data.DATA13;
    308         public static final String CONCRETE_DATA14 = Tables.DATA + "." + Data.DATA14;
    309         public static final String CONCRETE_DATA15 = Tables.DATA + "." + Data.DATA15;
    310         public static final String CONCRETE_IS_PRIMARY = Tables.DATA + "." + Data.IS_PRIMARY;
    311         public static final String CONCRETE_PACKAGE_ID = Tables.DATA + "." + PACKAGE_ID;
    312     }
    313 
    314     // Used only for legacy API support
    315     public interface ExtensionsColumns {
    316         public static final String NAME = Data.DATA1;
    317         public static final String VALUE = Data.DATA2;
    318     }
    319 
    320     public interface GroupMembershipColumns {
    321         public static final String RAW_CONTACT_ID = Data.RAW_CONTACT_ID;
    322         public static final String GROUP_ROW_ID = GroupMembership.GROUP_ROW_ID;
    323     }
    324 
    325     public interface PhoneColumns {
    326         public static final String NORMALIZED_NUMBER = Data.DATA4;
    327         public static final String CONCRETE_NORMALIZED_NUMBER = DataColumns.CONCRETE_DATA4;
    328     }
    329 
    330     public interface GroupsColumns {
    331         public static final String PACKAGE_ID = "package_id";
    332 
    333         public static final String CONCRETE_ID = Tables.GROUPS + "." + BaseColumns._ID;
    334         public static final String CONCRETE_SOURCE_ID = Tables.GROUPS + "." + Groups.SOURCE_ID;
    335         public static final String CONCRETE_ACCOUNT_NAME = Tables.GROUPS + "." + Groups.ACCOUNT_NAME;
    336         public static final String CONCRETE_ACCOUNT_TYPE = Tables.GROUPS + "." + Groups.ACCOUNT_TYPE;
    337     }
    338 
    339     public interface ActivitiesColumns {
    340         public static final String PACKAGE_ID = "package_id";
    341         public static final String MIMETYPE_ID = "mimetype_id";
    342     }
    343 
    344     public interface PhoneLookupColumns {
    345         public static final String _ID = BaseColumns._ID;
    346         public static final String DATA_ID = "data_id";
    347         public static final String RAW_CONTACT_ID = "raw_contact_id";
    348         public static final String NORMALIZED_NUMBER = "normalized_number";
    349         public static final String MIN_MATCH = "min_match";
    350     }
    351 
    352     public interface NameLookupColumns {
    353         public static final String RAW_CONTACT_ID = "raw_contact_id";
    354         public static final String DATA_ID = "data_id";
    355         public static final String NORMALIZED_NAME = "normalized_name";
    356         public static final String NAME_TYPE = "name_type";
    357     }
    358 
    359     public final static class NameLookupType {
    360         public static final int NAME_EXACT = 0;
    361         public static final int NAME_VARIANT = 1;
    362         public static final int NAME_COLLATION_KEY = 2;
    363         public static final int NICKNAME = 3;
    364         public static final int EMAIL_BASED_NICKNAME = 4;
    365         public static final int ORGANIZATION = 5;
    366         public static final int NAME_SHORTHAND = 6;
    367         public static final int NAME_CONSONANTS = 7;
    368 
    369         // This is the highest name lookup type code plus one
    370         public static final int TYPE_COUNT = 8;
    371 
    372         public static boolean isBasedOnStructuredName(int nameLookupType) {
    373             return nameLookupType == NameLookupType.NAME_EXACT
    374                     || nameLookupType == NameLookupType.NAME_VARIANT
    375                     || nameLookupType == NameLookupType.NAME_COLLATION_KEY;
    376         }
    377     }
    378 
    379     public interface PackagesColumns {
    380         public static final String _ID = BaseColumns._ID;
    381         public static final String PACKAGE = "package";
    382 
    383         public static final String CONCRETE_ID = Tables.PACKAGES + "." + _ID;
    384     }
    385 
    386     public interface MimetypesColumns {
    387         public static final String _ID = BaseColumns._ID;
    388         public static final String MIMETYPE = "mimetype";
    389 
    390         public static final String CONCRETE_ID = Tables.MIMETYPES + "." + BaseColumns._ID;
    391         public static final String CONCRETE_MIMETYPE = Tables.MIMETYPES + "." + MIMETYPE;
    392     }
    393 
    394     public interface AggregationExceptionColumns {
    395         public static final String _ID = BaseColumns._ID;
    396     }
    397 
    398     public interface NicknameLookupColumns {
    399         public static final String NAME = "name";
    400         public static final String CLUSTER = "cluster";
    401     }
    402 
    403     public interface SettingsColumns {
    404         public static final String CONCRETE_ACCOUNT_NAME = Tables.SETTINGS + "."
    405                 + Settings.ACCOUNT_NAME;
    406         public static final String CONCRETE_ACCOUNT_TYPE = Tables.SETTINGS + "."
    407                 + Settings.ACCOUNT_TYPE;
    408     }
    409 
    410     public interface PresenceColumns {
    411         String RAW_CONTACT_ID = "presence_raw_contact_id";
    412         String CONTACT_ID = "presence_contact_id";
    413     }
    414 
    415     public interface AggregatedPresenceColumns {
    416         String CONTACT_ID = "presence_contact_id";
    417 
    418         String CONCRETE_CONTACT_ID = Tables.AGGREGATED_PRESENCE + "." + CONTACT_ID;
    419     }
    420 
    421     public interface StatusUpdatesColumns {
    422         String DATA_ID = "status_update_data_id";
    423 
    424         String CONCRETE_DATA_ID = Tables.STATUS_UPDATES + "." + DATA_ID;
    425 
    426         String CONCRETE_PRESENCE = Tables.STATUS_UPDATES + "." + StatusUpdates.PRESENCE;
    427         String CONCRETE_STATUS = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS;
    428         String CONCRETE_STATUS_TIMESTAMP = Tables.STATUS_UPDATES + "."
    429                 + StatusUpdates.STATUS_TIMESTAMP;
    430         String CONCRETE_STATUS_RES_PACKAGE = Tables.STATUS_UPDATES + "."
    431                 + StatusUpdates.STATUS_RES_PACKAGE;
    432         String CONCRETE_STATUS_LABEL = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_LABEL;
    433         String CONCRETE_STATUS_ICON = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_ICON;
    434     }
    435 
    436     public interface ContactsStatusUpdatesColumns {
    437         String ALIAS = "contacts_" + Tables.STATUS_UPDATES;
    438 
    439         String CONCRETE_DATA_ID = ALIAS + "." + StatusUpdatesColumns.DATA_ID;
    440 
    441         String CONCRETE_PRESENCE = ALIAS + "." + StatusUpdates.PRESENCE;
    442         String CONCRETE_STATUS = ALIAS + "." + StatusUpdates.STATUS;
    443         String CONCRETE_STATUS_TIMESTAMP = ALIAS + "." + StatusUpdates.STATUS_TIMESTAMP;
    444         String CONCRETE_STATUS_RES_PACKAGE = ALIAS + "." + StatusUpdates.STATUS_RES_PACKAGE;
    445         String CONCRETE_STATUS_LABEL = ALIAS + "." + StatusUpdates.STATUS_LABEL;
    446         String CONCRETE_STATUS_ICON = ALIAS + "." + StatusUpdates.STATUS_ICON;
    447     }
    448 
    449     public interface PropertiesColumns {
    450         String PROPERTY_KEY = "property_key";
    451         String PROPERTY_VALUE = "property_value";
    452     }
    453 
    454     /** In-memory cache of previously found MIME-type mappings */
    455     private final HashMap<String, Long> mMimetypeCache = new HashMap<String, Long>();
    456     /** In-memory cache of previously found package name mappings */
    457     private final HashMap<String, Long> mPackageCache = new HashMap<String, Long>();
    458 
    459 
    460     /** Compiled statements for querying and inserting mappings */
    461     private SQLiteStatement mMimetypeQuery;
    462     private SQLiteStatement mPackageQuery;
    463     private SQLiteStatement mContactIdQuery;
    464     private SQLiteStatement mAggregationModeQuery;
    465     private SQLiteStatement mMimetypeInsert;
    466     private SQLiteStatement mPackageInsert;
    467     private SQLiteStatement mDataMimetypeQuery;
    468     private SQLiteStatement mActivitiesMimetypeQuery;
    469 
    470     private final Context mContext;
    471     private final SyncStateContentProviderHelper mSyncState;
    472 
    473 
    474     /** Compiled statements for updating {@link Contacts#IN_VISIBLE_GROUP}. */
    475     private SQLiteStatement mVisibleSpecificUpdate;
    476     private SQLiteStatement mVisibleUpdateRawContacts;
    477     private SQLiteStatement mVisibleSpecificUpdateRawContacts;
    478 
    479     private boolean mReopenDatabase = false;
    480 
    481     private static ContactsDatabaseHelper sSingleton = null;
    482 
    483     private boolean mUseStrictPhoneNumberComparison;
    484 
    485     /**
    486      * List of package names with access to {@link RawContacts#IS_RESTRICTED} data.
    487      */
    488     private String[] mUnrestrictedPackages;
    489 
    490     public static synchronized ContactsDatabaseHelper getInstance(Context context) {
    491         if (sSingleton == null) {
    492             sSingleton = new ContactsDatabaseHelper(context);
    493         }
    494         return sSingleton;
    495     }
    496 
    497     /**
    498      * Private constructor, callers except unit tests should obtain an instance through
    499      * {@link #getInstance(android.content.Context)} instead.
    500      */
    501     ContactsDatabaseHelper(Context context) {
    502         super(context, DATABASE_NAME, null, DATABASE_VERSION);
    503         if (false) Log.i(TAG, "Creating OpenHelper");
    504         Resources resources = context.getResources();
    505 
    506         mContext = context;
    507         mSyncState = new SyncStateContentProviderHelper();
    508         mUseStrictPhoneNumberComparison =
    509                 resources.getBoolean(
    510                         com.android.internal.R.bool.config_use_strict_phone_number_comparation);
    511         int resourceId = resources.getIdentifier("unrestricted_packages", "array",
    512                 context.getPackageName());
    513         if (resourceId != 0) {
    514             mUnrestrictedPackages = resources.getStringArray(resourceId);
    515         } else {
    516             mUnrestrictedPackages = new String[0];
    517         }
    518     }
    519 
    520     @Override
    521     public void onOpen(SQLiteDatabase db) {
    522         mSyncState.onDatabaseOpened(db);
    523 
    524         // Create compiled statements for package and mimetype lookups
    525         mMimetypeQuery = db.compileStatement("SELECT " + MimetypesColumns._ID + " FROM "
    526                 + Tables.MIMETYPES + " WHERE " + MimetypesColumns.MIMETYPE + "=?");
    527         mPackageQuery = db.compileStatement("SELECT " + PackagesColumns._ID + " FROM "
    528                 + Tables.PACKAGES + " WHERE " + PackagesColumns.PACKAGE + "=?");
    529         mContactIdQuery = db.compileStatement("SELECT " + RawContacts.CONTACT_ID + " FROM "
    530                 + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=?");
    531         mAggregationModeQuery = db.compileStatement("SELECT " + RawContacts.AGGREGATION_MODE
    532                 + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=?");
    533         mMimetypeInsert = db.compileStatement("INSERT INTO " + Tables.MIMETYPES + "("
    534                 + MimetypesColumns.MIMETYPE + ") VALUES (?)");
    535         mPackageInsert = db.compileStatement("INSERT INTO " + Tables.PACKAGES + "("
    536                 + PackagesColumns.PACKAGE + ") VALUES (?)");
    537 
    538         mDataMimetypeQuery = db.compileStatement("SELECT " + MimetypesColumns.MIMETYPE + " FROM "
    539                 + Tables.DATA_JOIN_MIMETYPES + " WHERE " + Tables.DATA + "." + Data._ID + "=?");
    540         mActivitiesMimetypeQuery = db.compileStatement("SELECT " + MimetypesColumns.MIMETYPE
    541                 + " FROM " + Tables.ACTIVITIES_JOIN_MIMETYPES + " WHERE " + Tables.ACTIVITIES + "."
    542                 + Activities._ID + "=?");
    543 
    544         // Change visibility of a specific contact
    545         mVisibleSpecificUpdate = db.compileStatement(
    546                 "UPDATE " + Tables.CONTACTS +
    547                 " SET " + Contacts.IN_VISIBLE_GROUP + "=(" + Clauses.CONTACT_IS_VISIBLE + ")" +
    548                 " WHERE " + ContactsColumns.CONCRETE_ID + "=?");
    549 
    550         // Return visibility of the aggregate contact joined with the raw contact
    551         String contactVisibility =
    552                 "SELECT " + Contacts.IN_VISIBLE_GROUP +
    553                 " FROM " + Tables.CONTACTS +
    554                 " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID;
    555 
    556         // Set visibility of raw contacts to the visibility of corresponding aggregate contacts
    557         mVisibleUpdateRawContacts = db.compileStatement(
    558                 "UPDATE " + Tables.RAW_CONTACTS +
    559                 " SET " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "=(CASE WHEN ("
    560                         + contactVisibility + ")=1 THEN 1 ELSE 0 END)" +
    561                 " WHERE " + RawContacts.DELETED + "=0" +
    562                 " AND " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "!=("
    563                         + contactVisibility + ")=1");
    564 
    565         // Set visibility of a raw contact to the visibility of corresponding aggregate contact
    566         mVisibleSpecificUpdateRawContacts = db.compileStatement(
    567                 "UPDATE " + Tables.RAW_CONTACTS +
    568                 " SET " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "=("
    569                         + contactVisibility + ")" +
    570                 " WHERE " + RawContacts.DELETED + "=0 AND " + RawContacts.CONTACT_ID + "=?");
    571 
    572         db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";");
    573         db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_PRESENCE + "." + Tables.PRESENCE + " ("+
    574                 StatusUpdates.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
    575                 StatusUpdates.PROTOCOL + " INTEGER NOT NULL," +
    576                 StatusUpdates.CUSTOM_PROTOCOL + " TEXT," +
    577                 StatusUpdates.IM_HANDLE + " TEXT," +
    578                 StatusUpdates.IM_ACCOUNT + " TEXT," +
    579                 PresenceColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
    580                 PresenceColumns.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
    581                 StatusUpdates.PRESENCE + " INTEGER," +
    582                 "UNIQUE(" + StatusUpdates.PROTOCOL + ", " + StatusUpdates.CUSTOM_PROTOCOL
    583                     + ", " + StatusUpdates.IM_HANDLE + ", " + StatusUpdates.IM_ACCOUNT + ")" +
    584         ");");
    585 
    586         db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex" + " ON "
    587                 + Tables.PRESENCE + " (" + PresenceColumns.RAW_CONTACT_ID + ");");
    588 
    589         db.execSQL("CREATE TABLE IF NOT EXISTS "
    590                         + DATABASE_PRESENCE + "." + Tables.AGGREGATED_PRESENCE + " ("+
    591                 AggregatedPresenceColumns.CONTACT_ID
    592                         + " INTEGER PRIMARY KEY REFERENCES contacts(_id)," +
    593                 StatusUpdates.PRESENCE_STATUS + " INTEGER" +
    594         ");");
    595 
    596 
    597         db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_deleted"
    598                 + " BEFORE DELETE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
    599                 + " BEGIN "
    600                 + "   DELETE FROM " + Tables.AGGREGATED_PRESENCE
    601                 + "     WHERE " + AggregatedPresenceColumns.CONTACT_ID + " = " +
    602                         "(SELECT " + PresenceColumns.CONTACT_ID +
    603                         " FROM " + Tables.PRESENCE +
    604                         " WHERE " + PresenceColumns.RAW_CONTACT_ID
    605                                 + "=OLD." + PresenceColumns.RAW_CONTACT_ID +
    606                         " AND NOT EXISTS" +
    607                                 "(SELECT " + PresenceColumns.RAW_CONTACT_ID +
    608                                 " FROM " + Tables.PRESENCE +
    609                                 " WHERE " + PresenceColumns.CONTACT_ID
    610                                         + "=OLD." + PresenceColumns.CONTACT_ID +
    611                                 " AND " + PresenceColumns.RAW_CONTACT_ID
    612                                         + "!=OLD." + PresenceColumns.RAW_CONTACT_ID + "));"
    613                 + " END");
    614 
    615         String replaceAggregatePresenceSql =
    616             "INSERT OR REPLACE INTO " + Tables.AGGREGATED_PRESENCE + "("
    617                     + AggregatedPresenceColumns.CONTACT_ID + ", "
    618                     + StatusUpdates.PRESENCE_STATUS + ")" +
    619             " SELECT " + PresenceColumns.CONTACT_ID + ","
    620                         + "MAX(" + StatusUpdates.PRESENCE_STATUS + ")" +
    621                     " FROM " + Tables.PRESENCE +
    622                     " WHERE " + PresenceColumns.CONTACT_ID
    623                         + "=NEW." + PresenceColumns.CONTACT_ID + ";";
    624 
    625         db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_inserted"
    626                 + " AFTER INSERT ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
    627                 + " BEGIN "
    628                 + replaceAggregatePresenceSql
    629                 + " END");
    630 
    631         db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_updated"
    632                 + " AFTER UPDATE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE
    633                 + " BEGIN "
    634                 + replaceAggregatePresenceSql
    635                 + " END");
    636     }
    637 
    638     @Override
    639     public void onCreate(SQLiteDatabase db) {
    640         Log.i(TAG, "Bootstrapping database");
    641 
    642         mSyncState.createDatabase(db);
    643 
    644         // One row per group of contacts corresponding to the same person
    645         db.execSQL("CREATE TABLE " + Tables.CONTACTS + " (" +
    646                 BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    647                 Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
    648                 Contacts.PHOTO_ID + " INTEGER REFERENCES data(_id)," +
    649                 Contacts.CUSTOM_RINGTONE + " TEXT," +
    650                 Contacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
    651                 Contacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
    652                 Contacts.LAST_TIME_CONTACTED + " INTEGER," +
    653                 Contacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
    654                 Contacts.IN_VISIBLE_GROUP + " INTEGER NOT NULL DEFAULT 1," +
    655                 Contacts.HAS_PHONE_NUMBER + " INTEGER NOT NULL DEFAULT 0," +
    656                 Contacts.LOOKUP_KEY + " TEXT," +
    657                 ContactsColumns.LAST_STATUS_UPDATE_ID + " INTEGER REFERENCES data(_id)," +
    658                 ContactsColumns.SINGLE_IS_RESTRICTED + " INTEGER NOT NULL DEFAULT 0" +
    659         ");");
    660 
    661         db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
    662                 Contacts.IN_VISIBLE_GROUP +
    663         ");");
    664 
    665         db.execSQL("CREATE INDEX contacts_has_phone_index ON " + Tables.CONTACTS + " (" +
    666                 Contacts.HAS_PHONE_NUMBER +
    667         ");");
    668 
    669         db.execSQL("CREATE INDEX contacts_restricted_index ON " + Tables.CONTACTS + " (" +
    670                 ContactsColumns.SINGLE_IS_RESTRICTED +
    671         ");");
    672 
    673         db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
    674                 Contacts.NAME_RAW_CONTACT_ID +
    675         ");");
    676 
    677         // Contacts table
    678         db.execSQL("CREATE TABLE " + Tables.RAW_CONTACTS + " (" +
    679                 RawContacts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    680                 RawContacts.IS_RESTRICTED + " INTEGER DEFAULT 0," +
    681                 RawContacts.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
    682                 RawContacts.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
    683                 RawContacts.SOURCE_ID + " TEXT," +
    684                 RawContacts.VERSION + " INTEGER NOT NULL DEFAULT 1," +
    685                 RawContacts.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
    686                 RawContacts.DELETED + " INTEGER NOT NULL DEFAULT 0," +
    687                 RawContacts.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," +
    688                 RawContacts.AGGREGATION_MODE + " INTEGER NOT NULL DEFAULT " +
    689                         RawContacts.AGGREGATION_MODE_DEFAULT + "," +
    690                 RawContactsColumns.AGGREGATION_NEEDED + " INTEGER NOT NULL DEFAULT 1," +
    691                 RawContacts.CUSTOM_RINGTONE + " TEXT," +
    692                 RawContacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," +
    693                 RawContacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," +
    694                 RawContacts.LAST_TIME_CONTACTED + " INTEGER," +
    695                 RawContacts.STARRED + " INTEGER NOT NULL DEFAULT 0," +
    696                 RawContacts.DISPLAY_NAME_PRIMARY + " TEXT," +
    697                 RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT," +
    698                 RawContacts.DISPLAY_NAME_SOURCE + " INTEGER NOT NULL DEFAULT " +
    699                         DisplayNameSources.UNDEFINED + "," +
    700                 RawContacts.PHONETIC_NAME + " TEXT," +
    701                 RawContacts.PHONETIC_NAME_STYLE + " TEXT," +
    702                 RawContacts.SORT_KEY_PRIMARY + " TEXT COLLATE " +
    703                         ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," +
    704                 RawContacts.SORT_KEY_ALTERNATIVE + " TEXT COLLATE " +
    705                         ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," +
    706                 RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0," +
    707                 RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + " INTEGER NOT NULL DEFAULT 0," +
    708                 RawContacts.SYNC1 + " TEXT, " +
    709                 RawContacts.SYNC2 + " TEXT, " +
    710                 RawContacts.SYNC3 + " TEXT, " +
    711                 RawContacts.SYNC4 + " TEXT " +
    712         ");");
    713 
    714         db.execSQL("CREATE INDEX raw_contacts_contact_id_index ON " + Tables.RAW_CONTACTS + " (" +
    715                 RawContacts.CONTACT_ID +
    716         ");");
    717 
    718         db.execSQL("CREATE INDEX raw_contacts_source_id_index ON " + Tables.RAW_CONTACTS + " (" +
    719                 RawContacts.SOURCE_ID + ", " +
    720                 RawContacts.ACCOUNT_TYPE + ", " +
    721                 RawContacts.ACCOUNT_NAME +
    722         ");");
    723 
    724         // TODO readd the index and investigate a controlled use of it
    725 //        db.execSQL("CREATE INDEX raw_contacts_agg_index ON " + Tables.RAW_CONTACTS + " (" +
    726 //                RawContactsColumns.AGGREGATION_NEEDED +
    727 //        ");");
    728 
    729         // Package name mapping table
    730         db.execSQL("CREATE TABLE " + Tables.PACKAGES + " (" +
    731                 PackagesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    732                 PackagesColumns.PACKAGE + " TEXT NOT NULL" +
    733         ");");
    734 
    735         // Mimetype mapping table
    736         db.execSQL("CREATE TABLE " + Tables.MIMETYPES + " (" +
    737                 MimetypesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    738                 MimetypesColumns.MIMETYPE + " TEXT NOT NULL" +
    739         ");");
    740 
    741         // Mimetype table requires an index on mime type
    742         db.execSQL("CREATE UNIQUE INDEX mime_type ON " + Tables.MIMETYPES + " (" +
    743                 MimetypesColumns.MIMETYPE +
    744         ");");
    745 
    746         // Public generic data table
    747         db.execSQL("CREATE TABLE " + Tables.DATA + " (" +
    748                 Data._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    749                 DataColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
    750                 DataColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
    751                 Data.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
    752                 Data.IS_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
    753                 Data.IS_SUPER_PRIMARY + " INTEGER NOT NULL DEFAULT 0," +
    754                 Data.DATA_VERSION + " INTEGER NOT NULL DEFAULT 0," +
    755                 Data.DATA1 + " TEXT," +
    756                 Data.DATA2 + " TEXT," +
    757                 Data.DATA3 + " TEXT," +
    758                 Data.DATA4 + " TEXT," +
    759                 Data.DATA5 + " TEXT," +
    760                 Data.DATA6 + " TEXT," +
    761                 Data.DATA7 + " TEXT," +
    762                 Data.DATA8 + " TEXT," +
    763                 Data.DATA9 + " TEXT," +
    764                 Data.DATA10 + " TEXT," +
    765                 Data.DATA11 + " TEXT," +
    766                 Data.DATA12 + " TEXT," +
    767                 Data.DATA13 + " TEXT," +
    768                 Data.DATA14 + " TEXT," +
    769                 Data.DATA15 + " TEXT," +
    770                 Data.SYNC1 + " TEXT, " +
    771                 Data.SYNC2 + " TEXT, " +
    772                 Data.SYNC3 + " TEXT, " +
    773                 Data.SYNC4 + " TEXT " +
    774         ");");
    775 
    776         db.execSQL("CREATE INDEX data_raw_contact_id ON " + Tables.DATA + " (" +
    777                 Data.RAW_CONTACT_ID +
    778         ");");
    779 
    780         /**
    781          * For email lookup and similar queries.
    782          */
    783         db.execSQL("CREATE INDEX data_mimetype_data1_index ON " + Tables.DATA + " (" +
    784                 DataColumns.MIMETYPE_ID + "," +
    785                 Data.DATA1 +
    786         ");");
    787 
    788         // Private phone numbers table used for lookup
    789         db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" +
    790                 PhoneLookupColumns.DATA_ID
    791                         + " INTEGER PRIMARY KEY REFERENCES data(_id) NOT NULL," +
    792                 PhoneLookupColumns.RAW_CONTACT_ID
    793                         + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
    794                 PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," +
    795                 PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" +
    796         ");");
    797 
    798         db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" +
    799                 PhoneLookupColumns.NORMALIZED_NUMBER + "," +
    800                 PhoneLookupColumns.RAW_CONTACT_ID + "," +
    801                 PhoneLookupColumns.DATA_ID +
    802         ");");
    803 
    804         db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
    805                 PhoneLookupColumns.MIN_MATCH + "," +
    806                 PhoneLookupColumns.RAW_CONTACT_ID + "," +
    807                 PhoneLookupColumns.DATA_ID +
    808         ");");
    809 
    810         // Private name/nickname table used for lookup
    811         db.execSQL("CREATE TABLE " + Tables.NAME_LOOKUP + " (" +
    812                 NameLookupColumns.DATA_ID
    813                         + " INTEGER REFERENCES data(_id) NOT NULL," +
    814                 NameLookupColumns.RAW_CONTACT_ID
    815                         + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," +
    816                 NameLookupColumns.NORMALIZED_NAME + " TEXT NOT NULL," +
    817                 NameLookupColumns.NAME_TYPE + " INTEGER NOT NULL," +
    818                 "PRIMARY KEY ("
    819                         + NameLookupColumns.DATA_ID + ", "
    820                         + NameLookupColumns.NORMALIZED_NAME + ", "
    821                         + NameLookupColumns.NAME_TYPE + ")" +
    822         ");");
    823 
    824         db.execSQL("CREATE INDEX name_lookup_raw_contact_id_index ON " + Tables.NAME_LOOKUP + " (" +
    825                 NameLookupColumns.RAW_CONTACT_ID +
    826         ");");
    827 
    828         db.execSQL("CREATE TABLE " + Tables.NICKNAME_LOOKUP + " (" +
    829                 NicknameLookupColumns.NAME + " TEXT," +
    830                 NicknameLookupColumns.CLUSTER + " TEXT" +
    831         ");");
    832 
    833         db.execSQL("CREATE UNIQUE INDEX nickname_lookup_index ON " + Tables.NICKNAME_LOOKUP + " (" +
    834                 NicknameLookupColumns.NAME + ", " +
    835                 NicknameLookupColumns.CLUSTER +
    836         ");");
    837 
    838         // Groups table
    839         db.execSQL("CREATE TABLE " + Tables.GROUPS + " (" +
    840                 Groups._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    841                 GroupsColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
    842                 Groups.ACCOUNT_NAME + " STRING DEFAULT NULL, " +
    843                 Groups.ACCOUNT_TYPE + " STRING DEFAULT NULL, " +
    844                 Groups.SOURCE_ID + " TEXT," +
    845                 Groups.VERSION + " INTEGER NOT NULL DEFAULT 1," +
    846                 Groups.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
    847                 Groups.TITLE + " TEXT," +
    848                 Groups.TITLE_RES + " INTEGER," +
    849                 Groups.NOTES + " TEXT," +
    850                 Groups.SYSTEM_ID + " TEXT," +
    851                 Groups.DELETED + " INTEGER NOT NULL DEFAULT 0," +
    852                 Groups.GROUP_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
    853                 Groups.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1," +
    854                 Groups.SYNC1 + " TEXT, " +
    855                 Groups.SYNC2 + " TEXT, " +
    856                 Groups.SYNC3 + " TEXT, " +
    857                 Groups.SYNC4 + " TEXT " +
    858         ");");
    859 
    860         db.execSQL("CREATE INDEX groups_source_id_index ON " + Tables.GROUPS + " (" +
    861                 Groups.SOURCE_ID + ", " +
    862                 Groups.ACCOUNT_TYPE + ", " +
    863                 Groups.ACCOUNT_NAME +
    864         ");");
    865 
    866         db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.AGGREGATION_EXCEPTIONS + " (" +
    867                 AggregationExceptionColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    868                 AggregationExceptions.TYPE + " INTEGER NOT NULL, " +
    869                 AggregationExceptions.RAW_CONTACT_ID1
    870                         + " INTEGER REFERENCES raw_contacts(_id), " +
    871                 AggregationExceptions.RAW_CONTACT_ID2
    872                         + " INTEGER REFERENCES raw_contacts(_id)" +
    873         ");");
    874 
    875         db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index1 ON " +
    876                 Tables.AGGREGATION_EXCEPTIONS + " (" +
    877                 AggregationExceptions.RAW_CONTACT_ID1 + ", " +
    878                 AggregationExceptions.RAW_CONTACT_ID2 +
    879         ");");
    880 
    881         db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index2 ON " +
    882                 Tables.AGGREGATION_EXCEPTIONS + " (" +
    883                 AggregationExceptions.RAW_CONTACT_ID2 + ", " +
    884                 AggregationExceptions.RAW_CONTACT_ID1 +
    885         ");");
    886 
    887         db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.SETTINGS + " (" +
    888                 Settings.ACCOUNT_NAME + " STRING NOT NULL," +
    889                 Settings.ACCOUNT_TYPE + " STRING NOT NULL," +
    890                 Settings.UNGROUPED_VISIBLE + " INTEGER NOT NULL DEFAULT 0," +
    891                 Settings.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1, " +
    892                 "PRIMARY KEY (" + Settings.ACCOUNT_NAME + ", " +
    893                     Settings.ACCOUNT_TYPE + ") ON CONFLICT REPLACE" +
    894         ");");
    895 
    896         // The table for recent calls is here so we can do table joins
    897         // on people, phones, and calls all in one place.
    898         db.execSQL("CREATE TABLE " + Tables.CALLS + " (" +
    899                 Calls._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    900                 Calls.NUMBER + " TEXT," +
    901                 Calls.DATE + " INTEGER," +
    902                 Calls.DURATION + " INTEGER," +
    903                 Calls.TYPE + " INTEGER," +
    904                 Calls.NEW + " INTEGER," +
    905                 Calls.CACHED_NAME + " TEXT," +
    906                 Calls.CACHED_NUMBER_TYPE + " INTEGER," +
    907                 Calls.CACHED_NUMBER_LABEL + " TEXT" +
    908         ");");
    909 
    910         // Activities table
    911         db.execSQL("CREATE TABLE " + Tables.ACTIVITIES + " (" +
    912                 Activities._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
    913                 ActivitiesColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," +
    914                 ActivitiesColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," +
    915                 Activities.RAW_ID + " TEXT," +
    916                 Activities.IN_REPLY_TO + " TEXT," +
    917                 Activities.AUTHOR_CONTACT_ID +  " INTEGER REFERENCES raw_contacts(_id)," +
    918                 Activities.TARGET_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," +
    919                 Activities.PUBLISHED + " INTEGER NOT NULL," +
    920                 Activities.THREAD_PUBLISHED + " INTEGER NOT NULL," +
    921                 Activities.TITLE + " TEXT NOT NULL," +
    922                 Activities.SUMMARY + " TEXT," +
    923                 Activities.LINK + " TEXT, " +
    924                 Activities.THUMBNAIL + " BLOB" +
    925         ");");
    926 
    927         db.execSQL("CREATE TABLE " + Tables.STATUS_UPDATES + " (" +
    928                 StatusUpdatesColumns.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," +
    929                 StatusUpdates.STATUS + " TEXT," +
    930                 StatusUpdates.STATUS_TIMESTAMP + " INTEGER," +
    931                 StatusUpdates.STATUS_RES_PACKAGE + " TEXT, " +
    932                 StatusUpdates.STATUS_LABEL + " INTEGER, " +
    933                 StatusUpdates.STATUS_ICON + " INTEGER" +
    934         ");");
    935 
    936         db.execSQL("CREATE TABLE " + Tables.PROPERTIES + " (" +
    937                 PropertiesColumns.PROPERTY_KEY + " TEXT PRIMARY KEY, " +
    938                 PropertiesColumns.PROPERTY_VALUE + " TEXT " +
    939         ");");
    940 
    941         db.execSQL("CREATE TABLE " + Tables.ACCOUNTS + " (" +
    942                 RawContacts.ACCOUNT_NAME + " TEXT, " +
    943                 RawContacts.ACCOUNT_TYPE + " TEXT " +
    944         ");");
    945 
    946         // Allow contacts without any account to be created for now.  Achieve that
    947         // by inserting a fake account with both type and name as NULL.
    948         // This "account" should be eliminated as soon as the first real writable account
    949         // is added to the phone.
    950         db.execSQL("INSERT INTO accounts VALUES(NULL, NULL)");
    951 
    952         createContactsViews(db);
    953         createGroupsView(db);
    954         createContactEntitiesView(db);
    955         createContactsTriggers(db);
    956         createContactsIndexes(db);
    957 
    958         loadNicknameLookupTable(db);
    959 
    960         // Add the legacy API support views, etc
    961         LegacyApiSupport.createDatabase(db);
    962 
    963         // This will create a sqlite_stat1 table that is used for query optimization
    964         db.execSQL("ANALYZE;");
    965 
    966         updateSqliteStats(db);
    967 
    968         // We need to close and reopen the database connection so that the stats are
    969         // taken into account. Make a note of it and do the actual reopening in the
    970         // getWritableDatabase method.
    971         mReopenDatabase = true;
    972 
    973         ContentResolver.requestSync(null /* all accounts */,
    974                 ContactsContract.AUTHORITY, new Bundle());
    975     }
    976 
    977     private static void createContactsTriggers(SQLiteDatabase db) {
    978 
    979         /*
    980          * Automatically delete Data rows when a raw contact is deleted.
    981          */
    982         db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;");
    983         db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted "
    984                 + "   BEFORE DELETE ON " + Tables.RAW_CONTACTS
    985                 + " BEGIN "
    986                 + "   DELETE FROM " + Tables.DATA
    987                 + "     WHERE " + Data.RAW_CONTACT_ID
    988                                 + "=OLD." + RawContacts._ID + ";"
    989                 + "   DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS
    990                 + "     WHERE " + AggregationExceptions.RAW_CONTACT_ID1
    991                                 + "=OLD." + RawContacts._ID
    992                 + "        OR " + AggregationExceptions.RAW_CONTACT_ID2
    993                                 + "=OLD." + RawContacts._ID + ";"
    994                 + "   DELETE FROM " + Tables.CONTACTS
    995                 + "     WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID
    996                 + "       AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS
    997                 + "            WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID
    998                 + "           )=1;"
    999                 + " END");
   1000 
   1001 
   1002         db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;");
   1003         db.execSQL("DROP TRIGGER IF EXISTS raw_contacts_times_contacted;");
   1004 
   1005         /*
   1006          * Triggers that update {@link RawContacts#VERSION} when the contact is
   1007          * marked for deletion or any time a data row is inserted, updated or
   1008          * deleted.
   1009          */
   1010         db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;");
   1011         db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted "
   1012                 + "   AFTER UPDATE ON " + Tables.RAW_CONTACTS
   1013                 + " BEGIN "
   1014                 + "   UPDATE " + Tables.RAW_CONTACTS
   1015                 + "     SET "
   1016                 +         RawContacts.VERSION + "=OLD." + RawContacts.VERSION + "+1 "
   1017                 + "     WHERE " + RawContacts._ID + "=OLD." + RawContacts._ID
   1018                 + "       AND NEW." + RawContacts.DELETED + "!= OLD." + RawContacts.DELETED + ";"
   1019                 + " END");
   1020 
   1021         db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_updated;");
   1022         db.execSQL("CREATE TRIGGER " + Tables.DATA + "_updated AFTER UPDATE ON " + Tables.DATA
   1023                 + " BEGIN "
   1024                 + "   UPDATE " + Tables.DATA
   1025                 + "     SET " + Data.DATA_VERSION + "=OLD." + Data.DATA_VERSION + "+1 "
   1026                 + "     WHERE " + Data._ID + "=OLD." + Data._ID + ";"
   1027                 + "   UPDATE " + Tables.RAW_CONTACTS
   1028                 + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
   1029                 + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
   1030                 + " END");
   1031 
   1032         db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_deleted;");
   1033         db.execSQL("CREATE TRIGGER " + Tables.DATA + "_deleted BEFORE DELETE ON " + Tables.DATA
   1034                 + " BEGIN "
   1035                 + "   UPDATE " + Tables.RAW_CONTACTS
   1036                 + "     SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 "
   1037                 + "     WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";"
   1038                 + "   DELETE FROM " + Tables.PHONE_LOOKUP
   1039                 + "     WHERE " + PhoneLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
   1040                 + "   DELETE FROM " + Tables.STATUS_UPDATES
   1041                 + "     WHERE " + StatusUpdatesColumns.DATA_ID + "=OLD." + Data._ID + ";"
   1042                 + "   DELETE FROM " + Tables.NAME_LOOKUP
   1043                 + "     WHERE " + NameLookupColumns.DATA_ID + "=OLD." + Data._ID + ";"
   1044                 + " END");
   1045 
   1046 
   1047         db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_updated1;");
   1048         db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_updated1 "
   1049                 + "   AFTER UPDATE ON " + Tables.GROUPS
   1050                 + " BEGIN "
   1051                 + "   UPDATE " + Tables.GROUPS
   1052                 + "     SET "
   1053                 +         Groups.VERSION + "=OLD." + Groups.VERSION + "+1"
   1054                 + "     WHERE " + Groups._ID + "=OLD." + Groups._ID + ";"
   1055                 + " END");
   1056     }
   1057 
   1058     private static void createContactsIndexes(SQLiteDatabase db) {
   1059         db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
   1060         db.execSQL("CREATE INDEX name_lookup_index ON " + Tables.NAME_LOOKUP + " (" +
   1061                 NameLookupColumns.NORMALIZED_NAME + "," +
   1062                 NameLookupColumns.NAME_TYPE + ", " +
   1063                 NameLookupColumns.RAW_CONTACT_ID + ", " +
   1064                 NameLookupColumns.DATA_ID +
   1065         ");");
   1066 
   1067         db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key1_index");
   1068         db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
   1069                 RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
   1070                 RawContacts.SORT_KEY_PRIMARY +
   1071         ");");
   1072 
   1073         db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key2_index");
   1074         db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
   1075                 RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
   1076                 RawContacts.SORT_KEY_ALTERNATIVE +
   1077         ");");
   1078     }
   1079 
   1080     private static void createContactsViews(SQLiteDatabase db) {
   1081         db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS_ALL + ";");
   1082         db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS_RESTRICTED + ";");
   1083         db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_ALL + ";");
   1084         db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_RESTRICTED + ";");
   1085         db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS_ALL + ";");
   1086         db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS_RESTRICTED + ";");
   1087 
   1088         String dataColumns =
   1089                 Data.IS_PRIMARY + ", "
   1090                 + Data.IS_SUPER_PRIMARY + ", "
   1091                 + Data.DATA_VERSION + ", "
   1092                 + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + ","
   1093                 + MimetypesColumns.MIMETYPE + " AS " + Data.MIMETYPE + ", "
   1094                 + Data.DATA1 + ", "
   1095                 + Data.DATA2 + ", "
   1096                 + Data.DATA3 + ", "
   1097                 + Data.DATA4 + ", "
   1098                 + Data.DATA5 + ", "
   1099                 + Data.DATA6 + ", "
   1100                 + Data.DATA7 + ", "
   1101                 + Data.DATA8 + ", "
   1102                 + Data.DATA9 + ", "
   1103                 + Data.DATA10 + ", "
   1104                 + Data.DATA11 + ", "
   1105                 + Data.DATA12 + ", "
   1106                 + Data.DATA13 + ", "
   1107                 + Data.DATA14 + ", "
   1108                 + Data.DATA15 + ", "
   1109                 + Data.SYNC1 + ", "
   1110                 + Data.SYNC2 + ", "
   1111                 + Data.SYNC3 + ", "
   1112                 + Data.SYNC4;
   1113 
   1114         String syncColumns =
   1115                 RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ","
   1116                 + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ","
   1117                 + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + ","
   1118                 + RawContactsColumns.CONCRETE_NAME_VERIFIED + " AS " + RawContacts.NAME_VERIFIED + ","
   1119                 + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + ","
   1120                 + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + ","
   1121                 + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + ","
   1122                 + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + ","
   1123                 + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + ","
   1124                 + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4;
   1125 
   1126         String contactOptionColumns =
   1127                 ContactsColumns.CONCRETE_CUSTOM_RINGTONE
   1128                         + " AS " + RawContacts.CUSTOM_RINGTONE + ","
   1129                 + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
   1130                         + " AS " + RawContacts.SEND_TO_VOICEMAIL + ","
   1131                 + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
   1132                         + " AS " + RawContacts.LAST_TIME_CONTACTED + ","
   1133                 + ContactsColumns.CONCRETE_TIMES_CONTACTED
   1134                         + " AS " + RawContacts.TIMES_CONTACTED + ","
   1135                 + ContactsColumns.CONCRETE_STARRED
   1136                         + " AS " + RawContacts.STARRED;
   1137 
   1138         String contactNameColumns =
   1139                 "name_raw_contact." + RawContacts.DISPLAY_NAME_SOURCE
   1140                         + " AS " + Contacts.DISPLAY_NAME_SOURCE + ", "
   1141                 + "name_raw_contact." + RawContacts.DISPLAY_NAME_PRIMARY
   1142                         + " AS " + Contacts.DISPLAY_NAME_PRIMARY + ", "
   1143                 + "name_raw_contact." + RawContacts.DISPLAY_NAME_ALTERNATIVE
   1144                         + " AS " + Contacts.DISPLAY_NAME_ALTERNATIVE + ", "
   1145                 + "name_raw_contact." + RawContacts.PHONETIC_NAME
   1146                         + " AS " + Contacts.PHONETIC_NAME + ", "
   1147                 + "name_raw_contact." + RawContacts.PHONETIC_NAME_STYLE
   1148                         + " AS " + Contacts.PHONETIC_NAME_STYLE + ", "
   1149                 + "name_raw_contact." + RawContacts.SORT_KEY_PRIMARY
   1150                         + " AS " + Contacts.SORT_KEY_PRIMARY + ", "
   1151                 + "name_raw_contact." + RawContacts.SORT_KEY_ALTERNATIVE
   1152                         + " AS " + Contacts.SORT_KEY_ALTERNATIVE + ", "
   1153                 + "name_raw_contact." + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP
   1154                         + " AS " + Contacts.IN_VISIBLE_GROUP;
   1155 
   1156         String dataSelect = "SELECT "
   1157                 + DataColumns.CONCRETE_ID + " AS " + Data._ID + ","
   1158                 + Data.RAW_CONTACT_ID + ", "
   1159                 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", "
   1160                 + syncColumns + ", "
   1161                 + dataColumns + ", "
   1162                 + contactOptionColumns + ", "
   1163                 + contactNameColumns + ", "
   1164                 + Contacts.LOOKUP_KEY + ", "
   1165                 + Contacts.PHOTO_ID + ", "
   1166                 + Contacts.NAME_RAW_CONTACT_ID + ","
   1167                 + ContactsColumns.LAST_STATUS_UPDATE_ID + ", "
   1168                 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
   1169                 + " FROM " + Tables.DATA
   1170                 + " JOIN " + Tables.MIMETYPES + " ON ("
   1171                 +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
   1172                 + " JOIN " + Tables.RAW_CONTACTS + " ON ("
   1173                 +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
   1174                 + " JOIN " + Tables.CONTACTS + " ON ("
   1175                 +   RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"
   1176                 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
   1177                 +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"
   1178                 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
   1179                 +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
   1180                 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
   1181                 +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
   1182                 +   "' AND " + GroupsColumns.CONCRETE_ID + "="
   1183                         + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
   1184 
   1185         db.execSQL("CREATE VIEW " + Views.DATA_ALL + " AS " + dataSelect);
   1186         db.execSQL("CREATE VIEW " + Views.DATA_RESTRICTED + " AS " + dataSelect + " WHERE "
   1187                 + RawContactsColumns.CONCRETE_IS_RESTRICTED + "=0");
   1188 
   1189         String rawContactOptionColumns =
   1190                 RawContacts.CUSTOM_RINGTONE + ","
   1191                 + RawContacts.SEND_TO_VOICEMAIL + ","
   1192                 + RawContacts.LAST_TIME_CONTACTED + ","
   1193                 + RawContacts.TIMES_CONTACTED + ","
   1194                 + RawContacts.STARRED;
   1195 
   1196         String rawContactsSelect = "SELECT "
   1197                 + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ","
   1198                 + RawContacts.CONTACT_ID + ", "
   1199                 + RawContacts.AGGREGATION_MODE + ", "
   1200                 + RawContacts.DELETED + ", "
   1201                 + RawContacts.DISPLAY_NAME_SOURCE  + ", "
   1202                 + RawContacts.DISPLAY_NAME_PRIMARY  + ", "
   1203                 + RawContacts.DISPLAY_NAME_ALTERNATIVE  + ", "
   1204                 + RawContacts.PHONETIC_NAME  + ", "
   1205                 + RawContacts.PHONETIC_NAME_STYLE  + ", "
   1206                 + RawContacts.SORT_KEY_PRIMARY  + ", "
   1207                 + RawContacts.SORT_KEY_ALTERNATIVE + ", "
   1208                 + rawContactOptionColumns + ", "
   1209                 + syncColumns
   1210                 + " FROM " + Tables.RAW_CONTACTS;
   1211 
   1212         db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS_ALL + " AS " + rawContactsSelect);
   1213         db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS_RESTRICTED + " AS " + rawContactsSelect
   1214                 + " WHERE " + RawContacts.IS_RESTRICTED + "=0");
   1215 
   1216         String contactsColumns =
   1217                 ContactsColumns.CONCRETE_CUSTOM_RINGTONE
   1218                         + " AS " + Contacts.CUSTOM_RINGTONE + ", "
   1219                 + contactNameColumns + ", "
   1220                 + Contacts.HAS_PHONE_NUMBER + ", "
   1221                 + Contacts.LOOKUP_KEY + ", "
   1222                 + Contacts.PHOTO_ID + ", "
   1223                 + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED
   1224                         + " AS " + Contacts.LAST_TIME_CONTACTED + ", "
   1225                 + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL
   1226                         + " AS " + Contacts.SEND_TO_VOICEMAIL + ", "
   1227                 + ContactsColumns.CONCRETE_STARRED
   1228                         + " AS " + Contacts.STARRED + ", "
   1229                 + ContactsColumns.CONCRETE_TIMES_CONTACTED
   1230                         + " AS " + Contacts.TIMES_CONTACTED + ", "
   1231                 + ContactsColumns.LAST_STATUS_UPDATE_ID;
   1232 
   1233         String contactsSelect = "SELECT "
   1234                 + ContactsColumns.CONCRETE_ID + " AS " + Contacts._ID + ","
   1235                 + contactsColumns
   1236                 + " FROM " + Tables.CONTACTS
   1237                 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON("
   1238                 +   Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")";
   1239 
   1240         db.execSQL("CREATE VIEW " + Views.CONTACTS_ALL + " AS " + contactsSelect);
   1241         db.execSQL("CREATE VIEW " + Views.CONTACTS_RESTRICTED + " AS " + contactsSelect
   1242                 + " WHERE " + ContactsColumns.SINGLE_IS_RESTRICTED + "=0");
   1243     }
   1244 
   1245     private static void createGroupsView(SQLiteDatabase db) {
   1246         db.execSQL("DROP VIEW IF EXISTS " + Views.GROUPS_ALL + ";");
   1247         String groupsColumns =
   1248                 Groups.ACCOUNT_NAME + ","
   1249                 + Groups.ACCOUNT_TYPE + ","
   1250                 + Groups.SOURCE_ID + ","
   1251                 + Groups.VERSION + ","
   1252                 + Groups.DIRTY + ","
   1253                 + Groups.TITLE + ","
   1254                 + Groups.TITLE_RES + ","
   1255                 + Groups.NOTES + ","
   1256                 + Groups.SYSTEM_ID + ","
   1257                 + Groups.DELETED + ","
   1258                 + Groups.GROUP_VISIBLE + ","
   1259                 + Groups.SHOULD_SYNC + ","
   1260                 + Groups.SYNC1 + ","
   1261                 + Groups.SYNC2 + ","
   1262                 + Groups.SYNC3 + ","
   1263                 + Groups.SYNC4 + ","
   1264                 + PackagesColumns.PACKAGE + " AS " + Groups.RES_PACKAGE;
   1265 
   1266         String groupsSelect = "SELECT "
   1267                 + GroupsColumns.CONCRETE_ID + " AS " + Groups._ID + ","
   1268                 + groupsColumns
   1269                 + " FROM " + Tables.GROUPS_JOIN_PACKAGES;
   1270 
   1271         db.execSQL("CREATE VIEW " + Views.GROUPS_ALL + " AS " + groupsSelect);
   1272     }
   1273 
   1274     private static void createContactEntitiesView(SQLiteDatabase db) {
   1275         db.execSQL("DROP VIEW IF EXISTS " + Tables.CONTACT_ENTITIES + ";");
   1276         db.execSQL("DROP VIEW IF EXISTS " + Tables.CONTACT_ENTITIES_RESTRICTED + ";");
   1277 
   1278         String contactEntitiesSelect = "SELECT "
   1279                 + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + ","
   1280                 + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + ","
   1281                 + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + ","
   1282                 + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + ","
   1283                 + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + ","
   1284                 + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + ","
   1285                 + RawContactsColumns.CONCRETE_NAME_VERIFIED + " AS " + RawContacts.NAME_VERIFIED + ","
   1286                 + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + ","
   1287                 + RawContacts.CONTACT_ID + ", "
   1288                 + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + ", "
   1289                 + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + ", "
   1290                 + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + ", "
   1291                 + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4 + ", "
   1292                 + Data.MIMETYPE + ", "
   1293                 + Data.DATA1 + ", "
   1294                 + Data.DATA2 + ", "
   1295                 + Data.DATA3 + ", "
   1296                 + Data.DATA4 + ", "
   1297                 + Data.DATA5 + ", "
   1298                 + Data.DATA6 + ", "
   1299                 + Data.DATA7 + ", "
   1300                 + Data.DATA8 + ", "
   1301                 + Data.DATA9 + ", "
   1302                 + Data.DATA10 + ", "
   1303                 + Data.DATA11 + ", "
   1304                 + Data.DATA12 + ", "
   1305                 + Data.DATA13 + ", "
   1306                 + Data.DATA14 + ", "
   1307                 + Data.DATA15 + ", "
   1308                 + Data.SYNC1 + ", "
   1309                 + Data.SYNC2 + ", "
   1310                 + Data.SYNC3 + ", "
   1311                 + Data.SYNC4 + ", "
   1312                 + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ", "
   1313                 + Data.IS_PRIMARY + ", "
   1314                 + Data.IS_SUPER_PRIMARY + ", "
   1315                 + Data.DATA_VERSION + ", "
   1316                 + DataColumns.CONCRETE_ID + " AS " + RawContacts.Entity.DATA_ID + ","
   1317                 + RawContactsColumns.CONCRETE_STARRED + " AS " + RawContacts.STARRED + ","
   1318                 + RawContactsColumns.CONCRETE_IS_RESTRICTED + " AS "
   1319                         + RawContacts.IS_RESTRICTED + ","
   1320                 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID
   1321                 + " FROM " + Tables.RAW_CONTACTS
   1322                 + " LEFT OUTER JOIN " + Tables.DATA + " ON ("
   1323                 +   DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"
   1324                 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON ("
   1325                 +   DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"
   1326                 + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON ("
   1327                 +   DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")"
   1328                 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON ("
   1329                 +   MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE
   1330                 +   "' AND " + GroupsColumns.CONCRETE_ID + "="
   1331                 + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")";
   1332 
   1333         db.execSQL("CREATE VIEW " + Tables.CONTACT_ENTITIES + " AS "
   1334                 + contactEntitiesSelect);
   1335         db.execSQL("CREATE VIEW " + Tables.CONTACT_ENTITIES_RESTRICTED + " AS "
   1336                 + contactEntitiesSelect + " WHERE " + RawContacts.IS_RESTRICTED + "=0");
   1337     }
   1338 
   1339     @Override
   1340     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   1341         if (oldVersion < 99) {
   1342             Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion
   1343                     + ", data will be lost!");
   1344 
   1345             db.execSQL("DROP TABLE IF EXISTS " + Tables.CONTACTS + ";");
   1346             db.execSQL("DROP TABLE IF EXISTS " + Tables.RAW_CONTACTS + ";");
   1347             db.execSQL("DROP TABLE IF EXISTS " + Tables.PACKAGES + ";");
   1348             db.execSQL("DROP TABLE IF EXISTS " + Tables.MIMETYPES + ";");
   1349             db.execSQL("DROP TABLE IF EXISTS " + Tables.DATA + ";");
   1350             db.execSQL("DROP TABLE IF EXISTS " + Tables.PHONE_LOOKUP + ";");
   1351             db.execSQL("DROP TABLE IF EXISTS " + Tables.NAME_LOOKUP + ";");
   1352             db.execSQL("DROP TABLE IF EXISTS " + Tables.NICKNAME_LOOKUP + ";");
   1353             db.execSQL("DROP TABLE IF EXISTS " + Tables.GROUPS + ";");
   1354             db.execSQL("DROP TABLE IF EXISTS " + Tables.ACTIVITIES + ";");
   1355             db.execSQL("DROP TABLE IF EXISTS " + Tables.CALLS + ";");
   1356             db.execSQL("DROP TABLE IF EXISTS " + Tables.SETTINGS + ";");
   1357             db.execSQL("DROP TABLE IF EXISTS " + Tables.STATUS_UPDATES + ";");
   1358 
   1359             // TODO: we should not be dropping agg_exceptions and contact_options. In case that
   1360             // table's schema changes, we should try to preserve the data, because it was entered
   1361             // by the user and has never been synched to the server.
   1362             db.execSQL("DROP TABLE IF EXISTS " + Tables.AGGREGATION_EXCEPTIONS + ";");
   1363 
   1364             onCreate(db);
   1365             return;
   1366         }
   1367 
   1368         Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion);
   1369 
   1370         boolean upgradeViewsAndTriggers = false;
   1371         boolean upgradeNameLookup = false;
   1372 
   1373         if (oldVersion == 99) {
   1374             upgradeViewsAndTriggers = true;
   1375             oldVersion++;
   1376         }
   1377 
   1378         if (oldVersion == 100) {
   1379             db.execSQL("CREATE INDEX IF NOT EXISTS mimetypes_mimetype_index ON "
   1380                     + Tables.MIMETYPES + " ("
   1381                             + MimetypesColumns.MIMETYPE + ","
   1382                             + MimetypesColumns._ID + ");");
   1383             updateIndexStats(db, Tables.MIMETYPES,
   1384                     "mimetypes_mimetype_index", "50 1 1");
   1385 
   1386             upgradeViewsAndTriggers = true;
   1387             oldVersion++;
   1388         }
   1389 
   1390         if (oldVersion == 101) {
   1391             upgradeViewsAndTriggers = true;
   1392             oldVersion++;
   1393         }
   1394 
   1395         if (oldVersion == 102) {
   1396             upgradeViewsAndTriggers = true;
   1397             oldVersion++;
   1398         }
   1399 
   1400         if (oldVersion == 103) {
   1401             upgradeViewsAndTriggers = true;
   1402             oldVersion++;
   1403         }
   1404 
   1405         if (oldVersion == 104 || oldVersion == 201) {
   1406             LegacyApiSupport.createSettingsTable(db);
   1407             upgradeViewsAndTriggers = true;
   1408             oldVersion++;
   1409         }
   1410 
   1411         if (oldVersion == 105) {
   1412             upgradeToVersion202(db);
   1413             upgradeNameLookup = true;
   1414             oldVersion = 202;
   1415         }
   1416 
   1417         if (oldVersion == 202) {
   1418             upgradeToVersion203(db);
   1419             upgradeViewsAndTriggers = true;
   1420             oldVersion++;
   1421         }
   1422 
   1423         if (oldVersion == 203) {
   1424             upgradeViewsAndTriggers = true;
   1425             oldVersion++;
   1426         }
   1427 
   1428         if (oldVersion == 204) {
   1429             upgradeToVersion205(db);
   1430             upgradeViewsAndTriggers = true;
   1431             oldVersion++;
   1432         }
   1433 
   1434         if (oldVersion == 205) {
   1435             upgrateToVersion206(db);
   1436             upgradeViewsAndTriggers = true;
   1437             oldVersion++;
   1438         }
   1439 
   1440         if (oldVersion == 206) {
   1441             upgradeToVersion300(db);
   1442             oldVersion = 300;
   1443         }
   1444 
   1445         if (oldVersion == 300) {
   1446             upgradeViewsAndTriggers = true;
   1447             oldVersion = 301;
   1448         }
   1449 
   1450         if (oldVersion == 301) {
   1451             upgradeViewsAndTriggers = true;
   1452             oldVersion = 302;
   1453         }
   1454 
   1455         if (oldVersion == 302) {
   1456             upgradeEmailToVersion303(db);
   1457             upgradeNicknameToVersion303(db);
   1458             oldVersion = 303;
   1459         }
   1460 
   1461         if (oldVersion == 303) {
   1462             upgradeToVersion304(db);
   1463             oldVersion = 304;
   1464         }
   1465 
   1466         if (oldVersion == 304) {
   1467             upgradeNameLookup = true;
   1468             oldVersion = 305;
   1469         }
   1470 
   1471         if (oldVersion == 305) {
   1472             upgradeToVersion306(db);
   1473             oldVersion = 306;
   1474         }
   1475 
   1476         if (oldVersion == 306) {
   1477             upgradeToVersion307(db);
   1478             oldVersion = 307;
   1479         }
   1480 
   1481         if (oldVersion == 307) {
   1482             upgradeToVersion308(db);
   1483             oldVersion = 308;
   1484         }
   1485 
   1486         if (oldVersion == 308) {
   1487             upgradeViewsAndTriggers = true;
   1488             oldVersion = 309;
   1489         }
   1490 
   1491         if (upgradeViewsAndTriggers) {
   1492             createContactsViews(db);
   1493             createGroupsView(db);
   1494             createContactEntitiesView(db);
   1495             createContactsTriggers(db);
   1496             createContactsIndexes(db);
   1497             LegacyApiSupport.createViews(db);
   1498             updateSqliteStats(db);
   1499             mReopenDatabase = true;
   1500         }
   1501 
   1502         if (upgradeNameLookup) {
   1503             rebuildNameLookup(db);
   1504         }
   1505 
   1506         if (oldVersion != newVersion) {
   1507             throw new IllegalStateException(
   1508                     "error upgrading the database to version " + newVersion);
   1509         }
   1510     }
   1511 
   1512     private void upgradeToVersion202(SQLiteDatabase db) {
   1513         db.execSQL(
   1514                 "ALTER TABLE " + Tables.PHONE_LOOKUP +
   1515                 " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;");
   1516 
   1517         db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" +
   1518                 PhoneLookupColumns.MIN_MATCH + "," +
   1519                 PhoneLookupColumns.RAW_CONTACT_ID + "," +
   1520                 PhoneLookupColumns.DATA_ID +
   1521         ");");
   1522 
   1523         updateIndexStats(db, Tables.PHONE_LOOKUP,
   1524                 "phone_lookup_min_match_index", "10000 2 2 1");
   1525 
   1526         SQLiteStatement update = db.compileStatement(
   1527                 "UPDATE " + Tables.PHONE_LOOKUP +
   1528                 " SET " + PhoneLookupColumns.MIN_MATCH + "=?" +
   1529                 " WHERE " + PhoneLookupColumns.DATA_ID + "=?");
   1530 
   1531         // Populate the new column
   1532         Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA +
   1533                 " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")",
   1534                 new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null);
   1535         try {
   1536             while (c.moveToNext()) {
   1537                 long dataId = c.getLong(0);
   1538                 String number = c.getString(1);
   1539                 if (!TextUtils.isEmpty(number)) {
   1540                     update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number));
   1541                     update.bindLong(2, dataId);
   1542                     update.execute();
   1543                 }
   1544             }
   1545         } finally {
   1546             c.close();
   1547         }
   1548     }
   1549 
   1550     private void upgradeToVersion203(SQLiteDatabase db) {
   1551         // Garbage-collect first. A bug in Eclair was sometimes leaving
   1552         // raw_contacts in the database that no longer had contacts associated
   1553         // with them.  To avoid failures during this database upgrade, drop
   1554         // the orphaned raw_contacts.
   1555         db.execSQL(
   1556                 "DELETE FROM raw_contacts" +
   1557                 " WHERE contact_id NOT NULL" +
   1558                 " AND contact_id NOT IN (SELECT _id FROM contacts)");
   1559 
   1560         db.execSQL(
   1561                 "ALTER TABLE " + Tables.CONTACTS +
   1562                 " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)");
   1563         db.execSQL(
   1564                 "ALTER TABLE " + Tables.RAW_CONTACTS +
   1565                 " ADD " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP
   1566                         + " INTEGER NOT NULL DEFAULT 0");
   1567 
   1568         // For each Contact, find the RawContact that contributed the display name
   1569         db.execSQL(
   1570                 "UPDATE " + Tables.CONTACTS +
   1571                 " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
   1572                         " SELECT " + RawContacts._ID +
   1573                         " FROM " + Tables.RAW_CONTACTS +
   1574                         " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
   1575                         " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" +
   1576                                 Tables.CONTACTS + "." + Contacts.DISPLAY_NAME +
   1577                         " ORDER BY " + RawContacts._ID +
   1578                         " LIMIT 1)"
   1579         );
   1580 
   1581         db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" +
   1582                 Contacts.NAME_RAW_CONTACT_ID +
   1583         ");");
   1584 
   1585         // If for some unknown reason we missed some names, let's make sure there are
   1586         // no contacts without a name, picking a raw contact "at random".
   1587         db.execSQL(
   1588                 "UPDATE " + Tables.CONTACTS +
   1589                 " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" +
   1590                         " SELECT " + RawContacts._ID +
   1591                         " FROM " + Tables.RAW_CONTACTS +
   1592                         " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID +
   1593                         " ORDER BY " + RawContacts._ID +
   1594                         " LIMIT 1)" +
   1595                 " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL"
   1596         );
   1597 
   1598         // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use.
   1599         db.execSQL(
   1600                 "UPDATE " + Tables.CONTACTS +
   1601                 " SET " + Contacts.DISPLAY_NAME + "=NULL"
   1602         );
   1603 
   1604         // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow
   1605         // indexing on (display_name, in_visible_group)
   1606         db.execSQL(
   1607                 "UPDATE " + Tables.RAW_CONTACTS +
   1608                 " SET " + RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "=(" +
   1609                         "SELECT " + Contacts.IN_VISIBLE_GROUP +
   1610                         " FROM " + Tables.CONTACTS +
   1611                         " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" +
   1612                 " WHERE " + RawContacts.CONTACT_ID + " NOT NULL"
   1613         );
   1614 
   1615         db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
   1616                 RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
   1617                 RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" +
   1618         ");");
   1619 
   1620         db.execSQL("DROP INDEX contacts_visible_index");
   1621         db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" +
   1622                 Contacts.IN_VISIBLE_GROUP +
   1623         ");");
   1624     }
   1625 
   1626     private void upgradeToVersion205(SQLiteDatabase db) {
   1627         db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
   1628                 + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;");
   1629         db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
   1630                 + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;");
   1631         db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
   1632                 + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;");
   1633         db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
   1634                 + " ADD " + RawContacts.SORT_KEY_PRIMARY
   1635                 + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
   1636         db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
   1637                 + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE
   1638                 + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";");
   1639 
   1640         final Locale locale = Locale.getDefault();
   1641 
   1642         NameSplitter splitter = createNameSplitter();
   1643 
   1644         SQLiteStatement rawContactUpdate = db.compileStatement(
   1645                 "UPDATE " + Tables.RAW_CONTACTS +
   1646                 " SET " +
   1647                         RawContacts.DISPLAY_NAME_PRIMARY + "=?," +
   1648                         RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," +
   1649                         RawContacts.PHONETIC_NAME + "=?," +
   1650                         RawContacts.PHONETIC_NAME_STYLE + "=?," +
   1651                         RawContacts.SORT_KEY_PRIMARY + "=?," +
   1652                         RawContacts.SORT_KEY_ALTERNATIVE + "=?" +
   1653                 " WHERE " + RawContacts._ID + "=?");
   1654 
   1655         upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter);
   1656         upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter);
   1657 
   1658         db.execSQL("DROP INDEX raw_contact_sort_key1_index");
   1659         db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" +
   1660                 RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
   1661                 RawContacts.SORT_KEY_PRIMARY +
   1662         ");");
   1663 
   1664         db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" +
   1665                 RawContactsColumns.CONTACT_IN_VISIBLE_GROUP + "," +
   1666                 RawContacts.SORT_KEY_ALTERNATIVE +
   1667         ");");
   1668     }
   1669 
   1670     private interface StructName205Query {
   1671         String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
   1672 
   1673         String COLUMNS[] = {
   1674                 DataColumns.CONCRETE_ID,
   1675                 Data.RAW_CONTACT_ID,
   1676                 RawContacts.DISPLAY_NAME_SOURCE,
   1677                 RawContacts.DISPLAY_NAME_PRIMARY,
   1678                 StructuredName.PREFIX,
   1679                 StructuredName.GIVEN_NAME,
   1680                 StructuredName.MIDDLE_NAME,
   1681                 StructuredName.FAMILY_NAME,
   1682                 StructuredName.SUFFIX,
   1683                 StructuredName.PHONETIC_FAMILY_NAME,
   1684                 StructuredName.PHONETIC_MIDDLE_NAME,
   1685                 StructuredName.PHONETIC_GIVEN_NAME,
   1686         };
   1687 
   1688         int ID = 0;
   1689         int RAW_CONTACT_ID = 1;
   1690         int DISPLAY_NAME_SOURCE = 2;
   1691         int DISPLAY_NAME = 3;
   1692         int PREFIX = 4;
   1693         int GIVEN_NAME = 5;
   1694         int MIDDLE_NAME = 6;
   1695         int FAMILY_NAME = 7;
   1696         int SUFFIX = 8;
   1697         int PHONETIC_FAMILY_NAME = 9;
   1698         int PHONETIC_MIDDLE_NAME = 10;
   1699         int PHONETIC_GIVEN_NAME = 11;
   1700     }
   1701 
   1702     private void upgradeStructuredNamesToVersion205(SQLiteDatabase db,
   1703             SQLiteStatement rawContactUpdate, NameSplitter splitter) {
   1704 
   1705         // Process structured names to detect the style of the full name and phonetic name
   1706 
   1707         long mMimeType;
   1708         try {
   1709             mMimeType = DatabaseUtils.longForQuery(db,
   1710                     "SELECT " + MimetypesColumns._ID +
   1711                     " FROM " + Tables.MIMETYPES +
   1712                     " WHERE " + MimetypesColumns.MIMETYPE
   1713                             + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null);
   1714         } catch (SQLiteDoneException e) {
   1715             // No structured names in the database
   1716             return;
   1717         }
   1718 
   1719         SQLiteStatement structuredNameUpdate = db.compileStatement(
   1720                 "UPDATE " + Tables.DATA +
   1721                 " SET " +
   1722                         StructuredName.FULL_NAME_STYLE + "=?," +
   1723                         StructuredName.DISPLAY_NAME + "=?," +
   1724                         StructuredName.PHONETIC_NAME_STYLE + "=?" +
   1725                 " WHERE " + Data._ID + "=?");
   1726 
   1727         NameSplitter.Name name = new NameSplitter.Name();
   1728         StringBuilder sb = new StringBuilder();
   1729         Cursor cursor = db.query(StructName205Query.TABLE,
   1730                 StructName205Query.COLUMNS,
   1731                 DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null);
   1732         try {
   1733             while (cursor.moveToNext()) {
   1734                 long dataId = cursor.getLong(StructName205Query.ID);
   1735                 long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID);
   1736                 int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE);
   1737                 String displayName = cursor.getString(StructName205Query.DISPLAY_NAME);
   1738 
   1739                 name.clear();
   1740                 name.prefix = cursor.getString(StructName205Query.PREFIX);
   1741                 name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME);
   1742                 name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME);
   1743                 name.familyName = cursor.getString(StructName205Query.FAMILY_NAME);
   1744                 name.suffix = cursor.getString(StructName205Query.SUFFIX);
   1745                 name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME);
   1746                 name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME);
   1747                 name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME);
   1748 
   1749                 upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name,
   1750                         structuredNameUpdate, rawContactUpdate, splitter, sb);
   1751             }
   1752         } finally {
   1753             cursor.close();
   1754         }
   1755     }
   1756 
   1757     private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource,
   1758             String currentDisplayName, NameSplitter.Name name,
   1759             SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate,
   1760             NameSplitter splitter, StringBuilder sb) {
   1761 
   1762         splitter.guessNameStyle(name);
   1763         int unadjustedFullNameStyle = name.fullNameStyle;
   1764         name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle);
   1765         String displayName = splitter.join(name, true);
   1766 
   1767         // Don't update database with the adjusted fullNameStyle as it is locale
   1768         // related
   1769         structuredNameUpdate.bindLong(1, unadjustedFullNameStyle);
   1770         DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName);
   1771         structuredNameUpdate.bindLong(3, name.phoneticNameStyle);
   1772         structuredNameUpdate.bindLong(4, dataId);
   1773         structuredNameUpdate.execute();
   1774 
   1775         if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) {
   1776             String displayNameAlternative = splitter.join(name, false);
   1777             String phoneticName = splitter.joinPhoneticName(name);
   1778             String sortKey = null;
   1779             String sortKeyAlternative = null;
   1780 
   1781             if (phoneticName != null) {
   1782                 sortKey = sortKeyAlternative = phoneticName;
   1783             } else if (name.fullNameStyle == FullNameStyle.CHINESE ||
   1784                     name.fullNameStyle == FullNameStyle.CJK) {
   1785                 sortKey = sortKeyAlternative = ContactLocaleUtils.getIntance()
   1786                         .getSortKey(displayName, name.fullNameStyle);
   1787             }
   1788 
   1789             if (sortKey == null) {
   1790                 sortKey = displayName;
   1791                 sortKeyAlternative = displayNameAlternative;
   1792             }
   1793 
   1794             updateRawContact205(rawContactUpdate, rawContactId, displayName,
   1795                     displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey,
   1796                     sortKeyAlternative);
   1797         }
   1798     }
   1799 
   1800     private interface Organization205Query {
   1801         String TABLE = Tables.DATA_JOIN_RAW_CONTACTS;
   1802 
   1803         String COLUMNS[] = {
   1804                 DataColumns.CONCRETE_ID,
   1805                 Data.RAW_CONTACT_ID,
   1806                 Organization.COMPANY,
   1807                 Organization.PHONETIC_NAME,
   1808         };
   1809 
   1810         int ID = 0;
   1811         int RAW_CONTACT_ID = 1;
   1812         int COMPANY = 2;
   1813         int PHONETIC_NAME = 3;
   1814     }
   1815 
   1816     private void upgradeOrganizationsToVersion205(SQLiteDatabase db,
   1817             SQLiteStatement rawContactUpdate, NameSplitter splitter) {
   1818         final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE);
   1819 
   1820         SQLiteStatement organizationUpdate = db.compileStatement(
   1821                 "UPDATE " + Tables.DATA +
   1822                 " SET " +
   1823                         Organization.PHONETIC_NAME_STYLE + "=?" +
   1824                 " WHERE " + Data._ID + "=?");
   1825 
   1826         Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS,
   1827                 DataColumns.MIMETYPE_ID + "=" + mimeType + " AND "
   1828                         + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION,
   1829                 null, null, null, null);
   1830         try {
   1831             while (cursor.moveToNext()) {
   1832                 long dataId = cursor.getLong(Organization205Query.ID);
   1833                 long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID);
   1834                 String company = cursor.getString(Organization205Query.COMPANY);
   1835                 String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME);
   1836 
   1837                 int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName);
   1838 
   1839                 organizationUpdate.bindLong(1, phoneticNameStyle);
   1840                 organizationUpdate.bindLong(2, dataId);
   1841                 organizationUpdate.execute();
   1842 
   1843                 String sortKey = null;
   1844                 if (phoneticName == null && company != null) {
   1845                     int nameStyle = splitter.guessFullNameStyle(company);
   1846                     nameStyle = splitter.getAdjustedFullNameStyle(nameStyle);
   1847                     if (nameStyle == FullNameStyle.CHINESE ||
   1848                             nameStyle == FullNameStyle.CJK ) {
   1849                         sortKey = ContactLocaleUtils.getIntance()
   1850                                 .getSortKey(company, nameStyle);
   1851                     }
   1852                 }
   1853 
   1854                 if (sortKey == null) {
   1855                     sortKey = company;
   1856                 }
   1857 
   1858                 updateRawContact205(rawContactUpdate, rawContactId, company,
   1859                         company, phoneticNameStyle, phoneticName, sortKey, sortKey);
   1860             }
   1861         } finally {
   1862             cursor.close();
   1863         }
   1864     }
   1865 
   1866     private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId,
   1867             String displayName, String displayNameAlternative, int phoneticNameStyle,
   1868             String phoneticName, String sortKeyPrimary, String sortKeyAlternative) {
   1869         bindString(rawContactUpdate, 1, displayName);
   1870         bindString(rawContactUpdate, 2, displayNameAlternative);
   1871         bindString(rawContactUpdate, 3, phoneticName);
   1872         rawContactUpdate.bindLong(4, phoneticNameStyle);
   1873         bindString(rawContactUpdate, 5, sortKeyPrimary);
   1874         bindString(rawContactUpdate, 6, sortKeyAlternative);
   1875         rawContactUpdate.bindLong(7, rawContactId);
   1876         rawContactUpdate.execute();
   1877     }
   1878 
   1879     private void upgrateToVersion206(SQLiteDatabase db) {
   1880         db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS
   1881                 + " ADD " + RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0;");
   1882     }
   1883 
   1884     private interface Organization300Query {
   1885         String TABLE = Tables.DATA;
   1886 
   1887         String SELECTION = DataColumns.MIMETYPE_ID + "=?";
   1888 
   1889         String COLUMNS[] = {
   1890                 Organization._ID,
   1891                 Organization.RAW_CONTACT_ID,
   1892                 Organization.COMPANY,
   1893                 Organization.TITLE
   1894         };
   1895 
   1896         int ID = 0;
   1897         int RAW_CONTACT_ID = 1;
   1898         int COMPANY = 2;
   1899         int TITLE = 3;
   1900     }
   1901 
   1902     /**
   1903      * Fix for the bug where name lookup records for organizations would get removed by
   1904      * unrelated updates of the data rows.
   1905      */
   1906     private void upgradeToVersion300(SQLiteDatabase db) {
   1907         final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE);
   1908         if (mimeType == -1) {
   1909             return;
   1910         }
   1911 
   1912         ContentValues values = new ContentValues();
   1913 
   1914         // Find all data rows with the mime type "organization"
   1915         Cursor cursor = db.query(Organization300Query.TABLE, Organization300Query.COLUMNS,
   1916                 Organization300Query.SELECTION, new String[] {String.valueOf(mimeType)},
   1917                 null, null, null);
   1918         try {
   1919             while (cursor.moveToNext()) {
   1920                 long dataId = cursor.getLong(Organization300Query.ID);
   1921                 long rawContactId = cursor.getLong(Organization300Query.RAW_CONTACT_ID);
   1922                 String company = cursor.getString(Organization300Query.COMPANY);
   1923                 String title = cursor.getString(Organization300Query.TITLE);
   1924 
   1925                 // First delete name lookup if there is any (chances are there won't be)
   1926                 db.delete(Tables.NAME_LOOKUP, NameLookupColumns.DATA_ID + "=?",
   1927                         new String[]{String.valueOf(dataId)});
   1928 
   1929                 // Now insert two name lookup records: one for company name, one for title
   1930                 values.put(NameLookupColumns.DATA_ID, dataId);
   1931                 values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
   1932                 values.put(NameLookupColumns.NAME_TYPE, NameLookupType.ORGANIZATION);
   1933 
   1934                 if (!TextUtils.isEmpty(company)) {
   1935                     values.put(NameLookupColumns.NORMALIZED_NAME,
   1936                             NameNormalizer.normalize(company));
   1937                     db.insert(Tables.NAME_LOOKUP, null, values);
   1938                 }
   1939 
   1940                 if (!TextUtils.isEmpty(title)) {
   1941                     values.put(NameLookupColumns.NORMALIZED_NAME,
   1942                             NameNormalizer.normalize(title));
   1943                     db.insert(Tables.NAME_LOOKUP, null, values);
   1944                 }
   1945             }
   1946         } finally {
   1947             cursor.close();
   1948         }
   1949     }
   1950 
   1951     private static final class Upgrade303Query {
   1952         public static final String TABLE = Tables.DATA;
   1953 
   1954         public static final String SELECTION =
   1955                 DataColumns.MIMETYPE_ID + "=?" +
   1956                     " AND " + Data._ID + " NOT IN " +
   1957                     "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" +
   1958                     " AND " + Data.DATA1 + " NOT NULL";
   1959 
   1960         public static final String COLUMNS[] = {
   1961                 Data._ID,
   1962                 Data.RAW_CONTACT_ID,
   1963                 Data.DATA1,
   1964         };
   1965 
   1966         public static final int ID = 0;
   1967         public static final int RAW_CONTACT_ID = 1;
   1968         public static final int DATA1 = 2;
   1969     }
   1970 
   1971     /**
   1972      * The {@link ContactsProvider2#update} method was deleting name lookup for new
   1973      * emails during the sync.  We need to restore the lost name lookup rows.
   1974      */
   1975     private void upgradeEmailToVersion303(SQLiteDatabase db) {
   1976         final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
   1977         if (mimeTypeId == -1) {
   1978             return;
   1979         }
   1980 
   1981         ContentValues values = new ContentValues();
   1982 
   1983         // Find all data rows with the mime type "email" that are missing name lookup
   1984         Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
   1985                 Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
   1986                 null, null, null);
   1987         try {
   1988             while (cursor.moveToNext()) {
   1989                 long dataId = cursor.getLong(Upgrade303Query.ID);
   1990                 long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
   1991                 String value = cursor.getString(Upgrade303Query.DATA1);
   1992                 value = extractHandleFromEmailAddress(value);
   1993 
   1994                 if (value != null) {
   1995                     values.put(NameLookupColumns.DATA_ID, dataId);
   1996                     values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
   1997                     values.put(NameLookupColumns.NAME_TYPE, NameLookupType.EMAIL_BASED_NICKNAME);
   1998                     values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
   1999                     db.insert(Tables.NAME_LOOKUP, null, values);
   2000                 }
   2001             }
   2002         } finally {
   2003             cursor.close();
   2004         }
   2005     }
   2006 
   2007     /**
   2008      * The {@link ContactsProvider2#update} method was deleting name lookup for new
   2009      * nicknames during the sync.  We need to restore the lost name lookup rows.
   2010      */
   2011     private void upgradeNicknameToVersion303(SQLiteDatabase db) {
   2012         final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
   2013         if (mimeTypeId == -1) {
   2014             return;
   2015         }
   2016 
   2017         ContentValues values = new ContentValues();
   2018 
   2019         // Find all data rows with the mime type "nickname" that are missing name lookup
   2020         Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS,
   2021                 Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)},
   2022                 null, null, null);
   2023         try {
   2024             while (cursor.moveToNext()) {
   2025                 long dataId = cursor.getLong(Upgrade303Query.ID);
   2026                 long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID);
   2027                 String value = cursor.getString(Upgrade303Query.DATA1);
   2028 
   2029                 values.put(NameLookupColumns.DATA_ID, dataId);
   2030                 values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId);
   2031                 values.put(NameLookupColumns.NAME_TYPE, NameLookupType.NICKNAME);
   2032                 values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value));
   2033                 db.insert(Tables.NAME_LOOKUP, null, values);
   2034             }
   2035         } finally {
   2036             cursor.close();
   2037         }
   2038     }
   2039 
   2040     private void upgradeToVersion304(SQLiteDatabase db) {
   2041         // Mimetype table requires an index on mime type
   2042         db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" +
   2043                 MimetypesColumns.MIMETYPE +
   2044         ");");
   2045     }
   2046 
   2047     private void upgradeToVersion306(SQLiteDatabase db) {
   2048         // Fix invalid lookup that was used for Exchange contacts (it was not escaped)
   2049         // It happened when a new contact was created AND synchronized
   2050         final StringBuilder lookupKeyBuilder = new StringBuilder();
   2051         final SQLiteStatement updateStatement = db.compileStatement(
   2052                 "UPDATE contacts " +
   2053                 "SET lookup=? " +
   2054                 "WHERE _id=?");
   2055         final Cursor contactIdCursor = db.rawQuery(
   2056                 "SELECT DISTINCT contact_id " +
   2057                 "FROM raw_contacts " +
   2058                 "WHERE deleted=0 AND account_type='com.android.exchange'",
   2059                 null);
   2060         try {
   2061             while (contactIdCursor.moveToNext()) {
   2062                 final long contactId = contactIdCursor.getLong(0);
   2063                 lookupKeyBuilder.setLength(0);
   2064                 final Cursor c = db.rawQuery(
   2065                         "SELECT account_type, account_name, _id, sourceid, display_name " +
   2066                         "FROM raw_contacts " +
   2067                         "WHERE contact_id=? " +
   2068                         "ORDER BY _id",
   2069                         new String[] { String.valueOf(contactId) });
   2070                 try {
   2071                     while (c.moveToNext()) {
   2072                         ContactLookupKey.appendToLookupKey(lookupKeyBuilder,
   2073                                 c.getString(0),
   2074                                 c.getString(1),
   2075                                 c.getLong(2),
   2076                                 c.getString(3),
   2077                                 c.getString(4));
   2078                     }
   2079                 } finally {
   2080                     c.close();
   2081                 }
   2082 
   2083                 if (lookupKeyBuilder.length() == 0) {
   2084                     updateStatement.bindNull(1);
   2085                 } else {
   2086                     updateStatement.bindString(1, Uri.encode(lookupKeyBuilder.toString()));
   2087                 }
   2088                 updateStatement.bindLong(2, contactId);
   2089 
   2090                 updateStatement.execute();
   2091             }
   2092         } finally {
   2093             updateStatement.close();
   2094             contactIdCursor.close();
   2095         }
   2096     }
   2097 
   2098     private void upgradeToVersion307(SQLiteDatabase db) {
   2099         db.execSQL("CREATE TABLE properties (" +
   2100                 "property_key TEXT PRIMARY_KEY, " +
   2101                 "property_value TEXT" +
   2102         ");");
   2103     }
   2104 
   2105     private void upgradeToVersion308(SQLiteDatabase db) {
   2106             db.execSQL("CREATE TABLE accounts (" +
   2107                     "account_name TEXT, " +
   2108                     "account_type TEXT " +
   2109             ");");
   2110 
   2111             db.execSQL("INSERT INTO accounts " +
   2112                     "SELECT DISTINCT account_name, account_type FROM raw_contacts");
   2113     }
   2114 
   2115     private void rebuildNameLookup(SQLiteDatabase db) {
   2116         db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
   2117         insertNameLookup(db);
   2118         createContactsIndexes(db);
   2119     }
   2120 
   2121     /**
   2122      * Regenerates all locale-sensitive data: nickname_lookup, name_lookup and sort keys.
   2123      */
   2124     public void setLocale(ContactsProvider2 provider, Locale locale) {
   2125         Log.i(TAG, "Switching to locale " + locale);
   2126 
   2127         long start = SystemClock.uptimeMillis();
   2128         SQLiteDatabase db = getWritableDatabase();
   2129         db.setLocale(locale);
   2130         db.beginTransaction();
   2131         try {
   2132             db.execSQL("DROP INDEX raw_contact_sort_key1_index");
   2133             db.execSQL("DROP INDEX raw_contact_sort_key2_index");
   2134             db.execSQL("DROP INDEX IF EXISTS name_lookup_index");
   2135 
   2136             loadNicknameLookupTable(db);
   2137             insertNameLookup(db);
   2138             rebuildSortKeys(db, provider);
   2139             createContactsIndexes(db);
   2140             db.setTransactionSuccessful();
   2141         } finally {
   2142             db.endTransaction();
   2143         }
   2144 
   2145         Log.i(TAG, "Locale change completed in " + (SystemClock.uptimeMillis() - start) + "ms");
   2146     }
   2147 
   2148     /**
   2149      * Regenerates sort keys for all contacts.
   2150      */
   2151     private void rebuildSortKeys(SQLiteDatabase db, ContactsProvider2 provider) {
   2152         Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID},
   2153                 null, null, null, null, null);
   2154         try {
   2155             while (cursor.moveToNext()) {
   2156                 long rawContactId = cursor.getLong(0);
   2157                 provider.updateRawContactDisplayName(db, rawContactId);
   2158             }
   2159         } finally {
   2160             cursor.close();
   2161         }
   2162     }
   2163 
   2164     private void insertNameLookup(SQLiteDatabase db) {
   2165         db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP);
   2166 
   2167         SQLiteStatement nameLookupInsert = db.compileStatement(
   2168                 "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "("
   2169                         + NameLookupColumns.RAW_CONTACT_ID + ","
   2170                         + NameLookupColumns.DATA_ID + ","
   2171                         + NameLookupColumns.NAME_TYPE + ","
   2172                         + NameLookupColumns.NORMALIZED_NAME +
   2173                 ") VALUES (?,?,?,?)");
   2174 
   2175         try {
   2176             insertStructuredNameLookup(db, nameLookupInsert);
   2177             insertOrganizationLookup(db, nameLookupInsert);
   2178             insertEmailLookup(db, nameLookupInsert);
   2179             insertNicknameLookup(db, nameLookupInsert);
   2180         } finally {
   2181             nameLookupInsert.close();
   2182         }
   2183     }
   2184 
   2185     private static final class StructuredNameQuery {
   2186         public static final String TABLE = Tables.DATA;
   2187 
   2188         public static final String SELECTION =
   2189                 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
   2190 
   2191         public static final String COLUMNS[] = {
   2192                 StructuredName._ID,
   2193                 StructuredName.RAW_CONTACT_ID,
   2194                 StructuredName.DISPLAY_NAME,
   2195         };
   2196 
   2197         public static final int ID = 0;
   2198         public static final int RAW_CONTACT_ID = 1;
   2199         public static final int DISPLAY_NAME = 2;
   2200     }
   2201 
   2202     private class StructuredNameLookupBuilder extends NameLookupBuilder {
   2203 
   2204         private final SQLiteStatement mNameLookupInsert;
   2205         private final CommonNicknameCache mCommonNicknameCache;
   2206 
   2207         public StructuredNameLookupBuilder(NameSplitter splitter,
   2208                 CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) {
   2209             super(splitter);
   2210             this.mCommonNicknameCache = commonNicknameCache;
   2211             this.mNameLookupInsert = nameLookupInsert;
   2212         }
   2213 
   2214         @Override
   2215         protected void insertNameLookup(long rawContactId, long dataId, int lookupType,
   2216                 String name) {
   2217             if (!TextUtils.isEmpty(name)) {
   2218                 ContactsDatabaseHelper.this.insertNormalizedNameLookup(mNameLookupInsert,
   2219                         rawContactId, dataId, lookupType, name);
   2220             }
   2221         }
   2222 
   2223         @Override
   2224         protected String[] getCommonNicknameClusters(String normalizedName) {
   2225             return mCommonNicknameCache.getCommonNicknameClusters(normalizedName);
   2226         }
   2227     }
   2228 
   2229     /**
   2230      * Inserts name lookup rows for all structured names in the database.
   2231      */
   2232     private void insertStructuredNameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
   2233         NameSplitter nameSplitter = createNameSplitter();
   2234         NameLookupBuilder nameLookupBuilder = new StructuredNameLookupBuilder(nameSplitter,
   2235                 new CommonNicknameCache(db), nameLookupInsert);
   2236         final long mimeTypeId = lookupMimeTypeId(db, StructuredName.CONTENT_ITEM_TYPE);
   2237         Cursor cursor = db.query(StructuredNameQuery.TABLE, StructuredNameQuery.COLUMNS,
   2238                 StructuredNameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
   2239                 null, null, null);
   2240         try {
   2241             while (cursor.moveToNext()) {
   2242                 long dataId = cursor.getLong(StructuredNameQuery.ID);
   2243                 long rawContactId = cursor.getLong(StructuredNameQuery.RAW_CONTACT_ID);
   2244                 String name = cursor.getString(StructuredNameQuery.DISPLAY_NAME);
   2245                 int fullNameStyle = nameSplitter.guessFullNameStyle(name);
   2246                 fullNameStyle = nameSplitter.getAdjustedFullNameStyle(fullNameStyle);
   2247                 nameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle);
   2248             }
   2249         } finally {
   2250             cursor.close();
   2251         }
   2252     }
   2253 
   2254     private static final class OrganizationQuery {
   2255         public static final String TABLE = Tables.DATA;
   2256 
   2257         public static final String SELECTION =
   2258                 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
   2259 
   2260         public static final String COLUMNS[] = {
   2261                 Organization._ID,
   2262                 Organization.RAW_CONTACT_ID,
   2263                 Organization.COMPANY,
   2264                 Organization.TITLE,
   2265         };
   2266 
   2267         public static final int ID = 0;
   2268         public static final int RAW_CONTACT_ID = 1;
   2269         public static final int COMPANY = 2;
   2270         public static final int TITLE = 3;
   2271     }
   2272 
   2273     /**
   2274      * Inserts name lookup rows for all organizations in the database.
   2275      */
   2276     private void insertOrganizationLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
   2277         final long mimeTypeId = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE);
   2278         Cursor cursor = db.query(OrganizationQuery.TABLE, OrganizationQuery.COLUMNS,
   2279                 OrganizationQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
   2280                 null, null, null);
   2281         try {
   2282             while (cursor.moveToNext()) {
   2283                 long dataId = cursor.getLong(OrganizationQuery.ID);
   2284                 long rawContactId = cursor.getLong(OrganizationQuery.RAW_CONTACT_ID);
   2285                 String organization = cursor.getString(OrganizationQuery.COMPANY);
   2286                 String title = cursor.getString(OrganizationQuery.TITLE);
   2287                 insertNameLookup(nameLookupInsert, rawContactId, dataId,
   2288                         NameLookupType.ORGANIZATION, organization);
   2289                 insertNameLookup(nameLookupInsert, rawContactId, dataId,
   2290                         NameLookupType.ORGANIZATION, title);
   2291             }
   2292         } finally {
   2293             cursor.close();
   2294         }
   2295     }
   2296 
   2297     private static final class EmailQuery {
   2298         public static final String TABLE = Tables.DATA;
   2299 
   2300         public static final String SELECTION =
   2301                 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
   2302 
   2303         public static final String COLUMNS[] = {
   2304                 Email._ID,
   2305                 Email.RAW_CONTACT_ID,
   2306                 Email.ADDRESS,
   2307         };
   2308 
   2309         public static final int ID = 0;
   2310         public static final int RAW_CONTACT_ID = 1;
   2311         public static final int ADDRESS = 2;
   2312     }
   2313 
   2314     /**
   2315      * Inserts name lookup rows for all email addresses in the database.
   2316      */
   2317     private void insertEmailLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
   2318         final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE);
   2319         Cursor cursor = db.query(EmailQuery.TABLE, EmailQuery.COLUMNS,
   2320                 EmailQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
   2321                 null, null, null);
   2322         try {
   2323             while (cursor.moveToNext()) {
   2324                 long dataId = cursor.getLong(EmailQuery.ID);
   2325                 long rawContactId = cursor.getLong(EmailQuery.RAW_CONTACT_ID);
   2326                 String address = cursor.getString(EmailQuery.ADDRESS);
   2327                 address = extractHandleFromEmailAddress(address);
   2328                 insertNameLookup(nameLookupInsert, rawContactId, dataId,
   2329                         NameLookupType.EMAIL_BASED_NICKNAME, address);
   2330             }
   2331         } finally {
   2332             cursor.close();
   2333         }
   2334     }
   2335 
   2336     private static final class NicknameQuery {
   2337         public static final String TABLE = Tables.DATA;
   2338 
   2339         public static final String SELECTION =
   2340                 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL";
   2341 
   2342         public static final String COLUMNS[] = {
   2343                 Nickname._ID,
   2344                 Nickname.RAW_CONTACT_ID,
   2345                 Nickname.NAME,
   2346         };
   2347 
   2348         public static final int ID = 0;
   2349         public static final int RAW_CONTACT_ID = 1;
   2350         public static final int NAME = 2;
   2351     }
   2352 
   2353     /**
   2354      * Inserts name lookup rows for all nicknames in the database.
   2355      */
   2356     private void insertNicknameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) {
   2357         final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE);
   2358         Cursor cursor = db.query(NicknameQuery.TABLE, NicknameQuery.COLUMNS,
   2359                 NicknameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)},
   2360                 null, null, null);
   2361         try {
   2362             while (cursor.moveToNext()) {
   2363                 long dataId = cursor.getLong(NicknameQuery.ID);
   2364                 long rawContactId = cursor.getLong(NicknameQuery.RAW_CONTACT_ID);
   2365                 String nickname = cursor.getString(NicknameQuery.NAME);
   2366                 insertNameLookup(nameLookupInsert, rawContactId, dataId,
   2367                         NameLookupType.NICKNAME, nickname);
   2368             }
   2369         } finally {
   2370             cursor.close();
   2371         }
   2372     }
   2373 
   2374     /**
   2375      * Inserts a record in the {@link Tables#NAME_LOOKUP} table.
   2376      */
   2377     public void insertNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
   2378             int lookupType, String name) {
   2379         if (TextUtils.isEmpty(name)) {
   2380             return;
   2381         }
   2382 
   2383         String normalized = NameNormalizer.normalize(name);
   2384         if (TextUtils.isEmpty(normalized)) {
   2385             return;
   2386         }
   2387 
   2388         insertNormalizedNameLookup(stmt, rawContactId, dataId, lookupType, normalized);
   2389     }
   2390 
   2391     private void insertNormalizedNameLookup(SQLiteStatement stmt, long rawContactId, long dataId,
   2392             int lookupType, String normalizedName) {
   2393         stmt.bindLong(1, rawContactId);
   2394         stmt.bindLong(2, dataId);
   2395         stmt.bindLong(3, lookupType);
   2396         stmt.bindString(4, normalizedName);
   2397         stmt.executeInsert();
   2398     }
   2399 
   2400     public String extractHandleFromEmailAddress(String email) {
   2401         Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
   2402         if (tokens.length == 0) {
   2403             return null;
   2404         }
   2405 
   2406         String address = tokens[0].getAddress();
   2407         int at = address.indexOf('@');
   2408         if (at != -1) {
   2409             return address.substring(0, at);
   2410         }
   2411         return null;
   2412     }
   2413 
   2414     public String extractAddressFromEmailAddress(String email) {
   2415         Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email);
   2416         if (tokens.length == 0) {
   2417             return null;
   2418         }
   2419 
   2420         return tokens[0].getAddress();
   2421     }
   2422 
   2423     private long lookupMimeTypeId(SQLiteDatabase db, String mimeType) {
   2424         try {
   2425             return DatabaseUtils.longForQuery(db,
   2426                     "SELECT " + MimetypesColumns._ID +
   2427                     " FROM " + Tables.MIMETYPES +
   2428                     " WHERE " + MimetypesColumns.MIMETYPE
   2429                             + "='" + mimeType + "'", null);
   2430         } catch (SQLiteDoneException e) {
   2431             // No rows of this type in the database
   2432             return -1;
   2433         }
   2434     }
   2435 
   2436     private void bindString(SQLiteStatement stmt, int index, String value) {
   2437         if (value == null) {
   2438             stmt.bindNull(index);
   2439         } else {
   2440             stmt.bindString(index, value);
   2441         }
   2442     }
   2443 
   2444     /**
   2445      * Adds index stats into the SQLite database to force it to always use the lookup indexes.
   2446      */
   2447     private void updateSqliteStats(SQLiteDatabase db) {
   2448 
   2449         // Specific stats strings are based on an actual large database after running ANALYZE
   2450         try {
   2451             updateIndexStats(db, Tables.CONTACTS,
   2452                     "contacts_restricted_index", "10000 9000");
   2453             updateIndexStats(db, Tables.CONTACTS,
   2454                     "contacts_has_phone_index", "10000 500");
   2455             updateIndexStats(db, Tables.CONTACTS,
   2456                     "contacts_visible_index", "10000 500 1");
   2457 
   2458             updateIndexStats(db, Tables.RAW_CONTACTS,
   2459                     "raw_contacts_source_id_index", "10000 1 1 1");
   2460             updateIndexStats(db, Tables.RAW_CONTACTS,
   2461                     "raw_contacts_contact_id_index", "10000 2");
   2462 
   2463             updateIndexStats(db, Tables.NAME_LOOKUP,
   2464                     "name_lookup_raw_contact_id_index", "10000 3");
   2465             updateIndexStats(db, Tables.NAME_LOOKUP,
   2466                     "name_lookup_index", "10000 3 2 2 1");
   2467             updateIndexStats(db, Tables.NAME_LOOKUP,
   2468                     "sqlite_autoindex_name_lookup_1", "10000 3 2 1");
   2469 
   2470             updateIndexStats(db, Tables.PHONE_LOOKUP,
   2471                     "phone_lookup_index", "10000 2 2 1");
   2472             updateIndexStats(db, Tables.PHONE_LOOKUP,
   2473                     "phone_lookup_min_match_index", "10000 2 2 1");
   2474 
   2475             updateIndexStats(db, Tables.DATA,
   2476                     "data_mimetype_data1_index", "60000 5000 2");
   2477             updateIndexStats(db, Tables.DATA,
   2478                     "data_raw_contact_id", "60000 10");
   2479 
   2480             updateIndexStats(db, Tables.GROUPS,
   2481                     "groups_source_id_index", "50 1 1 1");
   2482 
   2483             updateIndexStats(db, Tables.NICKNAME_LOOKUP,
   2484                     "sqlite_autoindex_name_lookup_1", "500 2 1");
   2485 
   2486         } catch (SQLException e) {
   2487             Log.e(TAG, "Could not update index stats", e);
   2488         }
   2489     }
   2490 
   2491     /**
   2492      * Stores statistics for a given index.
   2493      *
   2494      * @param stats has the following structure: the first index is the expected size of
   2495      * the table.  The following integer(s) are the expected number of records selected with the
   2496      * index.  There should be one integer per indexed column.
   2497      */
   2498     private void updateIndexStats(SQLiteDatabase db, String table, String index,
   2499             String stats) {
   2500         db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl='" + table + "' AND idx='" + index + "';");
   2501         db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat)"
   2502                 + " VALUES ('" + table + "','" + index + "','" + stats + "');");
   2503     }
   2504 
   2505     @Override
   2506     public synchronized SQLiteDatabase getWritableDatabase() {
   2507         SQLiteDatabase db = super.getWritableDatabase();
   2508         if (mReopenDatabase) {
   2509             mReopenDatabase = false;
   2510             close();
   2511             db = super.getWritableDatabase();
   2512         }
   2513         return db;
   2514     }
   2515 
   2516     /**
   2517      * Wipes all data except mime type and package lookup tables.
   2518      */
   2519     public void wipeData() {
   2520         SQLiteDatabase db = getWritableDatabase();
   2521 
   2522         db.execSQL("DELETE FROM " + Tables.ACCOUNTS + ";");
   2523         db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL)");
   2524 
   2525         db.execSQL("DELETE FROM " + Tables.CONTACTS + ";");
   2526         db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";");
   2527         db.execSQL("DELETE FROM " + Tables.DATA + ";");
   2528         db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";");
   2529         db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";");
   2530         db.execSQL("DELETE FROM " + Tables.GROUPS + ";");
   2531         db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";");
   2532         db.execSQL("DELETE FROM " + Tables.SETTINGS + ";");
   2533         db.execSQL("DELETE FROM " + Tables.ACTIVITIES + ";");
   2534         db.execSQL("DELETE FROM " + Tables.CALLS + ";");
   2535 
   2536         // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP
   2537     }
   2538 
   2539     public NameSplitter createNameSplitter() {
   2540         return new NameSplitter(
   2541                 mContext.getString(com.android.internal.R.string.common_name_prefixes),
   2542                 mContext.getString(com.android.internal.R.string.common_last_name_prefixes),
   2543                 mContext.getString(com.android.internal.R.string.common_name_suffixes),
   2544                 mContext.getString(com.android.internal.R.string.common_name_conjunctions),
   2545                 Locale.getDefault());
   2546     }
   2547 
   2548     /**
   2549      * Return the {@link ApplicationInfo#uid} for the given package name.
   2550      */
   2551     public static int getUidForPackageName(PackageManager pm, String packageName) {
   2552         try {
   2553             ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */);
   2554             return clientInfo.uid;
   2555         } catch (NameNotFoundException e) {
   2556             throw new RuntimeException(e);
   2557         }
   2558     }
   2559 
   2560     /**
   2561      * Perform an internal string-to-integer lookup using the compiled
   2562      * {@link SQLiteStatement} provided, using the in-memory cache to speed up
   2563      * lookups. If a mapping isn't found in cache or database, it will be
   2564      * created. All new, uncached answers are added to the cache automatically.
   2565      *
   2566      * @param query Compiled statement used to query for the mapping.
   2567      * @param insert Compiled statement used to insert a new mapping when no
   2568      *            existing one is found in cache or from query.
   2569      * @param value Value to find mapping for.
   2570      * @param cache In-memory cache of previous answers.
   2571      * @return An unique integer mapping for the given value.
   2572      */
   2573     private long getCachedId(SQLiteStatement query, SQLiteStatement insert,
   2574             String value, HashMap<String, Long> cache) {
   2575         // Try an in-memory cache lookup
   2576         if (cache.containsKey(value)) {
   2577             return cache.get(value);
   2578         }
   2579 
   2580         long id = -1;
   2581         try {
   2582             // Try searching database for mapping
   2583             DatabaseUtils.bindObjectToProgram(query, 1, value);
   2584             id = query.simpleQueryForLong();
   2585         } catch (SQLiteDoneException e) {
   2586             // Nothing found, so try inserting new mapping
   2587             DatabaseUtils.bindObjectToProgram(insert, 1, value);
   2588             id = insert.executeInsert();
   2589         }
   2590 
   2591         if (id != -1) {
   2592             // Cache and return the new answer
   2593             cache.put(value, id);
   2594             return id;
   2595         } else {
   2596             // Otherwise throw if no mapping found or created
   2597             throw new IllegalStateException("Couldn't find or create internal "
   2598                     + "lookup table entry for value " + value);
   2599         }
   2600     }
   2601 
   2602     /**
   2603      * Convert a package name into an integer, using {@link Tables#PACKAGES} for
   2604      * lookups and possible allocation of new IDs as needed.
   2605      */
   2606     public long getPackageId(String packageName) {
   2607         // Make sure compiled statements are ready by opening database
   2608         getReadableDatabase();
   2609         return getCachedId(mPackageQuery, mPackageInsert, packageName, mPackageCache);
   2610     }
   2611 
   2612     /**
   2613      * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for
   2614      * lookups and possible allocation of new IDs as needed.
   2615      */
   2616     public long getMimeTypeId(String mimetype) {
   2617         // Make sure compiled statements are ready by opening database
   2618         getReadableDatabase();
   2619         return getMimeTypeIdNoDbCheck(mimetype);
   2620     }
   2621 
   2622     private long getMimeTypeIdNoDbCheck(String mimetype) {
   2623         return getCachedId(mMimetypeQuery, mMimetypeInsert, mimetype, mMimetypeCache);
   2624     }
   2625 
   2626     /**
   2627      * Find the mimetype for the given {@link Data#_ID}.
   2628      */
   2629     public String getDataMimeType(long dataId) {
   2630         // Make sure compiled statements are ready by opening database
   2631         getReadableDatabase();
   2632         try {
   2633             // Try database query to find mimetype
   2634             DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId);
   2635             String mimetype = mDataMimetypeQuery.simpleQueryForString();
   2636             return mimetype;
   2637         } catch (SQLiteDoneException e) {
   2638             // No valid mapping found, so return null
   2639             return null;
   2640         }
   2641     }
   2642 
   2643     /**
   2644      * Find the mime-type for the given {@link Activities#_ID}.
   2645      */
   2646     public String getActivityMimeType(long activityId) {
   2647         // Make sure compiled statements are ready by opening database
   2648         getReadableDatabase();
   2649         try {
   2650             // Try database query to find mimetype
   2651             DatabaseUtils.bindObjectToProgram(mActivitiesMimetypeQuery, 1, activityId);
   2652             String mimetype = mActivitiesMimetypeQuery.simpleQueryForString();
   2653             return mimetype;
   2654         } catch (SQLiteDoneException e) {
   2655             // No valid mapping found, so return null
   2656             return null;
   2657         }
   2658     }
   2659 
   2660     /**
   2661      * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts.
   2662      */
   2663     public void updateAllVisible() {
   2664         SQLiteDatabase db = getWritableDatabase();
   2665         final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
   2666         String[] selectionArgs = new String[]{String.valueOf(groupMembershipMimetypeId)};
   2667 
   2668         // There are a couple questions that can be asked regarding the
   2669         // following two update statements:
   2670         //
   2671         // Q: Why do we run these two queries separately? They seem like they could be combined.
   2672         // A: This is a result of painstaking experimentation.  Turns out that the most
   2673         // important optimization is to make sure we never update a value to its current value.
   2674         // Changing 0 to 0 is unexpectedly expensive - SQLite actually writes the unchanged
   2675         // rows back to disk.  The other consideration is that the CONTACT_IS_VISIBLE condition
   2676         // is very complex and executing it twice in the same statement ("if contact_visible !=
   2677         // CONTACT_IS_VISIBLE change it to CONTACT_IS_VISIBLE") is more expensive than running
   2678         // two update statements.
   2679         //
   2680         // Q: How come we are using db.update instead of compiled statements?
   2681         // A: This is a limitation of the compiled statement API. It does not return the
   2682         // number of rows changed.  As you will see later in this method we really need
   2683         // to know how many rows have been changed.
   2684 
   2685         // First update contacts that are currently marked as invisible, but need to be visible
   2686         ContentValues values = new ContentValues();
   2687         values.put(Contacts.IN_VISIBLE_GROUP, 1);
   2688         int countMadeVisible = db.update(Tables.CONTACTS, values,
   2689                 Contacts.IN_VISIBLE_GROUP + "=0" + " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=1",
   2690                 selectionArgs);
   2691 
   2692         // Next update contacts that are currently marked as visible, but need to be invisible
   2693         values.put(Contacts.IN_VISIBLE_GROUP, 0);
   2694         int countMadeInvisible = db.update(Tables.CONTACTS, values,
   2695                 Contacts.IN_VISIBLE_GROUP + "=1" + " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=0",
   2696                 selectionArgs);
   2697 
   2698         if (countMadeVisible != 0 || countMadeInvisible != 0) {
   2699             // TODO break out the fields (contact_in_visible_group, sort_key, sort_key_alt) into
   2700             // a separate table.
   2701             // Rationale: The following statement will take a very long time on
   2702             // a large database even though we are only changing one field from 0 to 1 or from
   2703             // 1 to 0.  The reason for the slowness is that SQLite will need to write the whole
   2704             // page even when only one bit on it changes. Changing the visibility of a
   2705             // significant number of contacts will likely read and write almost the entire
   2706             // raw_contacts table.  So, the solution is to break out into a separate table
   2707             // the changing field along with the sort keys used for index-based sorting.
   2708             // That table will occupy a smaller number of pages, so rewriting it would
   2709             // not be as expensive.
   2710             mVisibleUpdateRawContacts.execute();
   2711         }
   2712     }
   2713 
   2714     /**
   2715      * Update {@link Contacts#IN_VISIBLE_GROUP} for a specific contact.
   2716      */
   2717     public void updateContactVisible(long contactId) {
   2718         final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE);
   2719         mVisibleSpecificUpdate.bindLong(1, groupMembershipMimetypeId);
   2720         mVisibleSpecificUpdate.bindLong(2, contactId);
   2721         mVisibleSpecificUpdate.execute();
   2722 
   2723         mVisibleSpecificUpdateRawContacts.bindLong(1, contactId);
   2724         mVisibleSpecificUpdateRawContacts.execute();
   2725     }
   2726 
   2727     /**
   2728      * Returns contact ID for the given contact or zero if it is NULL.
   2729      */
   2730     public long getContactId(long rawContactId) {
   2731         getReadableDatabase();
   2732         try {
   2733             DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId);
   2734             return mContactIdQuery.simpleQueryForLong();
   2735         } catch (SQLiteDoneException e) {
   2736             // No valid mapping found, so return 0
   2737             return 0;
   2738         }
   2739     }
   2740 
   2741     public int getAggregationMode(long rawContactId) {
   2742         getReadableDatabase();
   2743         try {
   2744             DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId);
   2745             return (int)mAggregationModeQuery.simpleQueryForLong();
   2746         } catch (SQLiteDoneException e) {
   2747             // No valid row found, so return "disabled"
   2748             return RawContacts.AGGREGATION_MODE_DISABLED;
   2749         }
   2750     }
   2751 
   2752     public void buildPhoneLookupAndRawContactQuery(SQLiteQueryBuilder qb, String number) {
   2753         String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
   2754         qb.setTables(Tables.DATA_JOIN_RAW_CONTACTS +
   2755                 " JOIN " + Tables.PHONE_LOOKUP
   2756                 + " ON(" + DataColumns.CONCRETE_ID + "=" + PhoneLookupColumns.DATA_ID + ")");
   2757 
   2758         StringBuilder sb = new StringBuilder();
   2759         sb.append(PhoneLookupColumns.MIN_MATCH + "='");
   2760         sb.append(minMatch);
   2761         sb.append("' AND PHONE_NUMBERS_EQUAL(data." + Phone.NUMBER + ", ");
   2762         DatabaseUtils.appendEscapedSQLString(sb, number);
   2763         sb.append(mUseStrictPhoneNumberComparison ? ", 1)" : ", 0)");
   2764 
   2765         qb.appendWhere(sb.toString());
   2766     }
   2767 
   2768     public void buildPhoneLookupAndContactQuery(SQLiteQueryBuilder qb, String number) {
   2769         String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
   2770         StringBuilder sb = new StringBuilder();
   2771         appendPhoneLookupTables(sb, minMatch, true);
   2772         qb.setTables(sb.toString());
   2773 
   2774         sb = new StringBuilder();
   2775         appendPhoneLookupSelection(sb, number);
   2776         qb.appendWhere(sb.toString());
   2777     }
   2778 
   2779     public String buildPhoneLookupAsNestedQuery(String number) {
   2780         StringBuilder sb = new StringBuilder();
   2781         final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number);
   2782         sb.append("(SELECT DISTINCT raw_contact_id" + " FROM ");
   2783         appendPhoneLookupTables(sb, minMatch, false);
   2784         sb.append(" WHERE ");
   2785         appendPhoneLookupSelection(sb, number);
   2786         sb.append(")");
   2787         return sb.toString();
   2788     }
   2789 
   2790     private void appendPhoneLookupTables(StringBuilder sb, final String minMatch,
   2791             boolean joinContacts) {
   2792         sb.append(Tables.RAW_CONTACTS);
   2793         if (joinContacts) {
   2794             sb.append(" JOIN " + getContactView() + " contacts_view"
   2795                     + " ON (contacts_view._id = raw_contacts.contact_id)");
   2796         }
   2797         sb.append(", (SELECT data_id FROM phone_lookup "
   2798                 + "WHERE (" + Tables.PHONE_LOOKUP + "." + PhoneLookupColumns.MIN_MATCH + " = '");
   2799         sb.append(minMatch);
   2800         sb.append("')) AS lookup, " + Tables.DATA);
   2801     }
   2802 
   2803     private void appendPhoneLookupSelection(StringBuilder sb, String number) {
   2804         sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id"
   2805                 + " AND PHONE_NUMBERS_EQUAL(data." + Phone.NUMBER + ", ");
   2806         DatabaseUtils.appendEscapedSQLString(sb, number);
   2807         sb.append(mUseStrictPhoneNumberComparison ? ", 1)" : ", 0)");
   2808     }
   2809 
   2810     public String getUseStrictPhoneNumberComparisonParameter() {
   2811         return mUseStrictPhoneNumberComparison ? "1" : "0";
   2812     }
   2813 
   2814     /**
   2815      * Loads common nickname mappings into the database.
   2816      */
   2817     private void loadNicknameLookupTable(SQLiteDatabase db) {
   2818         db.execSQL("DELETE FROM " + Tables.NICKNAME_LOOKUP);
   2819 
   2820         String[] strings = mContext.getResources().getStringArray(
   2821                 com.android.internal.R.array.common_nicknames);
   2822         if (strings == null || strings.length == 0) {
   2823             return;
   2824         }
   2825 
   2826         SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO "
   2827                 + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + ","
   2828                 + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)");
   2829 
   2830         try {
   2831             for (int clusterId = 0; clusterId < strings.length; clusterId++) {
   2832                 String[] names = strings[clusterId].split(",");
   2833                 for (int j = 0; j < names.length; j++) {
   2834                     String name = NameNormalizer.normalize(names[j]);
   2835                     try {
   2836                         DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name);
   2837                         DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2,
   2838                                 String.valueOf(clusterId));
   2839                         nicknameLookupInsert.executeInsert();
   2840                     } catch (SQLiteException e) {
   2841 
   2842                         // Print the exception and keep going - this is not a fatal error
   2843                         Log.e(TAG, "Cannot insert nickname: " + names[j], e);
   2844                     }
   2845                 }
   2846             }
   2847         } finally {
   2848             nicknameLookupInsert.close();
   2849         }
   2850     }
   2851 
   2852     public static void copyStringValue(ContentValues toValues, String toKey,
   2853             ContentValues fromValues, String fromKey) {
   2854         if (fromValues.containsKey(fromKey)) {
   2855             toValues.put(toKey, fromValues.getAsString(fromKey));
   2856         }
   2857     }
   2858 
   2859     public static void copyLongValue(ContentValues toValues, String toKey,
   2860             ContentValues fromValues, String fromKey) {
   2861         if (fromValues.containsKey(fromKey)) {
   2862             long longValue;
   2863             Object value = fromValues.get(fromKey);
   2864             if (value instanceof Boolean) {
   2865                 if ((Boolean)value) {
   2866                     longValue = 1;
   2867                 } else {
   2868                     longValue = 0;
   2869                 }
   2870             } else if (value instanceof String) {
   2871                 longValue = Long.parseLong((String)value);
   2872             } else {
   2873                 longValue = ((Number)value).longValue();
   2874             }
   2875             toValues.put(toKey, longValue);
   2876         }
   2877     }
   2878 
   2879     public SyncStateContentProviderHelper getSyncState() {
   2880         return mSyncState;
   2881     }
   2882 
   2883     /**
   2884      * Delete the aggregate contact if it has no constituent raw contacts other
   2885      * than the supplied one.
   2886      */
   2887     public void removeContactIfSingleton(long rawContactId) {
   2888         SQLiteDatabase db = getWritableDatabase();
   2889 
   2890         // Obtain contact ID from the supplied raw contact ID
   2891         String contactIdFromRawContactId = "(SELECT " + RawContacts.CONTACT_ID + " FROM "
   2892                 + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=" + rawContactId + ")";
   2893 
   2894         // Find other raw contacts in the same aggregate contact
   2895         String otherRawContacts = "(SELECT contacts1." + RawContacts._ID + " FROM "
   2896                 + Tables.RAW_CONTACTS + " contacts1 JOIN " + Tables.RAW_CONTACTS + " contacts2 ON ("
   2897                 + "contacts1." + RawContacts.CONTACT_ID + "=contacts2." + RawContacts.CONTACT_ID
   2898                 + ") WHERE contacts1." + RawContacts._ID + "!=" + rawContactId + ""
   2899                 + " AND contacts2." + RawContacts._ID + "=" + rawContactId + ")";
   2900 
   2901         db.execSQL("DELETE FROM " + Tables.CONTACTS
   2902                 + " WHERE " + Contacts._ID + "=" + contactIdFromRawContactId
   2903                 + " AND NOT EXISTS " + otherRawContacts + ";");
   2904     }
   2905 
   2906     /**
   2907      * Returns the value from the {@link Tables#PROPERTIES} table.
   2908      */
   2909     public String getProperty(String key, String defaultValue) {
   2910         Cursor cursor = getReadableDatabase().query(Tables.PROPERTIES,
   2911                 new String[]{PropertiesColumns.PROPERTY_VALUE},
   2912                 PropertiesColumns.PROPERTY_KEY + "=?",
   2913                 new String[]{key}, null, null, null);
   2914         String value = null;
   2915         try {
   2916             if (cursor.moveToFirst()) {
   2917                 value = cursor.getString(0);
   2918             }
   2919         } finally {
   2920             cursor.close();
   2921         }
   2922 
   2923         return value != null ? value : defaultValue;
   2924     }
   2925 
   2926     /**
   2927      * Stores a key-value pair in the {@link Tables#PROPERTIES} table.
   2928      */
   2929     public void setProperty(String key, String value) {
   2930         ContentValues values = new ContentValues();
   2931         values.put(PropertiesColumns.PROPERTY_KEY, key);
   2932         values.put(PropertiesColumns.PROPERTY_VALUE, value);
   2933         getWritableDatabase().replace(Tables.PROPERTIES, null, values);
   2934     }
   2935 
   2936     /**
   2937      * Check if {@link Binder#getCallingUid()} should be allowed access to
   2938      * {@link RawContacts#IS_RESTRICTED} data.
   2939      */
   2940     boolean hasAccessToRestrictedData() {
   2941         final PackageManager pm = mContext.getPackageManager();
   2942         final String[] callerPackages = pm.getPackagesForUid(Binder.getCallingUid());
   2943 
   2944         // Has restricted access if caller matches any packages
   2945         for (String callerPackage : callerPackages) {
   2946             if (hasAccessToRestrictedData(callerPackage)) {
   2947                 return true;
   2948             }
   2949         }
   2950         return false;
   2951     }
   2952 
   2953     /**
   2954      * Check if requestingPackage should be allowed access to
   2955      * {@link RawContacts#IS_RESTRICTED} data.
   2956      */
   2957     boolean hasAccessToRestrictedData(String requestingPackage) {
   2958         if (mUnrestrictedPackages != null) {
   2959             for (String allowedPackage : mUnrestrictedPackages) {
   2960                 if (allowedPackage.equals(requestingPackage)) {
   2961                     return true;
   2962                 }
   2963             }
   2964         }
   2965         return false;
   2966     }
   2967 
   2968     public String getDataView() {
   2969         return getDataView(false);
   2970     }
   2971 
   2972     public String getDataView(boolean requireRestrictedView) {
   2973         return (hasAccessToRestrictedData() && !requireRestrictedView) ?
   2974                 Views.DATA_ALL : Views.DATA_RESTRICTED;
   2975     }
   2976 
   2977     public String getRawContactView() {
   2978         return getRawContactView(false);
   2979     }
   2980 
   2981     public String getRawContactView(boolean requireRestrictedView) {
   2982         return (hasAccessToRestrictedData() && !requireRestrictedView) ?
   2983                 Views.RAW_CONTACTS_ALL : Views.RAW_CONTACTS_RESTRICTED;
   2984     }
   2985 
   2986     public String getContactView() {
   2987         return getContactView(false);
   2988     }
   2989 
   2990     public String getContactView(boolean requireRestrictedView) {
   2991         return (hasAccessToRestrictedData() && !requireRestrictedView) ?
   2992                 Views.CONTACTS_ALL : Views.CONTACTS_RESTRICTED;
   2993     }
   2994 
   2995     public String getGroupView() {
   2996         return Views.GROUPS_ALL;
   2997     }
   2998 
   2999     public String getContactEntitiesView() {
   3000         return getContactEntitiesView(false);
   3001     }
   3002 
   3003     public String getContactEntitiesView(boolean requireRestrictedView) {
   3004         return (hasAccessToRestrictedData() && !requireRestrictedView) ?
   3005                 Tables.CONTACT_ENTITIES : Tables.CONTACT_ENTITIES_RESTRICTED;
   3006     }
   3007 
   3008     /**
   3009      * Test if any of the columns appear in the given projection.
   3010      */
   3011     public boolean isInProjection(String[] projection, String... columns) {
   3012         if (projection == null) {
   3013             return true;
   3014         }
   3015 
   3016         // Optimized for a single-column test
   3017         if (columns.length == 1) {
   3018             String column = columns[0];
   3019             for (String test : projection) {
   3020                 if (column.equals(test)) {
   3021                     return true;
   3022                 }
   3023             }
   3024         } else {
   3025             for (String test : projection) {
   3026                 for (String column : columns) {
   3027                     if (column.equals(test)) {
   3028                         return true;
   3029                     }
   3030                 }
   3031             }
   3032         }
   3033         return false;
   3034     }
   3035 
   3036     /**
   3037      * Returns a detailed exception message for the supplied URI.  It includes the calling
   3038      * user and calling package(s).
   3039      */
   3040     public String exceptionMessage(Uri uri) {
   3041         return exceptionMessage(null, uri);
   3042     }
   3043 
   3044     /**
   3045      * Returns a detailed exception message for the supplied URI.  It includes the calling
   3046      * user and calling package(s).
   3047      */
   3048     public String exceptionMessage(String message, Uri uri) {
   3049         StringBuilder sb = new StringBuilder();
   3050         if (message != null) {
   3051             sb.append(message).append("; ");
   3052         }
   3053         sb.append("URI: ").append(uri);
   3054         final PackageManager pm = mContext.getPackageManager();
   3055         int callingUid = Binder.getCallingUid();
   3056         sb.append(", calling user: ");
   3057         String userName = pm.getNameForUid(callingUid);
   3058         if (userName != null) {
   3059             sb.append(userName);
   3060         } else {
   3061             sb.append(callingUid);
   3062         }
   3063 
   3064         final String[] callerPackages = pm.getPackagesForUid(callingUid);
   3065         if (callerPackages != null && callerPackages.length > 0) {
   3066             if (callerPackages.length == 1) {
   3067                 sb.append(", calling package:");
   3068                 sb.append(callerPackages[0]);
   3069             } else {
   3070                 sb.append(", calling package is one of: [");
   3071                 for (int i = 0; i < callerPackages.length; i++) {
   3072                     if (i != 0) {
   3073                         sb.append(", ");
   3074                     }
   3075                     sb.append(callerPackages[i]);
   3076                 }
   3077                 sb.append("]");
   3078             }
   3079         }
   3080 
   3081         return sb.toString();
   3082     }
   3083 }
   3084