diff options
author | Ben Gilad <gilad@google.com> | 2014-04-03 13:47:03 -0700 |
---|---|---|
committer | Ben Gilad <gilad@google.com> | 2014-04-04 14:21:08 -0700 |
commit | a157bdc5a6bc0b4bdf889d0ed6475571bc547012 (patch) | |
tree | f28d447653d6453525d355d990df5dd85863e80a /src/com/android/providers/contacts/ContactsDatabaseHelper.java | |
parent | 53ab19d6d135d948620f3a648aeded79a8e7e761 (diff) | |
download | packages_providers_ContactsProvider-a157bdc5a6bc0b4bdf889d0ed6475571bc547012.zip packages_providers_ContactsProvider-a157bdc5a6bc0b4bdf889d0ed6475571bc547012.tar.gz packages_providers_ContactsProvider-a157bdc5a6bc0b4bdf889d0ed6475571bc547012.tar.bz2 |
One more cleanup CL before the change to remove/replace mValues.
Shouldn't include any functional changes, mostly focused on
dead-code removal, also removing unused/unnecessary code/logic,
tightening up access modifiers (e.g. using private vs. public) as
much as possible, using Java's built-in iteration when applicable,
grouping variables by static/non-static and access modifiers (e.g.
private members last, etc).
Change-Id: I4fa6af136b5da0ae6183eadce4798746b18813cb
Diffstat (limited to 'src/com/android/providers/contacts/ContactsDatabaseHelper.java')
-rw-r--r-- | src/com/android/providers/contacts/ContactsDatabaseHelper.java | 847 |
1 files changed, 394 insertions, 453 deletions
diff --git a/src/com/android/providers/contacts/ContactsDatabaseHelper.java b/src/com/android/providers/contacts/ContactsDatabaseHelper.java index 2e929a3..82cf310 100644 --- a/src/com/android/providers/contacts/ContactsDatabaseHelper.java +++ b/src/com/android/providers/contacts/ContactsDatabaseHelper.java @@ -35,7 +35,6 @@ import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteStatement; -import android.location.CountryDetector; import android.net.Uri; import android.os.Binder; import android.os.Bundle; @@ -97,7 +96,6 @@ import libcore.icu.ICU; * Provides handy methods for maintaining package and mime-type lookup tables. */ public class ContactsDatabaseHelper extends SQLiteOpenHelper { - private static final String TAG = "ContactsDatabaseHelper"; /** * Contacts DB version ranges: @@ -118,9 +116,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { */ static final int DATABASE_VERSION = 901; - private static final String DATABASE_NAME = "contacts2.db"; - private static final String DATABASE_PRESENCE = "presence_db"; - public interface Tables { public static final String CONTACTS = "contacts"; public static final String DELETED_CONTACTS = "deleted_contacts"; @@ -159,12 +154,11 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { DATA, GROUPS, CALLS, - DIRECTORIES - }; + DIRECTORIES}; /** - * For {@link ContactsContract.DataUsageFeedback}. The table structure itself - * is not exposed outside. + * For {@link android.provider.ContactsContract.DataUsageFeedback}. The table structure + * itself is not exposed outside. */ public static final String DATA_USAGE_STAT = "data_usage_stat"; @@ -304,6 +298,24 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { public static final String STREAM_ITEMS = "view_stream_items"; } + public interface Projections { + String[] ID = new String[] {BaseColumns._ID}; + String[] LITERAL_ONE = new String[] {"1"}; + } + + /** + * Property names for {@link ContactsDatabaseHelper#getProperty} and + * {@link ContactsDatabaseHelper#setProperty}. + */ + public interface DbProperties { + String DIRECTORY_SCAN_COMPLETE = "directoryScanComplete"; + String AGGREGATION_ALGORITHM = "aggregation_v2"; + String KNOWN_ACCOUNTS = "known_accounts"; + String ICU_VERSION = "icu_version"; + String LOCALE = "locale"; + String DATABASE_TIME_CREATED = "database_time_created"; + } + public interface Clauses { final String HAVING_NO_GROUPS = "COUNT(" + DataColumns.CONCRETE_GROUP_ID + ") == 0"; @@ -474,7 +486,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { public static final String CONCRETE_PACKAGE_ID = Tables.DATA + "." + PACKAGE_ID; } - // Used only for legacy API support + // Used only for legacy API support. public interface ExtensionsColumns { public static final String NAME = Data.DATA1; public static final String VALUE = Data.DATA2; @@ -522,23 +534,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { public static final String NAME_TYPE = "name_type"; } - public final static class NameLookupType { - public static final int NAME_EXACT = 0; - public static final int NAME_VARIANT = 1; - public static final int NAME_COLLATION_KEY = 2; - public static final int NICKNAME = 3; - public static final int EMAIL_BASED_NICKNAME = 4; - - // This is the highest name lookup type code plus one - public static final int TYPE_COUNT = 5; - - public static boolean isBasedOnStructuredName(int nameLookupType) { - return nameLookupType == NameLookupType.NAME_EXACT - || nameLookupType == NameLookupType.NAME_VARIANT - || nameLookupType == NameLookupType.NAME_COLLATION_KEY; - } - } - public interface PackagesColumns { public static final String _ID = BaseColumns._ID; public static final String PACKAGE = "package"; @@ -579,7 +574,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { public interface AggregatedPresenceColumns { String CONTACT_ID = "presence_contact_id"; - String CONCRETE_CONTACT_ID = Tables.AGGREGATED_PRESENCE + "." + CONTACT_ID; } @@ -665,11 +659,11 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { String CONCRETE_DATA_SET = Tables.ACCOUNTS + "." + DATA_SET; } - public static final class DirectoryColumns { + public interface DirectoryColumns { public static final String TYPE_RESOURCE_NAME = "typeResourceName"; } - public static final class SearchIndexColumns { + public interface SearchIndexColumns { public static final String CONTACT_ID = "contact_id"; public static final String CONTENT = "content"; public static final String NAME = "name"; @@ -679,7 +673,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { /** * Private table for calculating per-contact-method ranking. */ - public static final class DataUsageStatColumns { + public interface DataUsageStatColumns { /** type: INTEGER (long) */ public static final String _ID = "stat_id"; public static final String CONCRETE_ID = Tables.DATA_USAGE_STAT + "." + _ID; @@ -706,37 +700,234 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { /** * Integer values for USAGE_TYPE. * - * @see ContactsContract.DataUsageFeedback#USAGE_TYPE + * @see android.provider.ContactsContract.DataUsageFeedback#USAGE_TYPE */ public static final int USAGE_TYPE_INT_CALL = 0; public static final int USAGE_TYPE_INT_LONG_TEXT = 1; public static final int USAGE_TYPE_INT_SHORT_TEXT = 2; } - public interface Projections { - String[] ID = new String[] {BaseColumns._ID}; - String[] LITERAL_ONE = new String[] {"1"}; + private interface EmailQuery { + public static final String TABLE = Tables.DATA; + + public static final String SELECTION = + DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; + + public static final String COLUMNS[] = { + Email._ID, + Email.RAW_CONTACT_ID, + Email.ADDRESS}; + + public static final int ID = 0; + public static final int RAW_CONTACT_ID = 1; + public static final int ADDRESS = 2; } - /** - * Property names for {@link ContactsDatabaseHelper#getProperty} and - * {@link ContactsDatabaseHelper#setProperty}. - */ - public interface DbProperties { - String DIRECTORY_SCAN_COMPLETE = "directoryScanComplete"; - String AGGREGATION_ALGORITHM = "aggregation_v2"; - String KNOWN_ACCOUNTS = "known_accounts"; - String ICU_VERSION = "icu_version"; - String LOCALE = "locale"; - String DATABASE_TIME_CREATED = "database_time_created"; + private interface Upgrade303Query { + public static final String TABLE = Tables.DATA; + + public static final String SELECTION = + DataColumns.MIMETYPE_ID + "=?" + + " AND " + Data._ID + " NOT IN " + + "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" + + " AND " + Data.DATA1 + " NOT NULL"; + + public static final String COLUMNS[] = { + Data._ID, + Data.RAW_CONTACT_ID, + Data.DATA1, + }; + + public static final int ID = 0; + public static final int RAW_CONTACT_ID = 1; + public static final int DATA1 = 2; + } + + private interface StructuredNameQuery { + public static final String TABLE = Tables.DATA; + + public static final String SELECTION = + DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; + + public static final String COLUMNS[] = { + StructuredName._ID, + StructuredName.RAW_CONTACT_ID, + StructuredName.DISPLAY_NAME, + }; + + public static final int ID = 0; + public static final int RAW_CONTACT_ID = 1; + public static final int DISPLAY_NAME = 2; + } + + private interface NicknameQuery { + public static final String TABLE = Tables.DATA; + + public static final String SELECTION = + DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; + + public static final String COLUMNS[] = { + Nickname._ID, + Nickname.RAW_CONTACT_ID, + Nickname.NAME}; + + public static final int ID = 0; + public static final int RAW_CONTACT_ID = 1; + public static final int NAME = 2; + } + + private interface StructName205Query { + String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; + String COLUMNS[] = { + DataColumns.CONCRETE_ID, + Data.RAW_CONTACT_ID, + RawContacts.DISPLAY_NAME_SOURCE, + RawContacts.DISPLAY_NAME_PRIMARY, + StructuredName.PREFIX, + StructuredName.GIVEN_NAME, + StructuredName.MIDDLE_NAME, + StructuredName.FAMILY_NAME, + StructuredName.SUFFIX, + StructuredName.PHONETIC_FAMILY_NAME, + StructuredName.PHONETIC_MIDDLE_NAME, + StructuredName.PHONETIC_GIVEN_NAME, + }; + + int ID = 0; + int RAW_CONTACT_ID = 1; + int DISPLAY_NAME_SOURCE = 2; + int DISPLAY_NAME = 3; + int PREFIX = 4; + int GIVEN_NAME = 5; + int MIDDLE_NAME = 6; + int FAMILY_NAME = 7; + int SUFFIX = 8; + int PHONETIC_FAMILY_NAME = 9; + int PHONETIC_MIDDLE_NAME = 10; + int PHONETIC_GIVEN_NAME = 11; + } + + private interface RawContactNameQuery { + public static final String RAW_SQL = + "SELECT " + + DataColumns.MIMETYPE_ID + "," + + Data.IS_PRIMARY + "," + + Data.DATA1 + "," + + Data.DATA2 + "," + + Data.DATA3 + "," + + Data.DATA4 + "," + + Data.DATA5 + "," + + Data.DATA6 + "," + + Data.DATA7 + "," + + Data.DATA8 + "," + + Data.DATA9 + "," + + Data.DATA10 + "," + + Data.DATA11 + + " FROM " + Tables.DATA + + " WHERE " + Data.RAW_CONTACT_ID + "=?" + + " AND (" + Data.DATA1 + " NOT NULL OR " + + Data.DATA8 + " NOT NULL OR " + + Data.DATA9 + " NOT NULL OR " + + Data.DATA10 + " NOT NULL OR " + // Phonetic name not empty + Organization.TITLE + " NOT NULL)"; + + public static final int MIMETYPE = 0; + public static final int IS_PRIMARY = 1; + public static final int DATA1 = 2; + public static final int GIVEN_NAME = 3; // data2 + public static final int FAMILY_NAME = 4; // data3 + public static final int PREFIX = 5; // data4 + public static final int TITLE = 5; // data4 + public static final int MIDDLE_NAME = 6; // data5 + public static final int SUFFIX = 7; // data6 + public static final int PHONETIC_GIVEN_NAME = 8; // data7 + public static final int PHONETIC_MIDDLE_NAME = 9; // data8 + public static final int ORGANIZATION_PHONETIC_NAME = 9; // data8 + public static final int PHONETIC_FAMILY_NAME = 10; // data9 + public static final int FULL_NAME_STYLE = 11; // data10 + public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11; // data10 + public static final int PHONETIC_NAME_STYLE = 12; // data11 } + private interface Organization205Query { + String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; + String COLUMNS[] = { + DataColumns.CONCRETE_ID, + Data.RAW_CONTACT_ID, + Organization.COMPANY, + Organization.PHONETIC_NAME, + }; + + int ID = 0; + int RAW_CONTACT_ID = 1; + int COMPANY = 2; + int PHONETIC_NAME = 3; + } + + public final static class NameLookupType { + public static final int NAME_EXACT = 0; + public static final int NAME_VARIANT = 1; + public static final int NAME_COLLATION_KEY = 2; + public static final int NICKNAME = 3; + public static final int EMAIL_BASED_NICKNAME = 4; + + // The highest name-lookup type plus one. + public static final int TYPE_COUNT = 5; + + public static boolean isBasedOnStructuredName(int nameLookupType) { + return nameLookupType == NameLookupType.NAME_EXACT + || nameLookupType == NameLookupType.NAME_VARIANT + || nameLookupType == NameLookupType.NAME_COLLATION_KEY; + } + } + + private class StructuredNameLookupBuilder extends NameLookupBuilder { + // NOTE(gilad): Is in intentional that we don't use the declaration on L960? + private final SQLiteStatement mNameLookupInsert; + private final CommonNicknameCache mCommonNicknameCache; + + public StructuredNameLookupBuilder(NameSplitter splitter, + CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) { + + super(splitter); + this.mCommonNicknameCache = commonNicknameCache; + this.mNameLookupInsert = nameLookupInsert; + } + + @Override + protected void insertNameLookup( + long rawContactId, long dataId, int lookupType, String name) { + + if (!TextUtils.isEmpty(name)) { + ContactsDatabaseHelper.this.insertNormalizedNameLookup( + mNameLookupInsert, rawContactId, dataId, lookupType, name); + } + } + + @Override + protected String[] getCommonNicknameClusters(String normalizedName) { + return mCommonNicknameCache.getCommonNicknameClusters(normalizedName); + } + } + + private static final String TAG = "ContactsDatabaseHelper"; + + private static final String DATABASE_NAME = "contacts2.db"; + private static final String DATABASE_PRESENCE = "presence_db"; + + private static ContactsDatabaseHelper sSingleton = null; + /** In-memory cache of previously found MIME-type mappings */ private final HashMap<String, Long> mMimetypeCache = new HashMap<String, Long>(); /** In-memory cache the packages table */ private final HashMap<String, Long> mPackageCache = new HashMap<String, Long>(); + private final Context mContext; + private final boolean mDatabaseOptimizationEnabled; + private final SyncStateContentProviderHelper mSyncState; + private final CountryMonitor mCountryMonitor; + private long mMimeTypeIdEmail; private long mMimeTypeIdIm; private long mMimeTypeIdNickname; @@ -751,13 +942,13 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { private SQLiteStatement mAggregationModeQuery; private SQLiteStatement mDataMimetypeQuery; - /** Precompiled sql statement for setting a data record to the primary. */ + /** Precompiled SQL statement for setting a data record to the primary. */ private SQLiteStatement mSetPrimaryStatement; - /** Precompiled sql statement for setting a data record to the super primary. */ + /** Precompiled SQL statement for setting a data record to the super primary. */ private SQLiteStatement mSetSuperPrimaryStatement; - /** Precompiled sql statement for clearing super primary of a single record. */ + /** Precompiled SQL statement for clearing super primary of a single record. */ private SQLiteStatement mClearSuperPrimaryStatement; - /** Precompiled sql statement for updating a contact display name */ + /** Precompiled SQL statement for updating a contact display name */ private SQLiteStatement mRawContactDisplayNameUpdate; private SQLiteStatement mNameLookupInsert; @@ -770,14 +961,8 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { private SQLiteStatement mResetNameVerifiedForOtherRawContacts; private SQLiteStatement mContactInDefaultDirectoryQuery; - private final Context mContext; - private final boolean mDatabaseOptimizationEnabled; - private final SyncStateContentProviderHelper mSyncState; - private final CountryMonitor mCountryMonitor; private StringBuilder mSb = new StringBuilder(); - private static ContactsDatabaseHelper sSingleton = null; - private boolean mUseStrictPhoneNumberComparison; private String[] mSelectionArgs1 = new String[1]; @@ -809,9 +994,8 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { mContext = context; mSyncState = new SyncStateContentProviderHelper(); mCountryMonitor = new CountryMonitor(context); - mUseStrictPhoneNumberComparison = - resources.getBoolean( - com.android.internal.R.bool.config_use_strict_phone_number_comparation); + mUseStrictPhoneNumberComparison = resources.getBoolean( + com.android.internal.R.bool.config_use_strict_phone_number_comparation); } public SQLiteDatabase getDatabase(boolean writable) { @@ -1177,7 +1361,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP + " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");"); - // Private name/nickname table used for lookup + // Private name/nickname table used for lookup. db.execSQL("CREATE TABLE " + Tables.NAME_LOOKUP + " (" + NameLookupColumns.DATA_ID + " INTEGER REFERENCES data(_id) NOT NULL," + @@ -1205,7 +1389,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { NicknameLookupColumns.CLUSTER + ");"); - // Groups table + // Groups table. db.execSQL("CREATE TABLE " + Tables.GROUPS + " (" + Groups._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + GroupsColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," + @@ -1352,7 +1536,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { // Set sequence starts. initializeAutoIncrementSequences(db); - // Add the legacy API support views, etc + // Add the legacy API support views, etc. LegacyApiSupport.createDatabase(db); if (mDatabaseOptimizationEnabled) { @@ -1416,9 +1600,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { private void createContactsTriggers(SQLiteDatabase db) { - /* - * Automatically delete Data rows when a raw contact is deleted. - */ + // Automatically delete Data rows when a raw contact is deleted. db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;"); db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted " + " BEFORE DELETE ON " + Tables.RAW_CONTACTS @@ -1452,11 +1634,8 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;"); db.execSQL("DROP TRIGGER IF EXISTS raw_contacts_times_contacted;"); - /* - * Triggers that update {@link RawContacts#VERSION} when the contact is - * marked for deletion or any time a data row is inserted, updated or - * deleted. - */ + // Triggers that update {@link RawContacts#VERSION} when the contact is marked for deletion + // or any time a data row is inserted, updated or deleted. db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;"); db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted " + " AFTER UPDATE ON " + Tables.RAW_CONTACTS @@ -1504,14 +1683,14 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { + " WHERE " + Groups._ID + "=OLD." + Groups._ID + ";" + " END"); - // Update DEFAULT_FILTER table per AUTO_ADD column update. - // See also upgradeToVersion411(). + // Update DEFAULT_FILTER table per AUTO_ADD column update, see upgradeToVersion411. final String insertContactsWithoutAccount = ( " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " SELECT " + RawContacts.CONTACT_ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + Clauses.LOCAL_ACCOUNT_ID + ";"); + final String insertContactsWithAccountNoDefaultGroup = ( " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " SELECT " + RawContacts.CONTACT_ID + @@ -1522,6 +1701,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_ID + " = " + GroupsColumns.CONCRETE_ACCOUNT_ID + " AND " + Groups.AUTO_ADD + " != 0" + ");"); + final String insertContactsWithAccountDefaultGroup = ( " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " SELECT " + RawContacts.CONTACT_ID + @@ -2104,7 +2284,8 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion == 206) { - upgradeToVersion300(db); + // Fix for the bug where name lookup records for organizations would get removed by + // unrelated updates of the data rows. No longer needed. oldVersion = 300; } @@ -2149,7 +2330,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { oldVersion = 308; } - // Gingerbread upgrades + // Gingerbread upgrades. if (oldVersion < 350) { upgradeViewsAndTriggers = true; oldVersion = 351; @@ -2165,7 +2346,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { oldVersion = 353; } - // Honeycomb upgrades + // Honeycomb upgrades. if (oldVersion < 400) { upgradeViewsAndTriggers = true; upgradeToVersion400(db); @@ -2212,8 +2393,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion == 407) { - // Obsolete - oldVersion = 408; + oldVersion = 408; // Obsolete. } if (oldVersion == 408) { @@ -2233,7 +2413,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion == 411) { - // Same upgrade as 353, only on Honeycomb devices + // Same upgrade as 353, only on Honeycomb devices. upgradeToVersion353(db); oldVersion = 412; } @@ -2264,7 +2444,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { oldVersion = 417; } - // Honeycomb-MR1 upgrades + // Honeycomb-MR1 upgrades. if (oldVersion < 500) { upgradeSearchIndex = true; } @@ -2292,7 +2472,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion < 600) { - upgradeToVersion600(db); + // This change used to add the profile raw contact ID to the Accounts table. That + // column is no longer needed (as of version 614) since the profile records are stored in + // a separate copy of the database for security reasons. So this change is now a no-op. upgradeViewsAndTriggers = true; oldVersion = 600; } @@ -2319,7 +2501,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { if (oldVersion < 605) { upgradeViewsAndTriggers = true; - upgradeToVersion605(db); + // This version used to create the stream item and stream item photos tables, but + // a newer version of those tables is created in version 609 below. So omitting the + // creation in this upgrade step to avoid a create->drop->create. oldVersion = 605; } @@ -2332,7 +2516,10 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { if (oldVersion < 607) { upgradeViewsAndTriggers = true; - upgradeToVersion607(db); + // We added "action" and "action_uri" to groups here, but realized this was not a smart + // move. This upgrade step has been removed (all dogfood phones that executed this step + // will have those columns, but that shouldn't hurt. Unfortunately, SQLite makes it + // hard to remove columns). oldVersion = 607; } @@ -2343,7 +2530,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion < 609) { - upgradeToVersion609(db); + // This version used to create the stream item and stream item photos tables, but a + // newer version of those tables is created in version 613 below. So omitting the + // creation in this upgrade step to avoid a create->drop->create. oldVersion = 609; } @@ -2370,7 +2559,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion < 614) { - // this creates the view "view_stream_items" + // This creates the "view_stream_items" view. upgradeViewsAndTriggers = true; oldVersion = 614; } @@ -2381,7 +2570,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion < 616) { - // this updates the "view_stream_items" view + // This updates the "view_stream_items" view. upgradeViewsAndTriggers = true; oldVersion = 616; } @@ -2421,13 +2610,13 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } if (oldVersion < 623) { - // change FTS to normalize names using collation key + // Change FTS to normalize names using collation key. upgradeSearchIndex = true; oldVersion = 623; } if (oldVersion < 624) { - // Upgraded the sqlite index stats + // Upgraded the SQLite index stats. upgradeViewsAndTriggers = true; oldVersion = 624; } @@ -2615,7 +2804,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { // Populate the new column Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA + " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")", - new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null); + new String[] {Data._ID, Phone.NUMBER}, null, null, null, null, null); try { while (c.moveToNext()) { long dataId = c.getLong(0); @@ -2748,43 +2937,10 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { ");"); } - private interface StructName205Query { - String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; - - String COLUMNS[] = { - DataColumns.CONCRETE_ID, - Data.RAW_CONTACT_ID, - RawContacts.DISPLAY_NAME_SOURCE, - RawContacts.DISPLAY_NAME_PRIMARY, - StructuredName.PREFIX, - StructuredName.GIVEN_NAME, - StructuredName.MIDDLE_NAME, - StructuredName.FAMILY_NAME, - StructuredName.SUFFIX, - StructuredName.PHONETIC_FAMILY_NAME, - StructuredName.PHONETIC_MIDDLE_NAME, - StructuredName.PHONETIC_GIVEN_NAME, - }; - - int ID = 0; - int RAW_CONTACT_ID = 1; - int DISPLAY_NAME_SOURCE = 2; - int DISPLAY_NAME = 3; - int PREFIX = 4; - int GIVEN_NAME = 5; - int MIDDLE_NAME = 6; - int FAMILY_NAME = 7; - int SUFFIX = 8; - int PHONETIC_FAMILY_NAME = 9; - int PHONETIC_MIDDLE_NAME = 10; - int PHONETIC_GIVEN_NAME = 11; - } - - private void upgradeStructuredNamesToVersion205(SQLiteDatabase db, - SQLiteStatement rawContactUpdate, NameSplitter splitter) { - - // Process structured names to detect the style of the full name and phonetic name + private void upgradeStructuredNamesToVersion205( + SQLiteDatabase db, SQLiteStatement rawContactUpdate, NameSplitter splitter) { + // Process structured names to detect the style of the full name and phonetic name. long mMimeType; try { mMimeType = DatabaseUtils.longForQuery(db, @@ -2792,8 +2948,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { " FROM " + Tables.MIMETYPES + " WHERE " + MimetypesColumns.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null); + } catch (SQLiteDoneException e) { - // No structured names in the database + // No structured names in the database. return; } @@ -2806,7 +2963,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { " WHERE " + Data._ID + "=?"); NameSplitter.Name name = new NameSplitter.Name(); - StringBuilder sb = new StringBuilder(); Cursor cursor = db.query(StructName205Query.TABLE, StructName205Query.COLUMNS, DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null); @@ -2815,7 +2971,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { long dataId = cursor.getLong(StructName205Query.ID); long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID); int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE); - String displayName = cursor.getString(StructName205Query.DISPLAY_NAME); name.clear(); name.prefix = cursor.getString(StructName205Query.PREFIX); @@ -2827,18 +2982,22 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME); name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME); - upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name, - structuredNameUpdate, rawContactUpdate, splitter, sb); + upgradeNameToVersion205(dataId, rawContactId, displayNameSource, name, + structuredNameUpdate, rawContactUpdate, splitter); } } finally { cursor.close(); } } - private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource, - String currentDisplayName, NameSplitter.Name name, - SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate, - NameSplitter splitter, StringBuilder sb) { + private void upgradeNameToVersion205( + long dataId, + long rawContactId, + int displayNameSource, + NameSplitter.Name name, + SQLiteStatement structuredNameUpdate, + SQLiteStatement rawContactUpdate, + NameSplitter splitter) { splitter.guessNameStyle(name); int unadjustedFullNameStyle = name.fullNameStyle; @@ -2877,26 +3036,10 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } } - private interface Organization205Query { - String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; - - String COLUMNS[] = { - DataColumns.CONCRETE_ID, - Data.RAW_CONTACT_ID, - Organization.COMPANY, - Organization.PHONETIC_NAME, - }; - - int ID = 0; - int RAW_CONTACT_ID = 1; - int COMPANY = 2; - int PHONETIC_NAME = 3; - } + private void upgradeOrganizationsToVersion205( + SQLiteDatabase db, SQLiteStatement rawContactUpdate, NameSplitter splitter) { - private void upgradeOrganizationsToVersion205(SQLiteDatabase db, - SQLiteStatement rawContactUpdate, NameSplitter splitter) { final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE); - SQLiteStatement organizationUpdate = db.compileStatement( "UPDATE " + Tables.DATA + " SET " + @@ -2949,34 +3092,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } /** - * Fix for the bug where name lookup records for organizations would get removed by - * unrelated updates of the data rows. - */ - private void upgradeToVersion300(SQLiteDatabase db) { - // No longer needed - } - - private static final class Upgrade303Query { - public static final String TABLE = Tables.DATA; - - public static final String SELECTION = - DataColumns.MIMETYPE_ID + "=?" + - " AND " + Data._ID + " NOT IN " + - "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" + - " AND " + Data.DATA1 + " NOT NULL"; - - public static final String COLUMNS[] = { - Data._ID, - Data.RAW_CONTACT_ID, - Data.DATA1, - }; - - public static final int ID = 0; - public static final int RAW_CONTACT_ID = 1; - public static final int DATA1 = 2; - } - - /** * The {@link ContactsProvider2#update} method was deleting name lookup for new * emails during the sync. We need to restore the lost name lookup rows. */ @@ -3046,7 +3161,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } private void upgradeToVersion304(SQLiteDatabase db) { - // Mimetype table requires an index on mime type + // Mimetype table requires an index on mime type. db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" + MimetypesColumns.MIMETYPE + ");"); @@ -3074,7 +3189,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { "FROM raw_contacts " + "WHERE contact_id=? " + "ORDER BY _id", - new String[] { String.valueOf(contactId) }); + new String[] {String.valueOf(contactId)}); try { while (c.moveToNext()) { ContactLookupKey.appendToLookupKey(lookupKeyBuilder, @@ -3177,8 +3292,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { Log.i(TAG, "Locale update completed in " + (SystemClock.elapsedRealtime() - start) + "ms"); } - private void rebuildLocaleData(SQLiteDatabase db, Locale locale, - boolean rebuildSqliteStats) { + private void rebuildLocaleData(SQLiteDatabase db, Locale locale, boolean rebuildSqliteStats) { db.execSQL("DROP INDEX raw_contact_sort_key1_index"); db.execSQL("DROP INDEX raw_contact_sort_key2_index"); db.execSQL("DROP INDEX IF EXISTS name_lookup_index"); @@ -3225,7 +3339,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { * Regenerates sort keys for all contacts. */ private void rebuildSortKeys(SQLiteDatabase db) { - Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID}, + Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[] {RawContacts._ID}, null, null, null, null, null); try { while (cursor.moveToNext()) { @@ -3257,50 +3371,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } } - private static final class StructuredNameQuery { - public static final String TABLE = Tables.DATA; - - public static final String SELECTION = - DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; - - public static final String COLUMNS[] = { - StructuredName._ID, - StructuredName.RAW_CONTACT_ID, - StructuredName.DISPLAY_NAME, - }; - - public static final int ID = 0; - public static final int RAW_CONTACT_ID = 1; - public static final int DISPLAY_NAME = 2; - } - - private class StructuredNameLookupBuilder extends NameLookupBuilder { - - private final SQLiteStatement mNameLookupInsert; - private final CommonNicknameCache mCommonNicknameCache; - - public StructuredNameLookupBuilder(NameSplitter splitter, - CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) { - super(splitter); - this.mCommonNicknameCache = commonNicknameCache; - this.mNameLookupInsert = nameLookupInsert; - } - - @Override - protected void insertNameLookup(long rawContactId, long dataId, int lookupType, - String name) { - if (!TextUtils.isEmpty(name)) { - ContactsDatabaseHelper.this.insertNormalizedNameLookup(mNameLookupInsert, - rawContactId, dataId, lookupType, name); - } - } - - @Override - protected String[] getCommonNicknameClusters(String normalizedName) { - return mCommonNicknameCache.getCommonNicknameClusters(normalizedName); - } - } - /** * Inserts name lookup rows for all structured names in the database. */ @@ -3326,42 +3396,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } } - private static final class OrganizationQuery { - public static final String TABLE = Tables.DATA; - - public static final String SELECTION = - DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; - - public static final String COLUMNS[] = { - Organization._ID, - Organization.RAW_CONTACT_ID, - Organization.COMPANY, - Organization.TITLE, - }; - - public static final int ID = 0; - public static final int RAW_CONTACT_ID = 1; - public static final int COMPANY = 2; - public static final int TITLE = 3; - } - - private static final class EmailQuery { - public static final String TABLE = Tables.DATA; - - public static final String SELECTION = - DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; - - public static final String COLUMNS[] = { - Email._ID, - Email.RAW_CONTACT_ID, - Email.ADDRESS, - }; - - public static final int ID = 0; - public static final int RAW_CONTACT_ID = 1; - public static final int ADDRESS = 2; - } - /** * Inserts name lookup rows for all email addresses in the database. */ @@ -3384,23 +3418,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } } - private static final class NicknameQuery { - public static final String TABLE = Tables.DATA; - - public static final String SELECTION = - DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; - - public static final String COLUMNS[] = { - Nickname._ID, - Nickname.RAW_CONTACT_ID, - Nickname.NAME, - }; - - public static final int ID = 0; - public static final int RAW_CONTACT_ID = 1; - public static final int NAME = 2; - } - /** * Inserts name lookup rows for all nicknames in the database. */ @@ -3637,7 +3654,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { " FROM " + Tables.DATA + " WHERE " + DataColumns.MIMETYPE_ID + "=?" + " AND " + StructuredName.PREFIX + " NOT NULL", - new String[]{ String.valueOf(mMimeTypeIdStructuredName) }); + new String[] {String.valueOf(mMimeTypeIdStructuredName)}); try { while(cursor.moveToNext()) { @@ -3650,12 +3667,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } } - private void upgradeToVersion600(SQLiteDatabase db) { - // This change used to add the profile raw contact ID to the Accounts table. That - // column is no longer needed (as of version 614) since the profile records are stored in - // a separate copy of the database for security reasons. So this change is now a no-op. - } - private void upgradeToVersion601(SQLiteDatabase db) { db.execSQL("CREATE TABLE data_usage_stat(" + "stat_id INTEGER PRIMARY KEY AUTOINCREMENT, " + @@ -3690,12 +3701,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { ");"); } - private void upgradeToVersion605(SQLiteDatabase db) { - // This version used to create the stream item and stream item photos tables, but a newer - // version of those tables is created in version 609 below. So omitting the creation in - // this upgrade step to avoid a create->drop->create. - } - private void upgradeToVersion606(SQLiteDatabase db) { db.execSQL("DROP VIEW IF EXISTS view_contacts_restricted;"); db.execSQL("DROP VIEW IF EXISTS view_data_restricted;"); @@ -3709,13 +3714,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { // provide ALTER TABLE DROP COLUMN. As they have DEFAULT 0, we can keep but ignore them } - private void upgradeToVersion607(SQLiteDatabase db) { - // We added "action" and "action_uri" to groups here, but realized this was not a smart - // move. This upgrade step has been removed (all dogfood phones that executed this step - // will have those columns, but that shouldn't hurt. Unfortunately, SQLite makes it hard - // to remove columns) - } - private void upgradeToVersion608(SQLiteDatabase db) { db.execSQL("ALTER TABLE contacts ADD photo_file_id INTEGER REFERENCES photo_files(_id);"); @@ -3726,12 +3724,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { "filesize INTEGER NOT NULL);"); } - private void upgradeToVersion609(SQLiteDatabase db) { - // This version used to create the stream item and stream item photos tables, but a newer - // version of those tables is created in version 613 below. So omitting the creation in - // this upgrade step to avoid a create->drop->create. - } - private void upgradeToVersion610(SQLiteDatabase db) { db.execSQL("ALTER TABLE calls ADD is_read INTEGER;"); } @@ -3759,7 +3751,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { // and re-creating them to get appropriate columns. The delta is as follows: // - In stream_items, package_id was replaced by res_package. // - In stream_item_photos, picture was replaced by photo_file_id. - // - Instead of resource ids for icon and label, we use resource name strings now + // - Instead of resource IDs for icon and label, we use resource name strings now // - Added sync columns // - Removed action and action_uri // - Text and comments are now nullable @@ -3983,17 +3975,16 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { if (TextUtils.isEmpty(phoneNumber)) continue; final String normalized = PhoneNumberUtils.normalizeNumber(phoneNumber); - if (TextUtils.isEmpty(normalized)) continue; - - db.execSQL("INSERT INTO phone_lookup" + - "(data_id, raw_contact_id, normalized_number, min_match)" + - " VALUES(?,?,?,?)", - new String[] { - String.valueOf(dataIds[i]), - String.valueOf(rawContactIds[i]), - normalized, - PhoneNumberUtils.toCallerIDMinMatch(normalized) - }); + if (!TextUtils.isEmpty(normalized)) { + db.execSQL("INSERT INTO phone_lookup" + + "(data_id, raw_contact_id, normalized_number, min_match)" + + " VALUES(?,?,?,?)", + new String[] { + String.valueOf(dataIds[i]), + String.valueOf(rawContactIds[i]), + normalized, + PhoneNumberUtils.toCallerIDMinMatch(normalized)}); + } } } @@ -4054,9 +4045,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } String address = tokens[0].getAddress(); - int at = address.indexOf('@'); - if (at != -1) { - return address.substring(0, at); + int index = address.indexOf('@'); + if (index != -1) { + return address.substring(0, index); } return null; } @@ -4066,7 +4057,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { if (tokens.length == 0) { return null; } - return tokens[0].getAddress().trim(); } @@ -4078,7 +4068,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { " WHERE " + MimetypesColumns.MIMETYPE + "='" + mimeType + "'", null); } catch (SQLiteDoneException e) { - // No rows of this type in the database + // No rows of this type in the database. return -1; } } @@ -4102,8 +4092,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { /** * Add a string like "(((column1) = (column2)) OR ((column1) IS NULL AND (column2) IS NULL))" */ - private static StringBuilder addJoinExpressionAllowingNull(StringBuilder sb, - String column1, String column2) { + private static StringBuilder addJoinExpressionAllowingNull( + StringBuilder sb, String column1, String column2) { + sb.append("(((").append(column1).append(")=(").append(column2); sb.append("))OR(("); sb.append(column1).append(") IS NULL AND (").append(column2).append(") IS NULL))"); @@ -4118,7 +4109,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { */ private void updateSqliteStats(SQLiteDatabase db) { if (!mDatabaseOptimizationEnabled) { - return; // We don't use sqlite_stat1 during tests. + return; // We don't use sqlite_stat1 during tests. } // Specific stats strings are based on an actual large database after running ANALYZE @@ -4264,7 +4255,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { updateIndexStats(db, "search_index_segdir", "sqlite_autoindex_search_index_segdir_1", "9 5 1"); - // Force sqlite to reload sqlite_stat1. + // Force SQLite to reload sqlite_stat1. db.execSQL("ANALYZE sqlite_master;"); } catch (SQLException e) { Log.e(TAG, "Could not update index stats", e); @@ -4278,17 +4269,16 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { * the table. The following integer(s) are the expected number of records selected with the * index. There should be one integer per indexed column. */ - private void updateIndexStats(SQLiteDatabase db, String table, String index, - String stats) { + private void updateIndexStats(SQLiteDatabase db, String table, String index, String stats) { if (index == null) { db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl=? AND idx IS NULL", - new String[] { table }); + new String[] {table}); } else { db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl=? AND idx=?", - new String[] { table, index }); + new String[] {table, index}); } db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat) VALUES (?,?,?)", - new String[] { table, index, stats }); + new String[] {table, index, stats}); } /** @@ -4373,11 +4363,10 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { // Cache and return the new answer cache.put(value, id); return id; - } else { - // Otherwise throw if no mapping found or created - throw new IllegalStateException("Couldn't find or create internal " - + "lookup table entry for value " + value); } + // Otherwise throw if no mapping found or created + throw new IllegalStateException("Couldn't find or create internal " + + "lookup table entry for value " + value); } /** @@ -4385,8 +4374,10 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { * lookups and possible allocation of new IDs as needed. */ public long getPackageId(String packageName) { - // Try an in-memory cache lookup - if (mPackageCache.containsKey(packageName)) return mPackageCache.get(packageName); + // Try an in-memory cache lookup. + if (mPackageCache.containsKey(packageName)) { + return mPackageCache.get(packageName); + } final SQLiteStatement packageQuery = getWritableDatabase().compileStatement( "SELECT " + PackagesColumns._ID + @@ -4410,9 +4401,10 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { * lookups and possible allocation of new IDs as needed. */ public long getMimeTypeId(String mimetype) { - // Try an in-memory cache lookup - if (mMimetypeCache.containsKey(mimetype)) return mMimetypeCache.get(mimetype); - + // Try an in-memory cache lookup. + if (mMimetypeCache.containsKey(mimetype)) { + return mMimetypeCache.get(mimetype); + } return lookupMimeTypeId(mimetype, getWritableDatabase()); } @@ -4466,17 +4458,20 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { public int getDisplayNameSourceForMimeTypeId(int mimeTypeId) { if (mimeTypeId == mMimeTypeIdStructuredName) { return DisplayNameSources.STRUCTURED_NAME; - } else if (mimeTypeId == mMimeTypeIdEmail) { + } + if (mimeTypeId == mMimeTypeIdEmail) { return DisplayNameSources.EMAIL; - } else if (mimeTypeId == mMimeTypeIdPhone) { + } + if (mimeTypeId == mMimeTypeIdPhone) { return DisplayNameSources.PHONE; - } else if (mimeTypeId == mMimeTypeIdOrganization) { + } + if (mimeTypeId == mMimeTypeIdOrganization) { return DisplayNameSources.ORGANIZATION; - } else if (mimeTypeId == mMimeTypeIdNickname) { + } + if (mimeTypeId == mMimeTypeIdNickname) { return DisplayNameSources.NICKNAME; - } else { - return DisplayNameSources.UNDEFINED; } + return DisplayNameSources.UNDEFINED; } /** @@ -4618,9 +4613,8 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { String contactIdAsString = String.valueOf(contactId); long mimetype = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); - // The contact will be included in the default directory if contains - // a raw contact that is in any group or in an account that - // does not have any AUTO_ADD groups. + // The contact will be included in the default directory if contains a raw contact that is + // in any group or in an account that does not have any AUTO_ADD groups. boolean newVisibility = DatabaseUtils.longForQuery(db, "SELECT EXISTS (" + "SELECT " + RawContacts.CONTACT_ID + @@ -4662,15 +4656,15 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { if (newVisibility) { db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " VALUES(?)", - new String[] { contactIdAsString }); + new String[] {contactIdAsString}); txContext.invalidateSearchIndexForContact(contactId); } else { db.execSQL("DELETE FROM " + Tables.DEFAULT_DIRECTORY + " WHERE " + Contacts._ID + "=?", - new String[] { contactIdAsString }); + new String[] {contactIdAsString}); db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", - new String[] { contactIdAsString }); + new String[] {contactIdAsString}); } return true; } @@ -4694,7 +4688,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { */ private void updateCustomContactVisibility(SQLiteDatabase db, long optionalContactId) { final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); - String[] selectionArgs = new String[]{String.valueOf(groupMembershipMimetypeId)}; + String[] selectionArgs = new String[] {String.valueOf(groupMembershipMimetypeId)}; final String contactIdSelect = (optionalContactId < 0) ? "" : (Contacts._ID + "=" + optionalContactId + " AND "); @@ -4735,8 +4729,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId); return mContactIdQuery.simpleQueryForLong(); } catch (SQLiteDoneException e) { - // No valid mapping found, so return 0 - return 0; + return 0; // No valid mapping found. } } @@ -4751,13 +4744,13 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId); return (int)mAggregationModeQuery.simpleQueryForLong(); } catch (SQLiteDoneException e) { - // No valid row found, so return "disabled" - return RawContacts.AGGREGATION_MODE_DISABLED; + return RawContacts.AGGREGATION_MODE_DISABLED; // No valid row found. } } public void buildPhoneLookupAndContactQuery( SQLiteQueryBuilder qb, String normalizedNumber, String numberE164) { + String minMatch = PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber); StringBuilder sb = new StringBuilder(); appendPhoneLookupTables(sb, minMatch, true); @@ -4777,7 +4770,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { public void buildFallbackPhoneLookupAndContactQuery(SQLiteQueryBuilder qb, String number) { final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number); final StringBuilder sb = new StringBuilder(); - //append lookup tables + // Append lookup tables. sb.append(Tables.RAW_CONTACTS); sb.append(" JOIN " + Views.CONTACTS + " as contacts_view" + " ON (contacts_view._id = " + Tables.RAW_CONTACTS @@ -4815,7 +4808,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { sb.append("="); sb.append(Long.toString(getMimeTypeIdForSip())); // Return the arguments to be passed to the query. - return new String[]{ sipAddress }; + return new String[] {sipAddress}; } public String buildPhoneLookupAsNestedQuery(String number) { @@ -4829,8 +4822,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { return sb.toString(); } - private void appendPhoneLookupTables(StringBuilder sb, final String minMatch, - boolean joinContacts) { + private void appendPhoneLookupTables( + StringBuilder sb, final String minMatch, boolean joinContacts) { + sb.append(Tables.RAW_CONTACTS); if (joinContacts) { sb.append(" JOIN " + Views.CONTACTS + " contacts_view" @@ -4857,7 +4851,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { sb.append(" OR "); } if (hasNumber) { - // skip the suffix match entirely if we are using strict number comparison + // Skip the suffix match entirely if we are using strict number comparison. if (!mUseStrictPhoneNumberComparison) { int numberLen = number.length(); sb.append(" lookup.len <= "); @@ -4868,9 +4862,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { sb.append(numberLen); sb.append(" - lookup.len + 1) = lookup.normalized_number"); - // Some countries (e.g. Brazil) can have incoming calls which contain only the local - // number (no country calling code and no area code). This case is handled below. - // Details see b/5197612. + // Some countries (e.g. Brazil) can have incoming calls which contain only + // the local number (no country calling code and no area code). This case + // is handled below, see b/5197612. // This also handles a Gingerbread -> ICS upgrade issue; see b/5638376. sb.append(" OR ("); sb.append(" lookup.len > "); @@ -4912,17 +4906,16 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { try { for (int clusterId = 0; clusterId < strings.length; clusterId++) { String[] names = strings[clusterId].split(","); - for (int j = 0; j < names.length; j++) { - String name = NameNormalizer.normalize(names[j]); + for (String name : names) { + String normalizedName = NameNormalizer.normalize(name); try { - DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name); - DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2, - String.valueOf(clusterId)); + DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, normalizedName); + DatabaseUtils.bindObjectToProgram( + nicknameLookupInsert, 2, String.valueOf(clusterId)); nicknameLookupInsert.executeInsert(); } catch (SQLiteException e) { - - // Print the exception and keep going - this is not a fatal error - Log.e(TAG, "Cannot insert nickname: " + names[j], e); + // Print the exception and keep going (this is not a fatal error). + Log.e(TAG, "Cannot insert nickname: " + name, e); } } } @@ -4931,24 +4924,22 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } } - public static void copyStringValue(ContentValues toValues, String toKey, - ContentValues fromValues, String fromKey) { + public static void copyStringValue( + ContentValues toValues, String toKey, ContentValues fromValues, String fromKey) { + if (fromValues.containsKey(fromKey)) { toValues.put(toKey, fromValues.getAsString(fromKey)); } } - public static void copyLongValue(ContentValues toValues, String toKey, - ContentValues fromValues, String fromKey) { + public static void copyLongValue( + ContentValues toValues, String toKey, ContentValues fromValues, String fromKey) { + if (fromValues.containsKey(fromKey)) { long longValue; Object value = fromValues.get(fromKey); if (value instanceof Boolean) { - if ((Boolean)value) { - longValue = 1; - } else { - longValue = 0; - } + longValue = (Boolean) value ? 1 : 0; } else if (value instanceof String) { longValue = Long.parseLong((String)value); } else { @@ -4971,9 +4962,9 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { public String getProperty(SQLiteDatabase db, String key, String defaultValue) { Cursor cursor = db.query(Tables.PROPERTIES, - new String[]{PropertiesColumns.PROPERTY_VALUE}, + new String[] {PropertiesColumns.PROPERTY_VALUE}, PropertiesColumns.PROPERTY_KEY + "=?", - new String[]{key}, null, null, null); + new String[] {key}, null, null, null); String value = null; try { if (cursor.moveToFirst()) { @@ -5005,7 +4996,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { */ public static boolean isInProjection(String[] projection, String column) { if (projection == null) { - return true; // Null means "all columns". We can't really tell if it's in there... + return true; // Null means "all columns". We can't really tell if it's in there. } for (String test : projection) { if (column.equals(test)) { @@ -5016,7 +5007,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { } /** - * Test if any of the columns appear in the given projection. + * Tests if any of the columns appear in the given projection. */ public static boolean isInProjection(String[] projection, String... columns) { if (projection == null) { @@ -5026,12 +5017,11 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { // Optimized for a single-column test if (columns.length == 1) { return isInProjection(projection, columns[0]); - } else { - for (String test : projection) { - for (String column : columns) { - if (column.equals(test)) { - return true; - } + } + for (String test : projection) { + for (String column : columns) { + if (column.equals(test)) { + return true; } } } @@ -5060,11 +5050,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { int callingUid = Binder.getCallingUid(); sb.append(", calling user: "); String userName = pm.getNameForUid(callingUid); - if (userName != null) { - sb.append(userName); - } else { - sb.append(callingUid); - } + sb.append(userName == null ? callingUid : userName); final String[] callerPackages = pm.getPackagesForUid(callingUid); if (callerPackages != null && callerPackages.length > 0) { @@ -5082,7 +5068,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { sb.append("]"); } } - return sb.toString(); } @@ -5191,48 +5176,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { mResetNameVerifiedForOtherRawContacts.execute(); } - private interface RawContactNameQuery { - public static final String RAW_SQL = - "SELECT " - + DataColumns.MIMETYPE_ID + "," - + Data.IS_PRIMARY + "," - + Data.DATA1 + "," - + Data.DATA2 + "," - + Data.DATA3 + "," - + Data.DATA4 + "," - + Data.DATA5 + "," - + Data.DATA6 + "," - + Data.DATA7 + "," - + Data.DATA8 + "," - + Data.DATA9 + "," - + Data.DATA10 + "," - + Data.DATA11 + - " FROM " + Tables.DATA + - " WHERE " + Data.RAW_CONTACT_ID + "=?" + - " AND (" + Data.DATA1 + " NOT NULL OR " + - Data.DATA8 + " NOT NULL OR " + - Data.DATA9 + " NOT NULL OR " + - Data.DATA10 + " NOT NULL OR " + // Phonetic name not empty - Organization.TITLE + " NOT NULL)"; - - public static final int MIMETYPE = 0; - public static final int IS_PRIMARY = 1; - public static final int DATA1 = 2; - public static final int GIVEN_NAME = 3; // data2 - public static final int FAMILY_NAME = 4; // data3 - public static final int PREFIX = 5; // data4 - public static final int TITLE = 5; // data4 - public static final int MIDDLE_NAME = 6; // data5 - public static final int SUFFIX = 7; // data6 - public static final int PHONETIC_GIVEN_NAME = 8; // data7 - public static final int PHONETIC_MIDDLE_NAME = 9; // data8 - public static final int ORGANIZATION_PHONETIC_NAME = 9; // data8 - public static final int PHONETIC_FAMILY_NAME = 10; // data9 - public static final int FULL_NAME_STYLE = 11; // data10 - public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11; // data10 - public static final int PHONETIC_NAME_STYLE = 12; // data11 - } - /** * Updates a raw contact display name based on data rows, e.g. structured name, * organization, email etc. @@ -5449,7 +5392,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { mRawContactDisplayNameUpdate.execute(); } - /* + /** * Sets the given dataId record in the "data" table to primary, and resets all data records of * the same mimetype and under the same contact to not be primary. * @@ -5470,7 +5413,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { mSetPrimaryStatement.execute(); } - /* + /** * Clears the super primary of all data items of the given raw contact. does not touch * other raw contacts of the same joined aggregate */ @@ -5487,7 +5430,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { mClearSuperPrimaryStatement.execute(); } - /* + /** * Sets the given dataId record in the "data" table to "super primary", and resets all data * records of the same mimetype and under the same aggregate to not be "super primary". * @@ -5569,12 +5512,10 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { * Normalizes the nickname and inserts it in the name lookup table. */ public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) { - if (TextUtils.isEmpty(nickname)) { - return; + if (!TextUtils.isEmpty(nickname)) { + insertNameLookup(rawContactId, dataId, + NameLookupType.NICKNAME, NameNormalizer.normalize(nickname)); } - - insertNameLookup(rawContactId, dataId, - NameLookupType.NICKNAME, NameNormalizer.normalize(nickname)); } public void insertNameLookupForPhoneticName(long rawContactId, long dataId, String familyName, @@ -5606,7 +5547,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { " WHERE " + Data.RAW_CONTACT_ID + "=?" + " AND " + DataColumns.MIMETYPE_ID + "=?" + " AND " + Data.IS_SUPER_PRIMARY + "<>0)", - new String[] { String.valueOf(rawContactId), String.valueOf(mimeTypeId) }); + new String[] {String.valueOf(rawContactId), String.valueOf(mimeTypeId)}); try { if (!existsCursor.moveToFirst()) throw new IllegalStateException(); return existsCursor.getInt(0) != 0; @@ -5635,7 +5576,7 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { "SELECT " + SearchIndexColumns.CONTENT + " FROM " + Tables.SEARCH_INDEX + " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", - new String[] { String.valueOf(contactId) }); + new String[] {String.valueOf(contactId)}); } @NeededForTesting @@ -5644,6 +5585,6 @@ public class ContactsDatabaseHelper extends SQLiteOpenHelper { "SELECT " + SearchIndexColumns.TOKENS + " FROM " + Tables.SEARCH_INDEX + " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", - new String[] { String.valueOf(contactId) }); + new String[] {String.valueOf(contactId)}); } } |