ContactsDatabaseHelper.java revision 71f0747e4126c41aa30a5ffc431b8c70b3458445
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17package com.android.providers.contacts; 18 19import android.content.ComponentName; 20import android.content.ContentResolver; 21import android.content.ContentValues; 22import android.content.Context; 23import android.content.Intent; 24import android.content.pm.ApplicationInfo; 25import android.content.pm.PackageManager; 26import android.content.pm.PackageManager.NameNotFoundException; 27import android.content.pm.UserInfo; 28import android.content.res.Resources; 29import android.database.CharArrayBuffer; 30import android.database.Cursor; 31import android.database.DatabaseUtils; 32import android.database.SQLException; 33import android.database.sqlite.SQLiteConstraintException; 34import android.database.sqlite.SQLiteDatabase; 35import android.database.sqlite.SQLiteDoneException; 36import android.database.sqlite.SQLiteException; 37import android.database.sqlite.SQLiteOpenHelper; 38import android.database.sqlite.SQLiteQueryBuilder; 39import android.database.sqlite.SQLiteStatement; 40import android.net.Uri; 41import android.os.Binder; 42import android.os.Bundle; 43import android.os.SystemClock; 44import android.os.UserManager; 45import android.provider.BaseColumns; 46import android.provider.CallLog.Calls; 47import android.provider.ContactsContract; 48import android.provider.ContactsContract.AggregationExceptions; 49import android.provider.ContactsContract.CommonDataKinds.Email; 50import android.provider.ContactsContract.CommonDataKinds.GroupMembership; 51import android.provider.ContactsContract.CommonDataKinds.Im; 52import android.provider.ContactsContract.CommonDataKinds.Nickname; 53import android.provider.ContactsContract.CommonDataKinds.Organization; 54import android.provider.ContactsContract.CommonDataKinds.Phone; 55import android.provider.ContactsContract.CommonDataKinds.SipAddress; 56import android.provider.ContactsContract.CommonDataKinds.StructuredName; 57import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; 58import android.provider.ContactsContract.Contacts; 59import android.provider.ContactsContract.Contacts.Photo; 60import android.provider.ContactsContract.Data; 61import android.provider.ContactsContract.Directory; 62import android.provider.ContactsContract.DisplayNameSources; 63import android.provider.ContactsContract.DisplayPhoto; 64import android.provider.ContactsContract.FullNameStyle; 65import android.provider.ContactsContract.Groups; 66import android.provider.ContactsContract.PhoneticNameStyle; 67import android.provider.ContactsContract.PhotoFiles; 68import android.provider.ContactsContract.PinnedPositions; 69import android.provider.ContactsContract.RawContacts; 70import android.provider.ContactsContract.Settings; 71import android.provider.ContactsContract.StatusUpdates; 72import android.provider.ContactsContract.StreamItemPhotos; 73import android.provider.ContactsContract.StreamItems; 74import android.provider.VoicemailContract; 75import android.provider.VoicemailContract.Voicemails; 76import android.telephony.PhoneNumberUtils; 77import android.telephony.SubscriptionInfo; 78import android.telephony.SubscriptionManager; 79import android.text.TextUtils; 80import android.text.util.Rfc822Token; 81import android.text.util.Rfc822Tokenizer; 82import android.util.Log; 83 84import com.android.common.content.SyncStateContentProviderHelper; 85import com.android.providers.contacts.aggregation.util.CommonNicknameCache; 86import com.android.providers.contacts.database.ContactsTableUtil; 87import com.android.providers.contacts.database.DeletedContactsTableUtil; 88import com.android.providers.contacts.database.MoreDatabaseUtils; 89import com.android.providers.contacts.util.NeededForTesting; 90import com.google.android.collect.Sets; 91import com.google.common.annotations.VisibleForTesting; 92 93import libcore.icu.ICU; 94 95import java.util.Locale; 96import java.util.Set; 97import java.util.concurrent.ConcurrentHashMap; 98 99/** 100 * Database helper for contacts. Designed as a singleton to make sure that all 101 * {@link android.content.ContentProvider} users get the same reference. 102 * Provides handy methods for maintaining package and mime-type lookup tables. 103 */ 104public class ContactsDatabaseHelper extends SQLiteOpenHelper { 105 106 /** 107 * Contacts DB version ranges: 108 * <pre> 109 * 0-98 Cupcake/Donut 110 * 100-199 Eclair 111 * 200-299 Eclair-MR1 112 * 300-349 Froyo 113 * 350-399 Gingerbread 114 * 400-499 Honeycomb 115 * 500-549 Honeycomb-MR1 116 * 550-599 Honeycomb-MR2 117 * 600-699 Ice Cream Sandwich 118 * 700-799 Jelly Bean 119 * 800-899 Kitkat 120 * 900-999 Lollipop 121 * 1000-1099 M 122 * </pre> 123 */ 124 static final int DATABASE_VERSION = 1011; 125 126 public interface Tables { 127 public static final String CONTACTS = "contacts"; 128 public static final String DELETED_CONTACTS = "deleted_contacts"; 129 public static final String RAW_CONTACTS = "raw_contacts"; 130 public static final String STREAM_ITEMS = "stream_items"; 131 public static final String STREAM_ITEM_PHOTOS = "stream_item_photos"; 132 public static final String PHOTO_FILES = "photo_files"; 133 public static final String PACKAGES = "packages"; 134 public static final String MIMETYPES = "mimetypes"; 135 public static final String PHONE_LOOKUP = "phone_lookup"; 136 public static final String NAME_LOOKUP = "name_lookup"; 137 public static final String AGGREGATION_EXCEPTIONS = "agg_exceptions"; 138 public static final String SETTINGS = "settings"; 139 public static final String DATA = "data"; 140 public static final String GROUPS = "groups"; 141 public static final String PRESENCE = "presence"; 142 public static final String AGGREGATED_PRESENCE = "agg_presence"; 143 public static final String NICKNAME_LOOKUP = "nickname_lookup"; 144 public static final String CALLS = "calls"; 145 public static final String STATUS_UPDATES = "status_updates"; 146 public static final String PROPERTIES = "properties"; 147 public static final String ACCOUNTS = "accounts"; 148 public static final String VISIBLE_CONTACTS = "visible_contacts"; 149 public static final String DIRECTORIES = "directories"; 150 public static final String DEFAULT_DIRECTORY = "default_directory"; 151 public static final String SEARCH_INDEX = "search_index"; 152 public static final String VOICEMAIL_STATUS = "voicemail_status"; 153 public static final String PRE_AUTHORIZED_URIS = "pre_authorized_uris"; 154 155 // This list of tables contains auto-incremented sequences. 156 public static final String[] SEQUENCE_TABLES = new String[] { 157 CONTACTS, 158 RAW_CONTACTS, 159 STREAM_ITEMS, 160 STREAM_ITEM_PHOTOS, 161 PHOTO_FILES, 162 DATA, 163 GROUPS, 164 CALLS, 165 DIRECTORIES}; 166 167 /** 168 * For {@link android.provider.ContactsContract.DataUsageFeedback}. The table structure 169 * itself is not exposed outside. 170 */ 171 public static final String DATA_USAGE_STAT = "data_usage_stat"; 172 173 public static final String DATA_JOIN_MIMETYPES = "data " 174 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id)"; 175 176 public static final String DATA_JOIN_RAW_CONTACTS = "data " 177 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)"; 178 179 // NOTE: If you want to refer to account name/type/data_set, AccountsColumns.CONCRETE_XXX 180 // MUST be used, as upgraded raw_contacts may have the account info columns too. 181 public static final String DATA_JOIN_MIMETYPE_RAW_CONTACTS = "data " 182 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) " 183 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)" 184 + " JOIN " + Tables.ACCOUNTS + " ON (" 185 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 186 + ")"; 187 188 // NOTE: This requires late binding of GroupMembership MIME-type 189 // TODO Consolidate settings and accounts 190 public static final String RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS = Tables.RAW_CONTACTS 191 + " JOIN " + Tables.ACCOUNTS + " ON (" 192 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 193 + ")" 194 + "LEFT OUTER JOIN " + Tables.SETTINGS + " ON (" 195 + AccountsColumns.CONCRETE_ACCOUNT_NAME + "=" 196 + SettingsColumns.CONCRETE_ACCOUNT_NAME + " AND " 197 + AccountsColumns.CONCRETE_ACCOUNT_TYPE + "=" 198 + SettingsColumns.CONCRETE_ACCOUNT_TYPE + " AND " 199 + "((" + AccountsColumns.CONCRETE_DATA_SET + " IS NULL AND " 200 + SettingsColumns.CONCRETE_DATA_SET + " IS NULL) OR (" 201 + AccountsColumns.CONCRETE_DATA_SET + "=" 202 + SettingsColumns.CONCRETE_DATA_SET + "))) " 203 + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND " 204 + "data.raw_contact_id = raw_contacts._id) " 205 + "LEFT OUTER JOIN groups ON (groups._id = data." + GroupMembership.GROUP_ROW_ID 206 + ")"; 207 208 // NOTE: This requires late binding of GroupMembership MIME-type 209 // TODO Add missing DATA_SET join -- or just consolidate settings and accounts 210 public static final String SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS = "settings " 211 + "LEFT OUTER JOIN raw_contacts ON (" 212 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=(SELECT " 213 + AccountsColumns.CONCRETE_ID 214 + " FROM " + Tables.ACCOUNTS 215 + " WHERE " 216 + "(" + AccountsColumns.CONCRETE_ACCOUNT_NAME 217 + "=" + SettingsColumns.CONCRETE_ACCOUNT_NAME + ") AND " 218 + "(" + AccountsColumns.CONCRETE_ACCOUNT_TYPE 219 + "=" + SettingsColumns.CONCRETE_ACCOUNT_TYPE + ")))" 220 + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND " 221 + "data.raw_contact_id = raw_contacts._id) " 222 + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)"; 223 224 public static final String CONTACTS_JOIN_RAW_CONTACTS_DATA_FILTERED_BY_GROUPMEMBERSHIP = 225 Tables.CONTACTS 226 + " INNER JOIN " + Tables.RAW_CONTACTS 227 + " ON (" + RawContactsColumns.CONCRETE_CONTACT_ID + "=" 228 + ContactsColumns.CONCRETE_ID 229 + ")" 230 + " INNER JOIN " + Tables.DATA 231 + " ON (" + DataColumns.CONCRETE_DATA1 + "=" + GroupsColumns.CONCRETE_ID 232 + " AND " 233 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID 234 + " AND " 235 + DataColumns.CONCRETE_MIMETYPE_ID + "=" 236 + "(SELECT " + MimetypesColumns._ID 237 + " FROM " + Tables.MIMETYPES 238 + " WHERE " 239 + MimetypesColumns.CONCRETE_MIMETYPE + "=" 240 + "'" + GroupMembership.CONTENT_ITEM_TYPE + "'" 241 + ")" 242 + ")"; 243 244 // NOTE: If you want to refer to account name/type/data_set, AccountsColumns.CONCRETE_XXX 245 // MUST be used, as upgraded raw_contacts may have the account info columns too. 246 public static final String DATA_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_GROUPS = "data " 247 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) " 248 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) " 249 + " JOIN " + Tables.ACCOUNTS + " ON (" 250 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 251 + ")" 252 + "LEFT OUTER JOIN packages ON (data.package_id = packages._id) " 253 + "LEFT OUTER JOIN groups " 254 + " ON (mimetypes.mimetype='" + GroupMembership.CONTENT_ITEM_TYPE + "' " 255 + " AND groups._id = data." + GroupMembership.GROUP_ROW_ID + ") "; 256 257 public static final String ACTIVITIES_JOIN_MIMETYPES = "activities " 258 + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id)"; 259 260 public static final String ACTIVITIES_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_CONTACTS = 261 "activities " 262 + "LEFT OUTER JOIN packages ON (activities.package_id = packages._id) " 263 + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id) " 264 + "LEFT OUTER JOIN raw_contacts ON (activities.author_contact_id = " + 265 "raw_contacts._id) " 266 + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)"; 267 268 public static final String NAME_LOOKUP_JOIN_RAW_CONTACTS = "name_lookup " 269 + "INNER JOIN view_raw_contacts ON (name_lookup.raw_contact_id = " 270 + "view_raw_contacts._id)"; 271 272 public static final String RAW_CONTACTS_JOIN_ACCOUNTS = Tables.RAW_CONTACTS 273 + " JOIN " + Tables.ACCOUNTS + " ON (" 274 + AccountsColumns.CONCRETE_ID + "=" + RawContactsColumns.CONCRETE_ACCOUNT_ID 275 + ")"; 276 } 277 278 public interface Joins { 279 /** 280 * Join string intended to be used with the GROUPS table/view. The main table must be named 281 * as "groups". 282 * 283 * Adds the "group_member_count column" to the query, which will be null if a group has 284 * no members. Use ifnull(group_member_count, 0) if 0 is needed instead. 285 */ 286 public static final String GROUP_MEMBER_COUNT = 287 " LEFT OUTER JOIN (SELECT " 288 + "data.data1 AS member_count_group_id, " 289 + "COUNT(data.raw_contact_id) AS group_member_count " 290 + "FROM data " 291 + "WHERE " 292 + "data.mimetype_id = (SELECT _id FROM mimetypes WHERE " 293 + "mimetypes.mimetype = '" + GroupMembership.CONTENT_ITEM_TYPE + "')" 294 + "GROUP BY member_count_group_id) AS member_count_table" // End of inner query 295 + " ON (groups._id = member_count_table.member_count_group_id)"; 296 } 297 298 public interface Views { 299 public static final String DATA = "view_data"; 300 public static final String RAW_CONTACTS = "view_raw_contacts"; 301 public static final String CONTACTS = "view_contacts"; 302 public static final String ENTITIES = "view_entities"; 303 public static final String RAW_ENTITIES = "view_raw_entities"; 304 public static final String GROUPS = "view_groups"; 305 public static final String DATA_USAGE_STAT = "view_data_usage_stat"; 306 public static final String STREAM_ITEMS = "view_stream_items"; 307 } 308 309 public interface Projections { 310 String[] ID = new String[] {BaseColumns._ID}; 311 String[] LITERAL_ONE = new String[] {"1"}; 312 } 313 314 /** 315 * Property names for {@link ContactsDatabaseHelper#getProperty} and 316 * {@link ContactsDatabaseHelper#setProperty}. 317 */ 318 public interface DbProperties { 319 String DIRECTORY_SCAN_COMPLETE = "directoryScanComplete"; 320 String AGGREGATION_ALGORITHM = "aggregation_v2"; 321 String KNOWN_ACCOUNTS = "known_accounts"; 322 String ICU_VERSION = "icu_version"; 323 String LOCALE = "locale"; 324 String DATABASE_TIME_CREATED = "database_time_created"; 325 String CALL_LOG_LAST_SYNCED = "call_log_last_synced"; 326 } 327 328 public interface Clauses { 329 final String HAVING_NO_GROUPS = "COUNT(" + DataColumns.CONCRETE_GROUP_ID + ") == 0"; 330 331 final String GROUP_BY_ACCOUNT_CONTACT_ID = SettingsColumns.CONCRETE_ACCOUNT_NAME + "," 332 + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "," + RawContacts.CONTACT_ID; 333 334 String LOCAL_ACCOUNT_ID = 335 "(SELECT " + AccountsColumns._ID + 336 " FROM " + Tables.ACCOUNTS + 337 " WHERE " + 338 AccountsColumns.ACCOUNT_NAME + " IS NULL AND " + 339 AccountsColumns.ACCOUNT_TYPE + " IS NULL AND " + 340 AccountsColumns.DATA_SET + " IS NULL)"; 341 342 final String RAW_CONTACT_IS_LOCAL = RawContactsColumns.CONCRETE_ACCOUNT_ID 343 + "=" + LOCAL_ACCOUNT_ID; 344 345 final String ZERO_GROUP_MEMBERSHIPS = "COUNT(" + GroupsColumns.CONCRETE_ID + ")=0"; 346 347 final String OUTER_RAW_CONTACTS = "outer_raw_contacts"; 348 final String OUTER_RAW_CONTACTS_ID = OUTER_RAW_CONTACTS + "." + RawContacts._ID; 349 350 final String CONTACT_IS_VISIBLE = 351 "SELECT " + 352 "MAX((SELECT (CASE WHEN " + 353 "(CASE" + 354 " WHEN " + RAW_CONTACT_IS_LOCAL + 355 " THEN 1 " + 356 " WHEN " + ZERO_GROUP_MEMBERSHIPS + 357 " THEN " + Settings.UNGROUPED_VISIBLE + 358 " ELSE MAX(" + Groups.GROUP_VISIBLE + ")" + 359 "END)=1 THEN 1 ELSE 0 END)" + 360 " FROM " + Tables.RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS + 361 " WHERE " + RawContactsColumns.CONCRETE_ID + "=" + OUTER_RAW_CONTACTS_ID + "))" + 362 " FROM " + Tables.RAW_CONTACTS + " AS " + OUTER_RAW_CONTACTS + 363 " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + 364 " GROUP BY " + RawContacts.CONTACT_ID; 365 366 final String GROUP_HAS_ACCOUNT_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND " 367 + GroupsColumns.ACCOUNT_ID + "=?"; 368 369 public static final String CONTACT_VISIBLE = 370 "EXISTS (SELECT _id FROM " + Tables.VISIBLE_CONTACTS 371 + " WHERE " + Tables.CONTACTS +"." + Contacts._ID 372 + "=" + Tables.VISIBLE_CONTACTS +"." + Contacts._ID + ")"; 373 374 public static final String CONTACT_IN_DEFAULT_DIRECTORY = 375 "EXISTS (SELECT _id FROM " + Tables.DEFAULT_DIRECTORY 376 + " WHERE " + Tables.CONTACTS +"." + Contacts._ID 377 + "=" + Tables.DEFAULT_DIRECTORY +"." + Contacts._ID + ")"; 378 } 379 380 public interface ContactsColumns { 381 public static final String LAST_STATUS_UPDATE_ID = "status_update_id"; 382 383 public static final String CONCRETE_ID = Tables.CONTACTS + "." + BaseColumns._ID; 384 385 public static final String CONCRETE_PHOTO_FILE_ID = Tables.CONTACTS + "." 386 + Contacts.PHOTO_FILE_ID; 387 public static final String CONCRETE_TIMES_CONTACTED = Tables.CONTACTS + "." 388 + Contacts.TIMES_CONTACTED; 389 public static final String CONCRETE_LAST_TIME_CONTACTED = Tables.CONTACTS + "." 390 + Contacts.LAST_TIME_CONTACTED; 391 public static final String CONCRETE_STARRED = Tables.CONTACTS + "." + Contacts.STARRED; 392 public static final String CONCRETE_PINNED = Tables.CONTACTS + "." + Contacts.PINNED; 393 public static final String CONCRETE_CUSTOM_RINGTONE = Tables.CONTACTS + "." 394 + Contacts.CUSTOM_RINGTONE; 395 public static final String CONCRETE_SEND_TO_VOICEMAIL = Tables.CONTACTS + "." 396 + Contacts.SEND_TO_VOICEMAIL; 397 public static final String CONCRETE_LOOKUP_KEY = Tables.CONTACTS + "." 398 + Contacts.LOOKUP_KEY; 399 public static final String CONCRETE_CONTACT_LAST_UPDATED_TIMESTAMP = Tables.CONTACTS + "." 400 + Contacts.CONTACT_LAST_UPDATED_TIMESTAMP; 401 public static final String PHONEBOOK_LABEL_PRIMARY = "phonebook_label"; 402 public static final String PHONEBOOK_BUCKET_PRIMARY = "phonebook_bucket"; 403 public static final String PHONEBOOK_LABEL_ALTERNATIVE = "phonebook_label_alt"; 404 public static final String PHONEBOOK_BUCKET_ALTERNATIVE = "phonebook_bucket_alt"; 405 } 406 407 public interface RawContactsColumns { 408 public static final String CONCRETE_ID = 409 Tables.RAW_CONTACTS + "." + BaseColumns._ID; 410 411 public static final String ACCOUNT_ID = "account_id"; 412 public static final String CONCRETE_ACCOUNT_ID = Tables.RAW_CONTACTS + "." + ACCOUNT_ID; 413 public static final String CONCRETE_SOURCE_ID = 414 Tables.RAW_CONTACTS + "." + RawContacts.SOURCE_ID; 415 public static final String CONCRETE_BACKUP_ID = 416 Tables.RAW_CONTACTS + "." + RawContacts.BACKUP_ID; 417 public static final String CONCRETE_VERSION = 418 Tables.RAW_CONTACTS + "." + RawContacts.VERSION; 419 public static final String CONCRETE_DIRTY = 420 Tables.RAW_CONTACTS + "." + RawContacts.DIRTY; 421 public static final String CONCRETE_DELETED = 422 Tables.RAW_CONTACTS + "." + RawContacts.DELETED; 423 public static final String CONCRETE_SYNC1 = 424 Tables.RAW_CONTACTS + "." + RawContacts.SYNC1; 425 public static final String CONCRETE_SYNC2 = 426 Tables.RAW_CONTACTS + "." + RawContacts.SYNC2; 427 public static final String CONCRETE_SYNC3 = 428 Tables.RAW_CONTACTS + "." + RawContacts.SYNC3; 429 public static final String CONCRETE_SYNC4 = 430 Tables.RAW_CONTACTS + "." + RawContacts.SYNC4; 431 public static final String CONCRETE_CUSTOM_RINGTONE = 432 Tables.RAW_CONTACTS + "." + RawContacts.CUSTOM_RINGTONE; 433 public static final String CONCRETE_SEND_TO_VOICEMAIL = 434 Tables.RAW_CONTACTS + "." + RawContacts.SEND_TO_VOICEMAIL; 435 public static final String CONCRETE_LAST_TIME_CONTACTED = 436 Tables.RAW_CONTACTS + "." + RawContacts.LAST_TIME_CONTACTED; 437 public static final String CONCRETE_TIMES_CONTACTED = 438 Tables.RAW_CONTACTS + "." + RawContacts.TIMES_CONTACTED; 439 public static final String CONCRETE_STARRED = 440 Tables.RAW_CONTACTS + "." + RawContacts.STARRED; 441 public static final String CONCRETE_PINNED = 442 Tables.RAW_CONTACTS + "." + RawContacts.PINNED; 443 444 public static final String DISPLAY_NAME = RawContacts.DISPLAY_NAME_PRIMARY; 445 public static final String DISPLAY_NAME_SOURCE = RawContacts.DISPLAY_NAME_SOURCE; 446 public static final String AGGREGATION_NEEDED = "aggregation_needed"; 447 448 public static final String CONCRETE_DISPLAY_NAME = 449 Tables.RAW_CONTACTS + "." + DISPLAY_NAME; 450 public static final String CONCRETE_CONTACT_ID = 451 Tables.RAW_CONTACTS + "." + RawContacts.CONTACT_ID; 452 public static final String PHONEBOOK_LABEL_PRIMARY = 453 ContactsColumns.PHONEBOOK_LABEL_PRIMARY; 454 public static final String PHONEBOOK_BUCKET_PRIMARY = 455 ContactsColumns.PHONEBOOK_BUCKET_PRIMARY; 456 public static final String PHONEBOOK_LABEL_ALTERNATIVE = 457 ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE; 458 public static final String PHONEBOOK_BUCKET_ALTERNATIVE = 459 ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE; 460 461 /** 462 * This column is no longer used, but we keep it in the table so an upgraded database 463 * will look the same as a new database. This reduces the chance of OEMs adding a second 464 * column with the same name. 465 */ 466 public static final String NAME_VERIFIED_OBSOLETE = "name_verified"; 467 } 468 469 public interface ViewRawContactsColumns { 470 String CONCRETE_ACCOUNT_NAME = Views.RAW_CONTACTS + "." + RawContacts.ACCOUNT_NAME; 471 String CONCRETE_ACCOUNT_TYPE = Views.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE; 472 String CONCRETE_DATA_SET = Views.RAW_CONTACTS + "." + RawContacts.DATA_SET; 473 } 474 475 public interface DataColumns { 476 public static final String PACKAGE_ID = "package_id"; 477 public static final String MIMETYPE_ID = "mimetype_id"; 478 479 public static final String CONCRETE_ID = Tables.DATA + "." + BaseColumns._ID; 480 public static final String CONCRETE_MIMETYPE_ID = Tables.DATA + "." + MIMETYPE_ID; 481 public static final String CONCRETE_RAW_CONTACT_ID = Tables.DATA + "." 482 + Data.RAW_CONTACT_ID; 483 public static final String CONCRETE_GROUP_ID = Tables.DATA + "." 484 + GroupMembership.GROUP_ROW_ID; 485 486 public static final String CONCRETE_DATA1 = Tables.DATA + "." + Data.DATA1; 487 public static final String CONCRETE_DATA2 = Tables.DATA + "." + Data.DATA2; 488 public static final String CONCRETE_DATA3 = Tables.DATA + "." + Data.DATA3; 489 public static final String CONCRETE_DATA4 = Tables.DATA + "." + Data.DATA4; 490 public static final String CONCRETE_DATA5 = Tables.DATA + "." + Data.DATA5; 491 public static final String CONCRETE_DATA6 = Tables.DATA + "." + Data.DATA6; 492 public static final String CONCRETE_DATA7 = Tables.DATA + "." + Data.DATA7; 493 public static final String CONCRETE_DATA8 = Tables.DATA + "." + Data.DATA8; 494 public static final String CONCRETE_DATA9 = Tables.DATA + "." + Data.DATA9; 495 public static final String CONCRETE_DATA10 = Tables.DATA + "." + Data.DATA10; 496 public static final String CONCRETE_DATA11 = Tables.DATA + "." + Data.DATA11; 497 public static final String CONCRETE_DATA12 = Tables.DATA + "." + Data.DATA12; 498 public static final String CONCRETE_DATA13 = Tables.DATA + "." + Data.DATA13; 499 public static final String CONCRETE_DATA14 = Tables.DATA + "." + Data.DATA14; 500 public static final String CONCRETE_DATA15 = Tables.DATA + "." + Data.DATA15; 501 public static final String CONCRETE_IS_PRIMARY = Tables.DATA + "." + Data.IS_PRIMARY; 502 public static final String CONCRETE_PACKAGE_ID = Tables.DATA + "." + PACKAGE_ID; 503 } 504 505 // Used only for legacy API support. 506 public interface ExtensionsColumns { 507 public static final String NAME = Data.DATA1; 508 public static final String VALUE = Data.DATA2; 509 } 510 511 public interface GroupMembershipColumns { 512 public static final String RAW_CONTACT_ID = Data.RAW_CONTACT_ID; 513 public static final String GROUP_ROW_ID = GroupMembership.GROUP_ROW_ID; 514 } 515 516 public interface GroupsColumns { 517 public static final String PACKAGE_ID = "package_id"; 518 public static final String CONCRETE_PACKAGE_ID = Tables.GROUPS + "." + PACKAGE_ID; 519 520 public static final String CONCRETE_ID = Tables.GROUPS + "." + BaseColumns._ID; 521 public static final String CONCRETE_SOURCE_ID = Tables.GROUPS + "." + Groups.SOURCE_ID; 522 523 public static final String ACCOUNT_ID = "account_id"; 524 public static final String CONCRETE_ACCOUNT_ID = Tables.GROUPS + "." + ACCOUNT_ID; 525 } 526 527 public interface ViewGroupsColumns { 528 String CONCRETE_ACCOUNT_NAME = Views.GROUPS + "." + Groups.ACCOUNT_NAME; 529 String CONCRETE_ACCOUNT_TYPE = Views.GROUPS + "." + Groups.ACCOUNT_TYPE; 530 String CONCRETE_DATA_SET = Views.GROUPS + "." + Groups.DATA_SET; 531 } 532 533 public interface ActivitiesColumns { 534 public static final String PACKAGE_ID = "package_id"; 535 public static final String MIMETYPE_ID = "mimetype_id"; 536 } 537 538 public interface PhoneLookupColumns { 539 public static final String _ID = BaseColumns._ID; 540 public static final String DATA_ID = "data_id"; 541 public static final String RAW_CONTACT_ID = "raw_contact_id"; 542 public static final String NORMALIZED_NUMBER = "normalized_number"; 543 public static final String MIN_MATCH = "min_match"; 544 } 545 546 public interface NameLookupColumns { 547 public static final String RAW_CONTACT_ID = "raw_contact_id"; 548 public static final String DATA_ID = "data_id"; 549 public static final String NORMALIZED_NAME = "normalized_name"; 550 public static final String NAME_TYPE = "name_type"; 551 } 552 553 public interface PackagesColumns { 554 public static final String _ID = BaseColumns._ID; 555 public static final String PACKAGE = "package"; 556 557 public static final String CONCRETE_ID = Tables.PACKAGES + "." + _ID; 558 } 559 560 public interface MimetypesColumns { 561 public static final String _ID = BaseColumns._ID; 562 public static final String MIMETYPE = "mimetype"; 563 564 public static final String CONCRETE_ID = Tables.MIMETYPES + "." + BaseColumns._ID; 565 public static final String CONCRETE_MIMETYPE = Tables.MIMETYPES + "." + MIMETYPE; 566 } 567 568 public interface AggregationExceptionColumns { 569 public static final String _ID = BaseColumns._ID; 570 } 571 572 public interface NicknameLookupColumns { 573 public static final String NAME = "name"; 574 public static final String CLUSTER = "cluster"; 575 } 576 577 public interface SettingsColumns { 578 public static final String CONCRETE_ACCOUNT_NAME = Tables.SETTINGS + "." 579 + Settings.ACCOUNT_NAME; 580 public static final String CONCRETE_ACCOUNT_TYPE = Tables.SETTINGS + "." 581 + Settings.ACCOUNT_TYPE; 582 public static final String CONCRETE_DATA_SET = Tables.SETTINGS + "." 583 + Settings.DATA_SET; 584 } 585 586 public interface PresenceColumns { 587 String RAW_CONTACT_ID = "presence_raw_contact_id"; 588 String CONTACT_ID = "presence_contact_id"; 589 } 590 591 public interface AggregatedPresenceColumns { 592 String CONTACT_ID = "presence_contact_id"; 593 String CONCRETE_CONTACT_ID = Tables.AGGREGATED_PRESENCE + "." + CONTACT_ID; 594 } 595 596 public interface StatusUpdatesColumns { 597 String DATA_ID = "status_update_data_id"; 598 599 String CONCRETE_DATA_ID = Tables.STATUS_UPDATES + "." + DATA_ID; 600 601 String CONCRETE_PRESENCE = Tables.STATUS_UPDATES + "." + StatusUpdates.PRESENCE; 602 String CONCRETE_STATUS = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS; 603 String CONCRETE_STATUS_TIMESTAMP = Tables.STATUS_UPDATES + "." 604 + StatusUpdates.STATUS_TIMESTAMP; 605 String CONCRETE_STATUS_RES_PACKAGE = Tables.STATUS_UPDATES + "." 606 + StatusUpdates.STATUS_RES_PACKAGE; 607 String CONCRETE_STATUS_LABEL = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_LABEL; 608 String CONCRETE_STATUS_ICON = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_ICON; 609 } 610 611 public interface ContactsStatusUpdatesColumns { 612 String ALIAS = "contacts_" + Tables.STATUS_UPDATES; 613 614 String CONCRETE_DATA_ID = ALIAS + "." + StatusUpdatesColumns.DATA_ID; 615 616 String CONCRETE_PRESENCE = ALIAS + "." + StatusUpdates.PRESENCE; 617 String CONCRETE_STATUS = ALIAS + "." + StatusUpdates.STATUS; 618 String CONCRETE_STATUS_TIMESTAMP = ALIAS + "." + StatusUpdates.STATUS_TIMESTAMP; 619 String CONCRETE_STATUS_RES_PACKAGE = ALIAS + "." + StatusUpdates.STATUS_RES_PACKAGE; 620 String CONCRETE_STATUS_LABEL = ALIAS + "." + StatusUpdates.STATUS_LABEL; 621 String CONCRETE_STATUS_ICON = ALIAS + "." + StatusUpdates.STATUS_ICON; 622 } 623 624 public interface StreamItemsColumns { 625 final String CONCRETE_ID = Tables.STREAM_ITEMS + "." + BaseColumns._ID; 626 final String CONCRETE_RAW_CONTACT_ID = 627 Tables.STREAM_ITEMS + "." + StreamItems.RAW_CONTACT_ID; 628 final String CONCRETE_PACKAGE = Tables.STREAM_ITEMS + "." + StreamItems.RES_PACKAGE; 629 final String CONCRETE_ICON = Tables.STREAM_ITEMS + "." + StreamItems.RES_ICON; 630 final String CONCRETE_LABEL = Tables.STREAM_ITEMS + "." + StreamItems.RES_LABEL; 631 final String CONCRETE_TEXT = Tables.STREAM_ITEMS + "." + StreamItems.TEXT; 632 final String CONCRETE_TIMESTAMP = Tables.STREAM_ITEMS + "." + StreamItems.TIMESTAMP; 633 final String CONCRETE_COMMENTS = Tables.STREAM_ITEMS + "." + StreamItems.COMMENTS; 634 final String CONCRETE_SYNC1 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC1; 635 final String CONCRETE_SYNC2 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC2; 636 final String CONCRETE_SYNC3 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC3; 637 final String CONCRETE_SYNC4 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC4; 638 } 639 640 public interface StreamItemPhotosColumns { 641 final String CONCRETE_ID = Tables.STREAM_ITEM_PHOTOS + "." + BaseColumns._ID; 642 final String CONCRETE_STREAM_ITEM_ID = Tables.STREAM_ITEM_PHOTOS + "." 643 + StreamItemPhotos.STREAM_ITEM_ID; 644 final String CONCRETE_SORT_INDEX = 645 Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SORT_INDEX; 646 final String CONCRETE_PHOTO_FILE_ID = Tables.STREAM_ITEM_PHOTOS + "." 647 + StreamItemPhotos.PHOTO_FILE_ID; 648 final String CONCRETE_SYNC1 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC1; 649 final String CONCRETE_SYNC2 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC2; 650 final String CONCRETE_SYNC3 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC3; 651 final String CONCRETE_SYNC4 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC4; 652 } 653 654 public interface PhotoFilesColumns { 655 String CONCRETE_ID = Tables.PHOTO_FILES + "." + BaseColumns._ID; 656 String CONCRETE_HEIGHT = Tables.PHOTO_FILES + "." + PhotoFiles.HEIGHT; 657 String CONCRETE_WIDTH = Tables.PHOTO_FILES + "." + PhotoFiles.WIDTH; 658 String CONCRETE_FILESIZE = Tables.PHOTO_FILES + "." + PhotoFiles.FILESIZE; 659 } 660 661 public interface PropertiesColumns { 662 String PROPERTY_KEY = "property_key"; 663 String PROPERTY_VALUE = "property_value"; 664 } 665 666 public interface AccountsColumns extends BaseColumns { 667 String CONCRETE_ID = Tables.ACCOUNTS + "." + BaseColumns._ID; 668 669 String ACCOUNT_NAME = RawContacts.ACCOUNT_NAME; 670 String ACCOUNT_TYPE = RawContacts.ACCOUNT_TYPE; 671 String DATA_SET = RawContacts.DATA_SET; 672 673 String CONCRETE_ACCOUNT_NAME = Tables.ACCOUNTS + "." + ACCOUNT_NAME; 674 String CONCRETE_ACCOUNT_TYPE = Tables.ACCOUNTS + "." + ACCOUNT_TYPE; 675 String CONCRETE_DATA_SET = Tables.ACCOUNTS + "." + DATA_SET; 676 } 677 678 public interface DirectoryColumns { 679 public static final String TYPE_RESOURCE_NAME = "typeResourceName"; 680 } 681 682 public interface SearchIndexColumns { 683 public static final String CONTACT_ID = "contact_id"; 684 public static final String CONTENT = "content"; 685 public static final String NAME = "name"; 686 public static final String TOKENS = "tokens"; 687 } 688 689 public interface PreAuthorizedUris { 690 public static final String _ID = BaseColumns._ID; 691 public static final String URI = "uri"; 692 public static final String EXPIRATION = "expiration"; 693 } 694 695 /** 696 * Private table for calculating per-contact-method ranking. 697 */ 698 public interface DataUsageStatColumns { 699 /** type: INTEGER (long) */ 700 public static final String _ID = "stat_id"; 701 public static final String CONCRETE_ID = Tables.DATA_USAGE_STAT + "." + _ID; 702 703 /** type: INTEGER (long) */ 704 public static final String DATA_ID = "data_id"; 705 public static final String CONCRETE_DATA_ID = Tables.DATA_USAGE_STAT + "." + DATA_ID; 706 707 /** type: INTEGER (long) */ 708 public static final String LAST_TIME_USED = "last_time_used"; 709 public static final String CONCRETE_LAST_TIME_USED = 710 Tables.DATA_USAGE_STAT + "." + LAST_TIME_USED; 711 712 /** type: INTEGER */ 713 public static final String TIMES_USED = "times_used"; 714 public static final String CONCRETE_TIMES_USED = 715 Tables.DATA_USAGE_STAT + "." + TIMES_USED; 716 717 /** type: INTEGER */ 718 public static final String USAGE_TYPE_INT = "usage_type"; 719 public static final String CONCRETE_USAGE_TYPE = 720 Tables.DATA_USAGE_STAT + "." + USAGE_TYPE_INT; 721 722 /** 723 * Integer values for USAGE_TYPE. 724 * 725 * @see android.provider.ContactsContract.DataUsageFeedback#USAGE_TYPE 726 */ 727 public static final int USAGE_TYPE_INT_CALL = 0; 728 public static final int USAGE_TYPE_INT_LONG_TEXT = 1; 729 public static final int USAGE_TYPE_INT_SHORT_TEXT = 2; 730 } 731 732 private interface EmailQuery { 733 public static final String TABLE = Tables.DATA; 734 735 public static final String SELECTION = 736 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; 737 738 public static final String COLUMNS[] = { 739 Email._ID, 740 Email.RAW_CONTACT_ID, 741 Email.ADDRESS}; 742 743 public static final int ID = 0; 744 public static final int RAW_CONTACT_ID = 1; 745 public static final int ADDRESS = 2; 746 } 747 748 private interface Upgrade303Query { 749 public static final String TABLE = Tables.DATA; 750 751 public static final String SELECTION = 752 DataColumns.MIMETYPE_ID + "=?" + 753 " AND " + Data._ID + " NOT IN " + 754 "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" + 755 " AND " + Data.DATA1 + " NOT NULL"; 756 757 public static final String COLUMNS[] = { 758 Data._ID, 759 Data.RAW_CONTACT_ID, 760 Data.DATA1, 761 }; 762 763 public static final int ID = 0; 764 public static final int RAW_CONTACT_ID = 1; 765 public static final int DATA1 = 2; 766 } 767 768 private interface StructuredNameQuery { 769 public static final String TABLE = Tables.DATA; 770 771 public static final String SELECTION = 772 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; 773 774 public static final String COLUMNS[] = { 775 StructuredName._ID, 776 StructuredName.RAW_CONTACT_ID, 777 StructuredName.DISPLAY_NAME, 778 }; 779 780 public static final int ID = 0; 781 public static final int RAW_CONTACT_ID = 1; 782 public static final int DISPLAY_NAME = 2; 783 } 784 785 private interface NicknameQuery { 786 public static final String TABLE = Tables.DATA; 787 788 public static final String SELECTION = 789 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; 790 791 public static final String COLUMNS[] = { 792 Nickname._ID, 793 Nickname.RAW_CONTACT_ID, 794 Nickname.NAME}; 795 796 public static final int ID = 0; 797 public static final int RAW_CONTACT_ID = 1; 798 public static final int NAME = 2; 799 } 800 801 private interface StructName205Query { 802 String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; 803 String COLUMNS[] = { 804 DataColumns.CONCRETE_ID, 805 Data.RAW_CONTACT_ID, 806 RawContacts.DISPLAY_NAME_SOURCE, 807 RawContacts.DISPLAY_NAME_PRIMARY, 808 StructuredName.PREFIX, 809 StructuredName.GIVEN_NAME, 810 StructuredName.MIDDLE_NAME, 811 StructuredName.FAMILY_NAME, 812 StructuredName.SUFFIX, 813 StructuredName.PHONETIC_FAMILY_NAME, 814 StructuredName.PHONETIC_MIDDLE_NAME, 815 StructuredName.PHONETIC_GIVEN_NAME, 816 }; 817 818 int ID = 0; 819 int RAW_CONTACT_ID = 1; 820 int DISPLAY_NAME_SOURCE = 2; 821 int DISPLAY_NAME = 3; 822 int PREFIX = 4; 823 int GIVEN_NAME = 5; 824 int MIDDLE_NAME = 6; 825 int FAMILY_NAME = 7; 826 int SUFFIX = 8; 827 int PHONETIC_FAMILY_NAME = 9; 828 int PHONETIC_MIDDLE_NAME = 10; 829 int PHONETIC_GIVEN_NAME = 11; 830 } 831 832 private interface RawContactNameQuery { 833 public static final String RAW_SQL = 834 "SELECT " 835 + DataColumns.MIMETYPE_ID + "," 836 + Data.IS_PRIMARY + "," 837 + Data.DATA1 + "," 838 + Data.DATA2 + "," 839 + Data.DATA3 + "," 840 + Data.DATA4 + "," 841 + Data.DATA5 + "," 842 + Data.DATA6 + "," 843 + Data.DATA7 + "," 844 + Data.DATA8 + "," 845 + Data.DATA9 + "," 846 + Data.DATA10 + "," 847 + Data.DATA11 + 848 " FROM " + Tables.DATA + 849 " WHERE " + Data.RAW_CONTACT_ID + "=?" + 850 " AND (" + Data.DATA1 + " NOT NULL OR " + 851 Data.DATA8 + " NOT NULL OR " + 852 Data.DATA9 + " NOT NULL OR " + 853 Data.DATA10 + " NOT NULL OR " + // Phonetic name not empty 854 Organization.TITLE + " NOT NULL)"; 855 856 public static final int MIMETYPE = 0; 857 public static final int IS_PRIMARY = 1; 858 public static final int DATA1 = 2; 859 public static final int GIVEN_NAME = 3; // data2 860 public static final int FAMILY_NAME = 4; // data3 861 public static final int PREFIX = 5; // data4 862 public static final int TITLE = 5; // data4 863 public static final int MIDDLE_NAME = 6; // data5 864 public static final int SUFFIX = 7; // data6 865 public static final int PHONETIC_GIVEN_NAME = 8; // data7 866 public static final int PHONETIC_MIDDLE_NAME = 9; // data8 867 public static final int ORGANIZATION_PHONETIC_NAME = 9; // data8 868 public static final int PHONETIC_FAMILY_NAME = 10; // data9 869 public static final int FULL_NAME_STYLE = 11; // data10 870 public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11; // data10 871 public static final int PHONETIC_NAME_STYLE = 12; // data11 872 } 873 874 private interface Organization205Query { 875 String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; 876 String COLUMNS[] = { 877 DataColumns.CONCRETE_ID, 878 Data.RAW_CONTACT_ID, 879 Organization.COMPANY, 880 Organization.PHONETIC_NAME, 881 }; 882 883 int ID = 0; 884 int RAW_CONTACT_ID = 1; 885 int COMPANY = 2; 886 int PHONETIC_NAME = 3; 887 } 888 889 public final static class NameLookupType { 890 public static final int NAME_EXACT = 0; 891 public static final int NAME_VARIANT = 1; 892 public static final int NAME_COLLATION_KEY = 2; 893 public static final int NICKNAME = 3; 894 public static final int EMAIL_BASED_NICKNAME = 4; 895 896 // The highest name-lookup type plus one. 897 public static final int TYPE_COUNT = 5; 898 899 public static boolean isBasedOnStructuredName(int nameLookupType) { 900 return nameLookupType == NameLookupType.NAME_EXACT 901 || nameLookupType == NameLookupType.NAME_VARIANT 902 || nameLookupType == NameLookupType.NAME_COLLATION_KEY; 903 } 904 } 905 906 private class StructuredNameLookupBuilder extends NameLookupBuilder { 907 // NOTE(gilad): Is in intentional that we don't use the declaration on L960? 908 private final SQLiteStatement mNameLookupInsert; 909 private final CommonNicknameCache mCommonNicknameCache; 910 911 public StructuredNameLookupBuilder(NameSplitter splitter, 912 CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) { 913 914 super(splitter); 915 this.mCommonNicknameCache = commonNicknameCache; 916 this.mNameLookupInsert = nameLookupInsert; 917 } 918 919 @Override 920 protected void insertNameLookup( 921 long rawContactId, long dataId, int lookupType, String name) { 922 923 if (!TextUtils.isEmpty(name)) { 924 ContactsDatabaseHelper.this.insertNormalizedNameLookup( 925 mNameLookupInsert, rawContactId, dataId, lookupType, name); 926 } 927 } 928 929 @Override 930 protected String[] getCommonNicknameClusters(String normalizedName) { 931 return mCommonNicknameCache.getCommonNicknameClusters(normalizedName); 932 } 933 } 934 935 private static final String TAG = "ContactsDatabaseHelper"; 936 937 private static final String DATABASE_NAME = "contacts2.db"; 938 private static final String DATABASE_PRESENCE = "presence_db"; 939 940 private static ContactsDatabaseHelper sSingleton = null; 941 942 /** In-memory cache of previously found MIME-type mappings */ 943 @VisibleForTesting 944 final ConcurrentHashMap<String, Long> mMimetypeCache = new ConcurrentHashMap<>(); 945 946 /** In-memory cache the packages table */ 947 @VisibleForTesting 948 final ConcurrentHashMap<String, Long> mPackageCache = new ConcurrentHashMap<>(); 949 950 private final Context mContext; 951 private final boolean mDatabaseOptimizationEnabled; 952 private final SyncStateContentProviderHelper mSyncState; 953 private final CountryMonitor mCountryMonitor; 954 955 private long mMimeTypeIdEmail; 956 private long mMimeTypeIdIm; 957 private long mMimeTypeIdNickname; 958 private long mMimeTypeIdOrganization; 959 private long mMimeTypeIdPhone; 960 private long mMimeTypeIdSip; 961 private long mMimeTypeIdStructuredName; 962 private long mMimeTypeIdStructuredPostal; 963 964 /** Compiled statements for querying and inserting mappings */ 965 private SQLiteStatement mContactIdQuery; 966 private SQLiteStatement mAggregationModeQuery; 967 private SQLiteStatement mDataMimetypeQuery; 968 969 /** Precompiled SQL statement for setting a data record to the primary. */ 970 private SQLiteStatement mSetPrimaryStatement; 971 /** Precompiled SQL statement for setting a data record to the super primary. */ 972 private SQLiteStatement mSetSuperPrimaryStatement; 973 /** Precompiled SQL statement for clearing super primary of a single record. */ 974 private SQLiteStatement mClearSuperPrimaryStatement; 975 /** Precompiled SQL statement for updating a contact display name */ 976 private SQLiteStatement mRawContactDisplayNameUpdate; 977 978 private SQLiteStatement mNameLookupInsert; 979 private SQLiteStatement mNameLookupDelete; 980 private SQLiteStatement mStatusUpdateAutoTimestamp; 981 private SQLiteStatement mStatusUpdateInsert; 982 private SQLiteStatement mStatusUpdateReplace; 983 private SQLiteStatement mStatusAttributionUpdate; 984 private SQLiteStatement mStatusUpdateDelete; 985 private SQLiteStatement mResetNameVerifiedForOtherRawContacts; 986 private SQLiteStatement mContactInDefaultDirectoryQuery; 987 988 private StringBuilder mSb = new StringBuilder(); 989 990 private boolean mUseStrictPhoneNumberComparison; 991 992 private String[] mSelectionArgs1 = new String[1]; 993 private NameSplitter.Name mName = new NameSplitter.Name(); 994 private CharArrayBuffer mCharArrayBuffer = new CharArrayBuffer(128); 995 private NameSplitter mNameSplitter; 996 997 public static synchronized ContactsDatabaseHelper getInstance(Context context) { 998 if (sSingleton == null) { 999 sSingleton = new ContactsDatabaseHelper(context, DATABASE_NAME, true); 1000 } 1001 return sSingleton; 1002 } 1003 1004 /** 1005 * Returns a new instance for unit tests. 1006 */ 1007 @NeededForTesting 1008 static ContactsDatabaseHelper getNewInstanceForTest(Context context) { 1009 return new ContactsDatabaseHelper(context, null, false); 1010 } 1011 1012 protected ContactsDatabaseHelper( 1013 Context context, String databaseName, boolean optimizationEnabled) { 1014 super(context, databaseName, null, DATABASE_VERSION); 1015 mDatabaseOptimizationEnabled = optimizationEnabled; 1016 Resources resources = context.getResources(); 1017 1018 mContext = context; 1019 mSyncState = new SyncStateContentProviderHelper(); 1020 mCountryMonitor = new CountryMonitor(context); 1021 mUseStrictPhoneNumberComparison = resources.getBoolean( 1022 com.android.internal.R.bool.config_use_strict_phone_number_comparation); 1023 } 1024 1025 public SQLiteDatabase getDatabase(boolean writable) { 1026 return writable ? getWritableDatabase() : getReadableDatabase(); 1027 } 1028 1029 /** 1030 * Clear all the cached database information and re-initialize it. 1031 * 1032 * @param db target database 1033 */ 1034 private void refreshDatabaseCaches(SQLiteDatabase db) { 1035 mStatusUpdateDelete = null; 1036 mStatusUpdateReplace = null; 1037 mStatusUpdateInsert = null; 1038 mStatusUpdateAutoTimestamp = null; 1039 mStatusAttributionUpdate = null; 1040 mResetNameVerifiedForOtherRawContacts = null; 1041 mRawContactDisplayNameUpdate = null; 1042 mSetPrimaryStatement = null; 1043 mClearSuperPrimaryStatement = null; 1044 mSetSuperPrimaryStatement = null; 1045 mNameLookupInsert = null; 1046 mNameLookupDelete = null; 1047 mDataMimetypeQuery = null; 1048 mContactIdQuery = null; 1049 mAggregationModeQuery = null; 1050 mContactInDefaultDirectoryQuery = null; 1051 1052 initializeCache(db); 1053 } 1054 1055 /** 1056 * (Re-)initialize the cached database information. 1057 * 1058 * @param db target database 1059 */ 1060 private void initializeCache(SQLiteDatabase db) { 1061 mMimetypeCache.clear(); 1062 mPackageCache.clear(); 1063 1064 // TODO: This could be optimized into one query instead of 7 1065 // Also: We shouldn't have those fields in the first place. This should just be 1066 // in the cache 1067 mMimeTypeIdEmail = lookupMimeTypeId(Email.CONTENT_ITEM_TYPE, db); 1068 mMimeTypeIdIm = lookupMimeTypeId(Im.CONTENT_ITEM_TYPE, db); 1069 mMimeTypeIdNickname = lookupMimeTypeId(Nickname.CONTENT_ITEM_TYPE, db); 1070 mMimeTypeIdOrganization = lookupMimeTypeId(Organization.CONTENT_ITEM_TYPE, db); 1071 mMimeTypeIdPhone = lookupMimeTypeId(Phone.CONTENT_ITEM_TYPE, db); 1072 mMimeTypeIdSip = lookupMimeTypeId(SipAddress.CONTENT_ITEM_TYPE, db); 1073 mMimeTypeIdStructuredName = lookupMimeTypeId(StructuredName.CONTENT_ITEM_TYPE, db); 1074 mMimeTypeIdStructuredPostal = lookupMimeTypeId(StructuredPostal.CONTENT_ITEM_TYPE, db); 1075 } 1076 1077 @Override 1078 public void onOpen(SQLiteDatabase db) { 1079 refreshDatabaseCaches(db); 1080 1081 mSyncState.onDatabaseOpened(db); 1082 1083 db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";"); 1084 db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_PRESENCE + "." + Tables.PRESENCE + " ("+ 1085 StatusUpdates.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," + 1086 StatusUpdates.PROTOCOL + " INTEGER NOT NULL," + 1087 StatusUpdates.CUSTOM_PROTOCOL + " TEXT," + 1088 StatusUpdates.IM_HANDLE + " TEXT," + 1089 StatusUpdates.IM_ACCOUNT + " TEXT," + 1090 PresenceColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," + 1091 PresenceColumns.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," + 1092 StatusUpdates.PRESENCE + " INTEGER," + 1093 StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0," + 1094 "UNIQUE(" + StatusUpdates.PROTOCOL + ", " + StatusUpdates.CUSTOM_PROTOCOL 1095 + ", " + StatusUpdates.IM_HANDLE + ", " + StatusUpdates.IM_ACCOUNT + ")" + 1096 ");"); 1097 1098 db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex" + " ON " 1099 + Tables.PRESENCE + " (" + PresenceColumns.RAW_CONTACT_ID + ");"); 1100 db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex2" + " ON " 1101 + Tables.PRESENCE + " (" + PresenceColumns.CONTACT_ID + ");"); 1102 1103 db.execSQL("CREATE TABLE IF NOT EXISTS " 1104 + DATABASE_PRESENCE + "." + Tables.AGGREGATED_PRESENCE + " ("+ 1105 AggregatedPresenceColumns.CONTACT_ID 1106 + " INTEGER PRIMARY KEY REFERENCES contacts(_id)," + 1107 StatusUpdates.PRESENCE + " INTEGER," + 1108 StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0" + 1109 ");"); 1110 1111 db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_deleted" 1112 + " BEFORE DELETE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE 1113 + " BEGIN " 1114 + " DELETE FROM " + Tables.AGGREGATED_PRESENCE 1115 + " WHERE " + AggregatedPresenceColumns.CONTACT_ID + " = " + 1116 "(SELECT " + PresenceColumns.CONTACT_ID + 1117 " FROM " + Tables.PRESENCE + 1118 " WHERE " + PresenceColumns.RAW_CONTACT_ID 1119 + "=OLD." + PresenceColumns.RAW_CONTACT_ID + 1120 " AND NOT EXISTS" + 1121 "(SELECT " + PresenceColumns.RAW_CONTACT_ID + 1122 " FROM " + Tables.PRESENCE + 1123 " WHERE " + PresenceColumns.CONTACT_ID 1124 + "=OLD." + PresenceColumns.CONTACT_ID + 1125 " AND " + PresenceColumns.RAW_CONTACT_ID 1126 + "!=OLD." + PresenceColumns.RAW_CONTACT_ID + "));" 1127 + " END"); 1128 1129 final String replaceAggregatePresenceSql = 1130 "INSERT OR REPLACE INTO " + Tables.AGGREGATED_PRESENCE + "(" 1131 + AggregatedPresenceColumns.CONTACT_ID + ", " 1132 + StatusUpdates.PRESENCE + ", " 1133 + StatusUpdates.CHAT_CAPABILITY + ")" 1134 + " SELECT " 1135 + PresenceColumns.CONTACT_ID + "," 1136 + StatusUpdates.PRESENCE + "," 1137 + StatusUpdates.CHAT_CAPABILITY 1138 + " FROM " + Tables.PRESENCE 1139 + " WHERE " 1140 + " (ifnull(" + StatusUpdates.PRESENCE + ",0) * 10 " 1141 + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))" 1142 + " = (SELECT " 1143 + "MAX (ifnull(" + StatusUpdates.PRESENCE + ",0) * 10 " 1144 + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))" 1145 + " FROM " + Tables.PRESENCE 1146 + " WHERE " + PresenceColumns.CONTACT_ID 1147 + "=NEW." + PresenceColumns.CONTACT_ID 1148 + ")" 1149 + " AND " + PresenceColumns.CONTACT_ID + "=NEW." + PresenceColumns.CONTACT_ID + ";"; 1150 1151 db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_inserted" 1152 + " AFTER INSERT ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE 1153 + " BEGIN " 1154 + replaceAggregatePresenceSql 1155 + " END"); 1156 1157 db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_updated" 1158 + " AFTER UPDATE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE 1159 + " BEGIN " 1160 + replaceAggregatePresenceSql 1161 + " END"); 1162 } 1163 1164 @Override 1165 public void onCreate(SQLiteDatabase db) { 1166 Log.i(TAG, "Bootstrapping database version: " + DATABASE_VERSION); 1167 1168 mSyncState.createDatabase(db); 1169 1170 // Create the properties table first so the create time is available as soon as possible. 1171 // The create time is needed by BOOT_COMPLETE to send broadcasts. 1172 db.execSQL("CREATE TABLE " + Tables.PROPERTIES + " (" + 1173 PropertiesColumns.PROPERTY_KEY + " TEXT PRIMARY KEY, " + 1174 PropertiesColumns.PROPERTY_VALUE + " TEXT " + 1175 ");"); 1176 setProperty(db, DbProperties.DATABASE_TIME_CREATED, String.valueOf( 1177 System.currentTimeMillis())); 1178 1179 db.execSQL("CREATE TABLE " + Tables.ACCOUNTS + " (" + 1180 AccountsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1181 AccountsColumns.ACCOUNT_NAME + " TEXT, " + 1182 AccountsColumns.ACCOUNT_TYPE + " TEXT, " + 1183 AccountsColumns.DATA_SET + " TEXT" + 1184 ");"); 1185 1186 // One row per group of contacts corresponding to the same person 1187 db.execSQL("CREATE TABLE " + Tables.CONTACTS + " (" + 1188 BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1189 Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," + 1190 Contacts.PHOTO_ID + " INTEGER REFERENCES data(_id)," + 1191 Contacts.PHOTO_FILE_ID + " INTEGER REFERENCES photo_files(_id)," + 1192 Contacts.CUSTOM_RINGTONE + " TEXT," + 1193 Contacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," + 1194 Contacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," + 1195 Contacts.LAST_TIME_CONTACTED + " INTEGER," + 1196 Contacts.STARRED + " INTEGER NOT NULL DEFAULT 0," + 1197 Contacts.PINNED + " INTEGER NOT NULL DEFAULT " + PinnedPositions.UNPINNED + "," + 1198 Contacts.HAS_PHONE_NUMBER + " INTEGER NOT NULL DEFAULT 0," + 1199 Contacts.LOOKUP_KEY + " TEXT," + 1200 ContactsColumns.LAST_STATUS_UPDATE_ID + " INTEGER REFERENCES data(_id)," + 1201 Contacts.CONTACT_LAST_UPDATED_TIMESTAMP + " INTEGER" + 1202 ");"); 1203 1204 ContactsTableUtil.createIndexes(db); 1205 1206 // deleted_contacts table 1207 DeletedContactsTableUtil.create(db); 1208 1209 // Raw_contacts table 1210 db.execSQL("CREATE TABLE " + Tables.RAW_CONTACTS + " (" + 1211 RawContacts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1212 RawContactsColumns.ACCOUNT_ID + " INTEGER REFERENCES " + 1213 Tables.ACCOUNTS + "(" + AccountsColumns._ID + ")," + 1214 RawContacts.SOURCE_ID + " TEXT," + 1215 RawContacts.BACKUP_ID + " TEXT," + 1216 RawContacts.RAW_CONTACT_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," + 1217 RawContacts.VERSION + " INTEGER NOT NULL DEFAULT 1," + 1218 RawContacts.DIRTY + " INTEGER NOT NULL DEFAULT 0," + 1219 RawContacts.DELETED + " INTEGER NOT NULL DEFAULT 0," + 1220 RawContacts.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," + 1221 RawContacts.AGGREGATION_MODE + " INTEGER NOT NULL DEFAULT " + 1222 RawContacts.AGGREGATION_MODE_DEFAULT + "," + 1223 RawContactsColumns.AGGREGATION_NEEDED + " INTEGER NOT NULL DEFAULT 1," + 1224 RawContacts.CUSTOM_RINGTONE + " TEXT," + 1225 RawContacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," + 1226 RawContacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," + 1227 RawContacts.LAST_TIME_CONTACTED + " INTEGER," + 1228 RawContacts.STARRED + " INTEGER NOT NULL DEFAULT 0," + 1229 RawContacts.PINNED + " INTEGER NOT NULL DEFAULT " + PinnedPositions.UNPINNED + 1230 "," + RawContacts.DISPLAY_NAME_PRIMARY + " TEXT," + 1231 RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT," + 1232 RawContacts.DISPLAY_NAME_SOURCE + " INTEGER NOT NULL DEFAULT " + 1233 DisplayNameSources.UNDEFINED + "," + 1234 RawContacts.PHONETIC_NAME + " TEXT," + 1235 // TODO: PHONETIC_NAME_STYLE should be INTEGER. There is a 1236 // mismatch between how the column is created here (TEXT) and 1237 // how it is created in upgradeToVersion205 (INTEGER). 1238 RawContacts.PHONETIC_NAME_STYLE + " TEXT," + 1239 RawContacts.SORT_KEY_PRIMARY + " TEXT COLLATE " + 1240 ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," + 1241 RawContactsColumns.PHONEBOOK_LABEL_PRIMARY + " TEXT," + 1242 RawContactsColumns.PHONEBOOK_BUCKET_PRIMARY + " INTEGER," + 1243 RawContacts.SORT_KEY_ALTERNATIVE + " TEXT COLLATE " + 1244 ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," + 1245 RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE + " TEXT," + 1246 RawContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + " INTEGER," + 1247 RawContactsColumns.NAME_VERIFIED_OBSOLETE + " INTEGER NOT NULL DEFAULT 0," + 1248 RawContacts.SYNC1 + " TEXT, " + 1249 RawContacts.SYNC2 + " TEXT, " + 1250 RawContacts.SYNC3 + " TEXT, " + 1251 RawContacts.SYNC4 + " TEXT " + 1252 ");"); 1253 1254 db.execSQL("CREATE INDEX raw_contacts_contact_id_index ON " + Tables.RAW_CONTACTS + " (" + 1255 RawContacts.CONTACT_ID + 1256 ");"); 1257 1258 db.execSQL("CREATE INDEX raw_contacts_source_id_account_id_index ON " + 1259 Tables.RAW_CONTACTS + " (" + 1260 RawContacts.SOURCE_ID + ", " + 1261 RawContactsColumns.ACCOUNT_ID + 1262 ");"); 1263 1264 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS raw_contacts_backup_id_account_id_index ON " + 1265 Tables.RAW_CONTACTS + " (" + 1266 RawContacts.BACKUP_ID + ", " + 1267 RawContactsColumns.ACCOUNT_ID + 1268 ");"); 1269 1270 db.execSQL("CREATE TABLE " + Tables.STREAM_ITEMS + " (" + 1271 StreamItems._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 1272 StreamItems.RAW_CONTACT_ID + " INTEGER NOT NULL, " + 1273 StreamItems.RES_PACKAGE + " TEXT, " + 1274 StreamItems.RES_ICON + " TEXT, " + 1275 StreamItems.RES_LABEL + " TEXT, " + 1276 StreamItems.TEXT + " TEXT, " + 1277 StreamItems.TIMESTAMP + " INTEGER NOT NULL, " + 1278 StreamItems.COMMENTS + " TEXT, " + 1279 StreamItems.SYNC1 + " TEXT, " + 1280 StreamItems.SYNC2 + " TEXT, " + 1281 StreamItems.SYNC3 + " TEXT, " + 1282 StreamItems.SYNC4 + " TEXT, " + 1283 "FOREIGN KEY(" + StreamItems.RAW_CONTACT_ID + ") REFERENCES " + 1284 Tables.RAW_CONTACTS + "(" + RawContacts._ID + "));"); 1285 1286 db.execSQL("CREATE TABLE " + Tables.STREAM_ITEM_PHOTOS + " (" + 1287 StreamItemPhotos._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 1288 StreamItemPhotos.STREAM_ITEM_ID + " INTEGER NOT NULL, " + 1289 StreamItemPhotos.SORT_INDEX + " INTEGER, " + 1290 StreamItemPhotos.PHOTO_FILE_ID + " INTEGER NOT NULL, " + 1291 StreamItemPhotos.SYNC1 + " TEXT, " + 1292 StreamItemPhotos.SYNC2 + " TEXT, " + 1293 StreamItemPhotos.SYNC3 + " TEXT, " + 1294 StreamItemPhotos.SYNC4 + " TEXT, " + 1295 "FOREIGN KEY(" + StreamItemPhotos.STREAM_ITEM_ID + ") REFERENCES " + 1296 Tables.STREAM_ITEMS + "(" + StreamItems._ID + "));"); 1297 1298 db.execSQL("CREATE TABLE " + Tables.PHOTO_FILES + " (" + 1299 PhotoFiles._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 1300 PhotoFiles.HEIGHT + " INTEGER NOT NULL, " + 1301 PhotoFiles.WIDTH + " INTEGER NOT NULL, " + 1302 PhotoFiles.FILESIZE + " INTEGER NOT NULL);"); 1303 1304 // TODO readd the index and investigate a controlled use of it 1305// db.execSQL("CREATE INDEX raw_contacts_agg_index ON " + Tables.RAW_CONTACTS + " (" + 1306// RawContactsColumns.AGGREGATION_NEEDED + 1307// ");"); 1308 1309 // Package name mapping table 1310 db.execSQL("CREATE TABLE " + Tables.PACKAGES + " (" + 1311 PackagesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1312 PackagesColumns.PACKAGE + " TEXT NOT NULL" + 1313 ");"); 1314 1315 // Mimetype mapping table 1316 db.execSQL("CREATE TABLE " + Tables.MIMETYPES + " (" + 1317 MimetypesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1318 MimetypesColumns.MIMETYPE + " TEXT NOT NULL" + 1319 ");"); 1320 1321 // Mimetype table requires an index on mime type 1322 db.execSQL("CREATE UNIQUE INDEX mime_type ON " + Tables.MIMETYPES + " (" + 1323 MimetypesColumns.MIMETYPE + 1324 ");"); 1325 1326 // Public generic data table 1327 db.execSQL("CREATE TABLE " + Tables.DATA + " (" + 1328 Data._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1329 DataColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," + 1330 DataColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," + 1331 Data.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 1332 Data.HASH_ID + " TEXT," + 1333 Data.IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," + 1334 Data.IS_PRIMARY + " INTEGER NOT NULL DEFAULT 0," + 1335 Data.IS_SUPER_PRIMARY + " INTEGER NOT NULL DEFAULT 0," + 1336 Data.DATA_VERSION + " INTEGER NOT NULL DEFAULT 0," + 1337 Data.DATA1 + " TEXT," + 1338 Data.DATA2 + " TEXT," + 1339 Data.DATA3 + " TEXT," + 1340 Data.DATA4 + " TEXT," + 1341 Data.DATA5 + " TEXT," + 1342 Data.DATA6 + " TEXT," + 1343 Data.DATA7 + " TEXT," + 1344 Data.DATA8 + " TEXT," + 1345 Data.DATA9 + " TEXT," + 1346 Data.DATA10 + " TEXT," + 1347 Data.DATA11 + " TEXT," + 1348 Data.DATA12 + " TEXT," + 1349 Data.DATA13 + " TEXT," + 1350 Data.DATA14 + " TEXT," + 1351 Data.DATA15 + " TEXT," + 1352 Data.SYNC1 + " TEXT, " + 1353 Data.SYNC2 + " TEXT, " + 1354 Data.SYNC3 + " TEXT, " + 1355 Data.SYNC4 + " TEXT, " + 1356 Data.CARRIER_PRESENCE + " INTEGER NOT NULL DEFAULT 0 " + 1357 ");"); 1358 1359 db.execSQL("CREATE INDEX data_raw_contact_id ON " + Tables.DATA + " (" + 1360 Data.RAW_CONTACT_ID + 1361 ");"); 1362 1363 /** 1364 * For email lookup and similar queries. 1365 */ 1366 db.execSQL("CREATE INDEX data_mimetype_data1_index ON " + Tables.DATA + " (" + 1367 DataColumns.MIMETYPE_ID + "," + 1368 Data.DATA1 + 1369 ");"); 1370 1371 /** 1372 * For contact backup restore queries. 1373 */ 1374 db.execSQL("CREATE INDEX IF NOT EXISTS data_hash_id_index ON " + Tables.DATA + " (" + 1375 Data.HASH_ID + 1376 ");"); 1377 1378 1379 // Private phone numbers table used for lookup 1380 db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" + 1381 PhoneLookupColumns.DATA_ID 1382 + " INTEGER REFERENCES data(_id) NOT NULL," + 1383 PhoneLookupColumns.RAW_CONTACT_ID 1384 + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 1385 PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," + 1386 PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" + 1387 ");"); 1388 1389 db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" + 1390 PhoneLookupColumns.NORMALIZED_NUMBER + "," + 1391 PhoneLookupColumns.RAW_CONTACT_ID + "," + 1392 PhoneLookupColumns.DATA_ID + 1393 ");"); 1394 1395 db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" + 1396 PhoneLookupColumns.MIN_MATCH + "," + 1397 PhoneLookupColumns.RAW_CONTACT_ID + "," + 1398 PhoneLookupColumns.DATA_ID + 1399 ");"); 1400 1401 db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP + 1402 " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");"); 1403 1404 // Private name/nickname table used for lookup. 1405 db.execSQL("CREATE TABLE " + Tables.NAME_LOOKUP + " (" + 1406 NameLookupColumns.DATA_ID 1407 + " INTEGER REFERENCES data(_id) NOT NULL," + 1408 NameLookupColumns.RAW_CONTACT_ID 1409 + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 1410 NameLookupColumns.NORMALIZED_NAME + " TEXT NOT NULL," + 1411 NameLookupColumns.NAME_TYPE + " INTEGER NOT NULL," + 1412 "PRIMARY KEY (" 1413 + NameLookupColumns.DATA_ID + ", " 1414 + NameLookupColumns.NORMALIZED_NAME + ", " 1415 + NameLookupColumns.NAME_TYPE + ")" + 1416 ");"); 1417 1418 db.execSQL("CREATE INDEX name_lookup_raw_contact_id_index ON " + Tables.NAME_LOOKUP + " (" + 1419 NameLookupColumns.RAW_CONTACT_ID + 1420 ");"); 1421 1422 db.execSQL("CREATE TABLE " + Tables.NICKNAME_LOOKUP + " (" + 1423 NicknameLookupColumns.NAME + " TEXT," + 1424 NicknameLookupColumns.CLUSTER + " TEXT" + 1425 ");"); 1426 1427 db.execSQL("CREATE UNIQUE INDEX nickname_lookup_index ON " + Tables.NICKNAME_LOOKUP + " (" + 1428 NicknameLookupColumns.NAME + ", " + 1429 NicknameLookupColumns.CLUSTER + 1430 ");"); 1431 1432 // Groups table. 1433 db.execSQL("CREATE TABLE " + Tables.GROUPS + " (" + 1434 Groups._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1435 GroupsColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," + 1436 GroupsColumns.ACCOUNT_ID + " INTEGER REFERENCES " + 1437 Tables.ACCOUNTS + "(" + AccountsColumns._ID + ")," + 1438 Groups.SOURCE_ID + " TEXT," + 1439 Groups.VERSION + " INTEGER NOT NULL DEFAULT 1," + 1440 Groups.DIRTY + " INTEGER NOT NULL DEFAULT 0," + 1441 Groups.TITLE + " TEXT," + 1442 Groups.TITLE_RES + " INTEGER," + 1443 Groups.NOTES + " TEXT," + 1444 Groups.SYSTEM_ID + " TEXT," + 1445 Groups.DELETED + " INTEGER NOT NULL DEFAULT 0," + 1446 Groups.GROUP_VISIBLE + " INTEGER NOT NULL DEFAULT 0," + 1447 Groups.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1," + 1448 Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0," + 1449 Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0," + 1450 Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," + 1451 Groups.SYNC1 + " TEXT, " + 1452 Groups.SYNC2 + " TEXT, " + 1453 Groups.SYNC3 + " TEXT, " + 1454 Groups.SYNC4 + " TEXT " + 1455 ");"); 1456 1457 db.execSQL("CREATE INDEX groups_source_id_account_id_index ON " + Tables.GROUPS + " (" + 1458 Groups.SOURCE_ID + ", " + 1459 GroupsColumns.ACCOUNT_ID + 1460 ");"); 1461 1462 db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.AGGREGATION_EXCEPTIONS + " (" + 1463 AggregationExceptionColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1464 AggregationExceptions.TYPE + " INTEGER NOT NULL, " + 1465 AggregationExceptions.RAW_CONTACT_ID1 1466 + " INTEGER REFERENCES raw_contacts(_id), " + 1467 AggregationExceptions.RAW_CONTACT_ID2 1468 + " INTEGER REFERENCES raw_contacts(_id)" + 1469 ");"); 1470 1471 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index1 ON " + 1472 Tables.AGGREGATION_EXCEPTIONS + " (" + 1473 AggregationExceptions.RAW_CONTACT_ID1 + ", " + 1474 AggregationExceptions.RAW_CONTACT_ID2 + 1475 ");"); 1476 1477 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index2 ON " + 1478 Tables.AGGREGATION_EXCEPTIONS + " (" + 1479 AggregationExceptions.RAW_CONTACT_ID2 + ", " + 1480 AggregationExceptions.RAW_CONTACT_ID1 + 1481 ");"); 1482 1483 db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.SETTINGS + " (" + 1484 Settings.ACCOUNT_NAME + " STRING NOT NULL," + 1485 Settings.ACCOUNT_TYPE + " STRING NOT NULL," + 1486 Settings.DATA_SET + " STRING," + 1487 Settings.UNGROUPED_VISIBLE + " INTEGER NOT NULL DEFAULT 0," + 1488 Settings.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1" + 1489 ");"); 1490 1491 db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" + 1492 Contacts._ID + " INTEGER PRIMARY KEY" + 1493 ");"); 1494 1495 db.execSQL("CREATE TABLE " + Tables.DEFAULT_DIRECTORY + " (" + 1496 Contacts._ID + " INTEGER PRIMARY KEY" + 1497 ");"); 1498 1499 // The table for recent calls is here so we can do table joins on people, phones, and 1500 // calls all in one place. 1501 // NOTE: When adding a new column to Tables.CALLS, make sure to also add it to 1502 // CallLogProvider.CALL_LOG_SYNC_PROJECTION, if it is a column that should be copied to 1503 // the call log of secondary users. 1504 db.execSQL("CREATE TABLE " + Tables.CALLS + " (" + 1505 Calls._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1506 Calls.NUMBER + " TEXT," + 1507 Calls.NUMBER_PRESENTATION + " INTEGER NOT NULL DEFAULT " + 1508 Calls.PRESENTATION_ALLOWED + "," + 1509 Calls.DATE + " INTEGER," + 1510 Calls.DURATION + " INTEGER," + 1511 Calls.DATA_USAGE + " INTEGER," + 1512 Calls.TYPE + " INTEGER," + 1513 Calls.FEATURES + " INTEGER NOT NULL DEFAULT 0," + 1514 Calls.PHONE_ACCOUNT_COMPONENT_NAME + " TEXT," + 1515 Calls.PHONE_ACCOUNT_ID + " TEXT," + 1516 Calls.PHONE_ACCOUNT_ADDRESS + " TEXT," + 1517 Calls.PHONE_ACCOUNT_HIDDEN + " INTEGER NOT NULL DEFAULT 0," + 1518 Calls.SUB_ID + " INTEGER DEFAULT -1," + 1519 Calls.NEW + " INTEGER," + 1520 Calls.CACHED_NAME + " TEXT," + 1521 Calls.CACHED_NUMBER_TYPE + " INTEGER," + 1522 Calls.CACHED_NUMBER_LABEL + " TEXT," + 1523 Calls.COUNTRY_ISO + " TEXT," + 1524 Calls.VOICEMAIL_URI + " TEXT," + 1525 Calls.IS_READ + " INTEGER," + 1526 Calls.GEOCODED_LOCATION + " TEXT," + 1527 Calls.CACHED_LOOKUP_URI + " TEXT," + 1528 Calls.CACHED_MATCHED_NUMBER + " TEXT," + 1529 Calls.CACHED_NORMALIZED_NUMBER + " TEXT," + 1530 Calls.CACHED_PHOTO_ID + " INTEGER NOT NULL DEFAULT 0," + 1531 Calls.CACHED_PHOTO_URI + " TEXT," + 1532 Calls.CACHED_FORMATTED_NUMBER + " TEXT," + 1533 Voicemails._DATA + " TEXT," + 1534 Voicemails.HAS_CONTENT + " INTEGER," + 1535 Voicemails.MIME_TYPE + " TEXT," + 1536 Voicemails.SOURCE_DATA + " TEXT," + 1537 Voicemails.SOURCE_PACKAGE + " TEXT," + 1538 Voicemails.TRANSCRIPTION + " TEXT," + 1539 Voicemails.STATE + " INTEGER," + 1540 Voicemails.DIRTY + " INTEGER NOT NULL DEFAULT 0," + 1541 Voicemails.DELETED + " INTEGER NOT NULL DEFAULT 0" + 1542 ");"); 1543 1544 // Voicemail source status table. 1545 db.execSQL("CREATE TABLE " + Tables.VOICEMAIL_STATUS + " (" + 1546 VoicemailContract.Status._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1547 VoicemailContract.Status.SOURCE_PACKAGE + " TEXT UNIQUE NOT NULL," + 1548 VoicemailContract.Status.PHONE_ACCOUNT_COMPONENT_NAME + " TEXT," + 1549 VoicemailContract.Status.PHONE_ACCOUNT_ID + " TEXT," + 1550 VoicemailContract.Status.SETTINGS_URI + " TEXT," + 1551 VoicemailContract.Status.VOICEMAIL_ACCESS_URI + " TEXT," + 1552 VoicemailContract.Status.CONFIGURATION_STATE + " INTEGER," + 1553 VoicemailContract.Status.DATA_CHANNEL_STATE + " INTEGER," + 1554 VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE + " INTEGER" + 1555 ");"); 1556 1557 db.execSQL("CREATE TABLE " + Tables.STATUS_UPDATES + " (" + 1558 StatusUpdatesColumns.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," + 1559 StatusUpdates.STATUS + " TEXT," + 1560 StatusUpdates.STATUS_TIMESTAMP + " INTEGER," + 1561 StatusUpdates.STATUS_RES_PACKAGE + " TEXT, " + 1562 StatusUpdates.STATUS_LABEL + " INTEGER, " + 1563 StatusUpdates.STATUS_ICON + " INTEGER" + 1564 ");"); 1565 1566 createDirectoriesTable(db); 1567 createSearchIndexTable(db, false /* we build stats table later */); 1568 1569 db.execSQL("CREATE TABLE " + Tables.DATA_USAGE_STAT + "(" + 1570 DataUsageStatColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 1571 DataUsageStatColumns.DATA_ID + " INTEGER NOT NULL, " + 1572 DataUsageStatColumns.USAGE_TYPE_INT + " INTEGER NOT NULL DEFAULT 0, " + 1573 DataUsageStatColumns.TIMES_USED + " INTEGER NOT NULL DEFAULT 0, " + 1574 DataUsageStatColumns.LAST_TIME_USED + " INTERGER NOT NULL DEFAULT 0, " + 1575 "FOREIGN KEY(" + DataUsageStatColumns.DATA_ID + ") REFERENCES " 1576 + Tables.DATA + "(" + Data._ID + ")" + 1577 ");"); 1578 db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " + 1579 Tables.DATA_USAGE_STAT + " (" + 1580 DataUsageStatColumns.DATA_ID + ", " + 1581 DataUsageStatColumns.USAGE_TYPE_INT + 1582 ");"); 1583 1584 db.execSQL("CREATE TABLE " + Tables.PRE_AUTHORIZED_URIS + " ("+ 1585 PreAuthorizedUris._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 1586 PreAuthorizedUris.URI + " STRING NOT NULL, " + 1587 PreAuthorizedUris.EXPIRATION + " INTEGER NOT NULL DEFAULT 0);"); 1588 1589 // When adding new tables, be sure to also add size-estimates in updateSqliteStats 1590 createContactsViews(db); 1591 createGroupsView(db); 1592 createContactsTriggers(db); 1593 createContactsIndexes(db, false /* we build stats table later */); 1594 1595 loadNicknameLookupTable(db); 1596 1597 // Set sequence starts. 1598 initializeAutoIncrementSequences(db); 1599 1600 // Add the legacy API support views, etc. 1601 LegacyApiSupport.createDatabase(db); 1602 1603 if (mDatabaseOptimizationEnabled) { 1604 // This will create a sqlite_stat1 table that is used for query optimization 1605 db.execSQL("ANALYZE;"); 1606 1607 updateSqliteStats(db); 1608 } 1609 1610 ContentResolver.requestSync(null /* all accounts */, 1611 ContactsContract.AUTHORITY, new Bundle()); 1612 1613 // Only send broadcasts for regular contacts db. 1614 if (dbForProfile() == 0) { 1615 final Intent dbCreatedIntent = new Intent( 1616 ContactsContract.Intents.CONTACTS_DATABASE_CREATED); 1617 dbCreatedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1618 mContext.sendBroadcast(dbCreatedIntent, android.Manifest.permission.READ_CONTACTS); 1619 } 1620 } 1621 1622 protected void initializeAutoIncrementSequences(SQLiteDatabase db) { 1623 // Default implementation does nothing. 1624 } 1625 1626 private void createDirectoriesTable(SQLiteDatabase db) { 1627 db.execSQL("CREATE TABLE " + Tables.DIRECTORIES + "(" + 1628 Directory._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1629 Directory.PACKAGE_NAME + " TEXT NOT NULL," + 1630 Directory.DIRECTORY_AUTHORITY + " TEXT NOT NULL," + 1631 Directory.TYPE_RESOURCE_ID + " INTEGER," + 1632 DirectoryColumns.TYPE_RESOURCE_NAME + " TEXT," + 1633 Directory.ACCOUNT_TYPE + " TEXT," + 1634 Directory.ACCOUNT_NAME + " TEXT," + 1635 Directory.DISPLAY_NAME + " TEXT, " + 1636 Directory.EXPORT_SUPPORT + " INTEGER NOT NULL" + 1637 " DEFAULT " + Directory.EXPORT_SUPPORT_NONE + "," + 1638 Directory.SHORTCUT_SUPPORT + " INTEGER NOT NULL" + 1639 " DEFAULT " + Directory.SHORTCUT_SUPPORT_NONE + "," + 1640 Directory.PHOTO_SUPPORT + " INTEGER NOT NULL" + 1641 " DEFAULT " + Directory.PHOTO_SUPPORT_NONE + 1642 ");"); 1643 1644 // Trigger a full scan of directories in the system 1645 setProperty(db, DbProperties.DIRECTORY_SCAN_COMPLETE, "0"); 1646 } 1647 1648 public void createSearchIndexTable(SQLiteDatabase db, boolean rebuildSqliteStats) { 1649 db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_INDEX); 1650 db.execSQL("CREATE VIRTUAL TABLE " + Tables.SEARCH_INDEX 1651 + " USING FTS4 (" 1652 + SearchIndexColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id) NOT NULL," 1653 + SearchIndexColumns.CONTENT + " TEXT, " 1654 + SearchIndexColumns.NAME + " TEXT, " 1655 + SearchIndexColumns.TOKENS + " TEXT" 1656 + ")"); 1657 if (rebuildSqliteStats) { 1658 updateSqliteStats(db); 1659 } 1660 } 1661 1662 private void createContactsTriggers(SQLiteDatabase db) { 1663 1664 // Automatically delete Data rows when a raw contact is deleted. 1665 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;"); 1666 db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted " 1667 + " BEFORE DELETE ON " + Tables.RAW_CONTACTS 1668 + " BEGIN " 1669 + " DELETE FROM " + Tables.DATA 1670 + " WHERE " + Data.RAW_CONTACT_ID 1671 + "=OLD." + RawContacts._ID + ";" 1672 + " DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS 1673 + " WHERE " + AggregationExceptions.RAW_CONTACT_ID1 1674 + "=OLD." + RawContacts._ID 1675 + " OR " + AggregationExceptions.RAW_CONTACT_ID2 1676 + "=OLD." + RawContacts._ID + ";" 1677 + " DELETE FROM " + Tables.VISIBLE_CONTACTS 1678 + " WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID 1679 + " AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS 1680 + " WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID 1681 + " )=1;" 1682 + " DELETE FROM " + Tables.DEFAULT_DIRECTORY 1683 + " WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID 1684 + " AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS 1685 + " WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID 1686 + " )=1;" 1687 + " DELETE FROM " + Tables.CONTACTS 1688 + " WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID 1689 + " AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS 1690 + " WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID 1691 + " )=1;" 1692 + " END"); 1693 1694 1695 db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;"); 1696 db.execSQL("DROP TRIGGER IF EXISTS raw_contacts_times_contacted;"); 1697 1698 // Triggers that update {@link RawContacts#VERSION} when the contact is marked for deletion 1699 // or any time a data row is inserted, updated or deleted. 1700 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;"); 1701 db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted " 1702 + " AFTER UPDATE ON " + Tables.RAW_CONTACTS 1703 + " BEGIN " 1704 + " UPDATE " + Tables.RAW_CONTACTS 1705 + " SET " 1706 + RawContacts.VERSION + "=OLD." + RawContacts.VERSION + "+1 " 1707 + " WHERE " + RawContacts._ID + "=OLD." + RawContacts._ID 1708 + " AND NEW." + RawContacts.DELETED + "!= OLD." + RawContacts.DELETED + ";" 1709 + " END"); 1710 1711 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_updated;"); 1712 db.execSQL("CREATE TRIGGER " + Tables.DATA + "_updated AFTER UPDATE ON " + Tables.DATA 1713 + " BEGIN " 1714 + " UPDATE " + Tables.DATA 1715 + " SET " + Data.DATA_VERSION + "=OLD." + Data.DATA_VERSION + "+1 " 1716 + " WHERE " + Data._ID + "=OLD." + Data._ID + ";" 1717 + " UPDATE " + Tables.RAW_CONTACTS 1718 + " SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 " 1719 + " WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";" 1720 + " END"); 1721 1722 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_deleted;"); 1723 db.execSQL("CREATE TRIGGER " + Tables.DATA + "_deleted BEFORE DELETE ON " + Tables.DATA 1724 + " BEGIN " 1725 + " UPDATE " + Tables.RAW_CONTACTS 1726 + " SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 " 1727 + " WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";" 1728 + " DELETE FROM " + Tables.PHONE_LOOKUP 1729 + " WHERE " + PhoneLookupColumns.DATA_ID + "=OLD." + Data._ID + ";" 1730 + " DELETE FROM " + Tables.STATUS_UPDATES 1731 + " WHERE " + StatusUpdatesColumns.DATA_ID + "=OLD." + Data._ID + ";" 1732 + " DELETE FROM " + Tables.NAME_LOOKUP 1733 + " WHERE " + NameLookupColumns.DATA_ID + "=OLD." + Data._ID + ";" 1734 + " END"); 1735 1736 1737 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_updated1;"); 1738 db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_updated1 " 1739 + " AFTER UPDATE ON " + Tables.GROUPS 1740 + " BEGIN " 1741 + " UPDATE " + Tables.GROUPS 1742 + " SET " 1743 + Groups.VERSION + "=OLD." + Groups.VERSION + "+1" 1744 + " WHERE " + Groups._ID + "=OLD." + Groups._ID + ";" 1745 + " END"); 1746 1747 // Update DEFAULT_FILTER table per AUTO_ADD column update, see upgradeToVersion411. 1748 final String insertContactsWithoutAccount = ( 1749 " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + 1750 " SELECT " + RawContacts.CONTACT_ID + 1751 " FROM " + Tables.RAW_CONTACTS + 1752 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_ID + 1753 "=" + Clauses.LOCAL_ACCOUNT_ID + ";"); 1754 1755 final String insertContactsWithAccountNoDefaultGroup = ( 1756 " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + 1757 " SELECT " + RawContacts.CONTACT_ID + 1758 " FROM " + Tables.RAW_CONTACTS + 1759 " WHERE NOT EXISTS" + 1760 " (SELECT " + Groups._ID + 1761 " FROM " + Tables.GROUPS + 1762 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_ID + " = " + 1763 GroupsColumns.CONCRETE_ACCOUNT_ID + 1764 " AND " + Groups.AUTO_ADD + " != 0" + ");"); 1765 1766 final String insertContactsWithAccountDefaultGroup = ( 1767 " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + 1768 " SELECT " + RawContacts.CONTACT_ID + 1769 " FROM " + Tables.RAW_CONTACTS + 1770 " JOIN " + Tables.DATA + 1771 " ON (" + RawContactsColumns.CONCRETE_ID + "=" + 1772 Data.RAW_CONTACT_ID + ")" + 1773 " WHERE " + DataColumns.MIMETYPE_ID + "=" + 1774 "(SELECT " + MimetypesColumns._ID + " FROM " + Tables.MIMETYPES + 1775 " WHERE " + MimetypesColumns.MIMETYPE + 1776 "='" + GroupMembership.CONTENT_ITEM_TYPE + "')" + 1777 " AND EXISTS" + 1778 " (SELECT " + Groups._ID + 1779 " FROM " + Tables.GROUPS + 1780 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_ID + " = " + 1781 GroupsColumns.CONCRETE_ACCOUNT_ID + 1782 " AND " + Groups.AUTO_ADD + " != 0" + ");"); 1783 1784 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_auto_add_updated1;"); 1785 db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_auto_add_updated1 " 1786 + " AFTER UPDATE OF " + Groups.AUTO_ADD + " ON " + Tables.GROUPS 1787 + " BEGIN " 1788 + " DELETE FROM " + Tables.DEFAULT_DIRECTORY + ";" 1789 + insertContactsWithoutAccount 1790 + insertContactsWithAccountNoDefaultGroup 1791 + insertContactsWithAccountDefaultGroup 1792 + " END"); 1793 } 1794 1795 private void createContactsIndexes(SQLiteDatabase db, boolean rebuildSqliteStats) { 1796 db.execSQL("DROP INDEX IF EXISTS name_lookup_index"); 1797 db.execSQL("CREATE INDEX name_lookup_index ON " + Tables.NAME_LOOKUP + " (" + 1798 NameLookupColumns.NORMALIZED_NAME + "," + 1799 NameLookupColumns.NAME_TYPE + ", " + 1800 NameLookupColumns.RAW_CONTACT_ID + ", " + 1801 NameLookupColumns.DATA_ID + 1802 ");"); 1803 1804 db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key1_index"); 1805 db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" + 1806 RawContacts.SORT_KEY_PRIMARY + 1807 ");"); 1808 1809 db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key2_index"); 1810 db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" + 1811 RawContacts.SORT_KEY_ALTERNATIVE + 1812 ");"); 1813 1814 if (rebuildSqliteStats) { 1815 updateSqliteStats(db); 1816 } 1817 } 1818 1819 private void createContactsViews(SQLiteDatabase db) { 1820 db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS + ";"); 1821 db.execSQL("DROP VIEW IF EXISTS " + Views.DATA + ";"); 1822 db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS + ";"); 1823 db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_ENTITIES + ";"); 1824 db.execSQL("DROP VIEW IF EXISTS " + Views.ENTITIES + ";"); 1825 db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_USAGE_STAT + ";"); 1826 db.execSQL("DROP VIEW IF EXISTS " + Views.STREAM_ITEMS + ";"); 1827 1828 String dataColumns = 1829 Data.IS_PRIMARY + ", " 1830 + Data.IS_SUPER_PRIMARY + ", " 1831 + Data.DATA_VERSION + ", " 1832 + DataColumns.CONCRETE_PACKAGE_ID + "," 1833 + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + "," 1834 + DataColumns.CONCRETE_MIMETYPE_ID + "," 1835 + MimetypesColumns.MIMETYPE + " AS " + Data.MIMETYPE + ", " 1836 + Data.IS_READ_ONLY + ", " 1837 + Data.DATA1 + ", " 1838 + Data.DATA2 + ", " 1839 + Data.DATA3 + ", " 1840 + Data.DATA4 + ", " 1841 + Data.DATA5 + ", " 1842 + Data.DATA6 + ", " 1843 + Data.DATA7 + ", " 1844 + Data.DATA8 + ", " 1845 + Data.DATA9 + ", " 1846 + Data.DATA10 + ", " 1847 + Data.DATA11 + ", " 1848 + Data.DATA12 + ", " 1849 + Data.DATA13 + ", " 1850 + Data.DATA14 + ", " 1851 + Data.DATA15 + ", " 1852 + Data.CARRIER_PRESENCE + ", " 1853 + Data.SYNC1 + ", " 1854 + Data.SYNC2 + ", " 1855 + Data.SYNC3 + ", " 1856 + Data.SYNC4; 1857 1858 String syncColumns = 1859 RawContactsColumns.CONCRETE_ACCOUNT_ID + "," 1860 + AccountsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + "," 1861 + AccountsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + "," 1862 + AccountsColumns.CONCRETE_DATA_SET + " AS " + RawContacts.DATA_SET + "," 1863 + "(CASE WHEN " + AccountsColumns.CONCRETE_DATA_SET + " IS NULL THEN " 1864 + AccountsColumns.CONCRETE_ACCOUNT_TYPE 1865 + " ELSE " + AccountsColumns.CONCRETE_ACCOUNT_TYPE + "||'/'||" 1866 + AccountsColumns.CONCRETE_DATA_SET + " END) AS " 1867 + RawContacts.ACCOUNT_TYPE_AND_DATA_SET + "," 1868 + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + "," 1869 + RawContactsColumns.CONCRETE_BACKUP_ID + " AS " + RawContacts.BACKUP_ID + "," 1870 + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + "," 1871 + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + "," 1872 + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + "," 1873 + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + "," 1874 + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + "," 1875 + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4; 1876 1877 String baseContactColumns = 1878 Contacts.HAS_PHONE_NUMBER + ", " 1879 + Contacts.NAME_RAW_CONTACT_ID + ", " 1880 + Contacts.LOOKUP_KEY + ", " 1881 + Contacts.PHOTO_ID + ", " 1882 + Contacts.PHOTO_FILE_ID + ", " 1883 + "CAST(" + Clauses.CONTACT_VISIBLE + " AS INTEGER) AS " 1884 + Contacts.IN_VISIBLE_GROUP + ", " 1885 + "CAST(" + Clauses.CONTACT_IN_DEFAULT_DIRECTORY + " AS INTEGER) AS " 1886 + Contacts.IN_DEFAULT_DIRECTORY + ", " 1887 + ContactsColumns.LAST_STATUS_UPDATE_ID + ", " 1888 + ContactsColumns.CONCRETE_CONTACT_LAST_UPDATED_TIMESTAMP; 1889 1890 String contactOptionColumns = 1891 ContactsColumns.CONCRETE_CUSTOM_RINGTONE 1892 + " AS " + RawContacts.CUSTOM_RINGTONE + "," 1893 + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL 1894 + " AS " + RawContacts.SEND_TO_VOICEMAIL + "," 1895 + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED 1896 + " AS " + RawContacts.LAST_TIME_CONTACTED + "," 1897 + ContactsColumns.CONCRETE_TIMES_CONTACTED 1898 + " AS " + RawContacts.TIMES_CONTACTED + "," 1899 + ContactsColumns.CONCRETE_STARRED 1900 + " AS " + RawContacts.STARRED + "," 1901 + ContactsColumns.CONCRETE_PINNED 1902 + " AS " + RawContacts.PINNED; 1903 1904 String contactNameColumns = 1905 "name_raw_contact." + RawContacts.DISPLAY_NAME_SOURCE 1906 + " AS " + Contacts.DISPLAY_NAME_SOURCE + ", " 1907 + "name_raw_contact." + RawContacts.DISPLAY_NAME_PRIMARY 1908 + " AS " + Contacts.DISPLAY_NAME_PRIMARY + ", " 1909 + "name_raw_contact." + RawContacts.DISPLAY_NAME_ALTERNATIVE 1910 + " AS " + Contacts.DISPLAY_NAME_ALTERNATIVE + ", " 1911 + "name_raw_contact." + RawContacts.PHONETIC_NAME 1912 + " AS " + Contacts.PHONETIC_NAME + ", " 1913 + "name_raw_contact." + RawContacts.PHONETIC_NAME_STYLE 1914 + " AS " + Contacts.PHONETIC_NAME_STYLE + ", " 1915 + "name_raw_contact." + RawContacts.SORT_KEY_PRIMARY 1916 + " AS " + Contacts.SORT_KEY_PRIMARY + ", " 1917 + "name_raw_contact." + RawContactsColumns.PHONEBOOK_LABEL_PRIMARY 1918 + " AS " + ContactsColumns.PHONEBOOK_LABEL_PRIMARY + ", " 1919 + "name_raw_contact." + RawContactsColumns.PHONEBOOK_BUCKET_PRIMARY 1920 + " AS " + ContactsColumns.PHONEBOOK_BUCKET_PRIMARY + ", " 1921 + "name_raw_contact." + RawContacts.SORT_KEY_ALTERNATIVE 1922 + " AS " + Contacts.SORT_KEY_ALTERNATIVE + ", " 1923 + "name_raw_contact." + RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE 1924 + " AS " + ContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE + ", " 1925 + "name_raw_contact." + RawContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE 1926 + " AS " + ContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE; 1927 1928 String dataSelect = "SELECT " 1929 + DataColumns.CONCRETE_ID + " AS " + Data._ID + "," 1930 + Data.HASH_ID + ", " 1931 + Data.RAW_CONTACT_ID + ", " 1932 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", " 1933 + syncColumns + ", " 1934 + dataColumns + ", " 1935 + contactOptionColumns + ", " 1936 + contactNameColumns + ", " 1937 + baseContactColumns + ", " 1938 + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 1939 Contacts.PHOTO_URI) + ", " 1940 + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 1941 Contacts.PHOTO_THUMBNAIL_URI) + ", " 1942 + dbForProfile() + " AS " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", " 1943 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID 1944 + " FROM " + Tables.DATA 1945 + " JOIN " + Tables.MIMETYPES + " ON (" 1946 + DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")" 1947 + " JOIN " + Tables.RAW_CONTACTS + " ON (" 1948 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")" 1949 + " JOIN " + Tables.ACCOUNTS + " ON (" 1950 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 1951 + ")" 1952 + " JOIN " + Tables.CONTACTS + " ON (" 1953 + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")" 1954 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON(" 1955 + Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")" 1956 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON (" 1957 + DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")" 1958 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON (" 1959 + MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE 1960 + "' AND " + GroupsColumns.CONCRETE_ID + "=" 1961 + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")"; 1962 1963 db.execSQL("CREATE VIEW " + Views.DATA + " AS " + dataSelect); 1964 1965 String rawContactOptionColumns = 1966 RawContacts.CUSTOM_RINGTONE + "," 1967 + RawContacts.SEND_TO_VOICEMAIL + "," 1968 + RawContacts.LAST_TIME_CONTACTED + "," 1969 + RawContacts.TIMES_CONTACTED + "," 1970 + RawContacts.STARRED + "," 1971 + RawContacts.PINNED; 1972 1973 String rawContactsSelect = "SELECT " 1974 + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + "," 1975 + RawContacts.CONTACT_ID + ", " 1976 + RawContacts.AGGREGATION_MODE + ", " 1977 + RawContacts.RAW_CONTACT_IS_READ_ONLY + ", " 1978 + RawContacts.DELETED + ", " 1979 + RawContacts.DISPLAY_NAME_SOURCE + ", " 1980 + RawContacts.DISPLAY_NAME_PRIMARY + ", " 1981 + RawContacts.DISPLAY_NAME_ALTERNATIVE + ", " 1982 + RawContacts.PHONETIC_NAME + ", " 1983 + RawContacts.PHONETIC_NAME_STYLE + ", " 1984 + RawContacts.SORT_KEY_PRIMARY + ", " 1985 + RawContactsColumns.PHONEBOOK_LABEL_PRIMARY + ", " 1986 + RawContactsColumns.PHONEBOOK_BUCKET_PRIMARY + ", " 1987 + RawContacts.SORT_KEY_ALTERNATIVE + ", " 1988 + RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE + ", " 1989 + RawContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + ", " 1990 + dbForProfile() + " AS " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", " 1991 + rawContactOptionColumns + ", " 1992 + syncColumns 1993 + " FROM " + Tables.RAW_CONTACTS 1994 + " JOIN " + Tables.ACCOUNTS + " ON (" 1995 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 1996 + ")"; 1997 1998 db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS + " AS " + rawContactsSelect); 1999 2000 String contactsColumns = 2001 ContactsColumns.CONCRETE_CUSTOM_RINGTONE 2002 + " AS " + Contacts.CUSTOM_RINGTONE + ", " 2003 + contactNameColumns + ", " 2004 + baseContactColumns + ", " 2005 + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED 2006 + " AS " + Contacts.LAST_TIME_CONTACTED + ", " 2007 + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL 2008 + " AS " + Contacts.SEND_TO_VOICEMAIL + ", " 2009 + ContactsColumns.CONCRETE_STARRED 2010 + " AS " + Contacts.STARRED + ", " 2011 + ContactsColumns.CONCRETE_PINNED 2012 + " AS " + Contacts.PINNED + ", " 2013 + ContactsColumns.CONCRETE_TIMES_CONTACTED 2014 + " AS " + Contacts.TIMES_CONTACTED; 2015 2016 String contactsSelect = "SELECT " 2017 + ContactsColumns.CONCRETE_ID + " AS " + Contacts._ID + "," 2018 + contactsColumns + ", " 2019 + buildDisplayPhotoUriAlias(ContactsColumns.CONCRETE_ID, Contacts.PHOTO_URI) + ", " 2020 + buildThumbnailPhotoUriAlias(ContactsColumns.CONCRETE_ID, 2021 Contacts.PHOTO_THUMBNAIL_URI) + ", " 2022 + dbForProfile() + " AS " + Contacts.IS_USER_PROFILE 2023 + " FROM " + Tables.CONTACTS 2024 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON(" 2025 + Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"; 2026 2027 db.execSQL("CREATE VIEW " + Views.CONTACTS + " AS " + contactsSelect); 2028 2029 String rawEntitiesSelect = "SELECT " 2030 + RawContacts.CONTACT_ID + ", " 2031 + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + "," 2032 + dataColumns + ", " 2033 + syncColumns + ", " 2034 + Data.SYNC1 + ", " 2035 + Data.SYNC2 + ", " 2036 + Data.SYNC3 + ", " 2037 + Data.SYNC4 + ", " 2038 + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ", " 2039 + DataColumns.CONCRETE_ID + " AS " + RawContacts.Entity.DATA_ID + "," 2040 + RawContactsColumns.CONCRETE_STARRED + " AS " + RawContacts.STARRED + "," 2041 + dbForProfile() + " AS " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "," 2042 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID 2043 + " FROM " + Tables.RAW_CONTACTS 2044 + " JOIN " + Tables.ACCOUNTS + " ON (" 2045 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 2046 + ")" 2047 + " LEFT OUTER JOIN " + Tables.DATA + " ON (" 2048 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")" 2049 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON (" 2050 + DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")" 2051 + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON (" 2052 + DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")" 2053 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON (" 2054 + MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE 2055 + "' AND " + GroupsColumns.CONCRETE_ID + "=" 2056 + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")"; 2057 2058 db.execSQL("CREATE VIEW " + Views.RAW_ENTITIES + " AS " 2059 + rawEntitiesSelect); 2060 2061 String entitiesSelect = "SELECT " 2062 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + Contacts._ID + ", " 2063 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", " 2064 + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + "," 2065 + dataColumns + ", " 2066 + syncColumns + ", " 2067 + contactsColumns + ", " 2068 + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 2069 Contacts.PHOTO_URI) + ", " 2070 + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 2071 Contacts.PHOTO_THUMBNAIL_URI) + ", " 2072 + dbForProfile() + " AS " + Contacts.IS_USER_PROFILE + ", " 2073 + Data.SYNC1 + ", " 2074 + Data.SYNC2 + ", " 2075 + Data.SYNC3 + ", " 2076 + Data.SYNC4 + ", " 2077 + RawContactsColumns.CONCRETE_ID + " AS " + Contacts.Entity.RAW_CONTACT_ID + ", " 2078 + DataColumns.CONCRETE_ID + " AS " + Contacts.Entity.DATA_ID + "," 2079 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID 2080 + " FROM " + Tables.RAW_CONTACTS 2081 + " JOIN " + Tables.ACCOUNTS + " ON (" 2082 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 2083 + ")" 2084 + " JOIN " + Tables.CONTACTS + " ON (" 2085 + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")" 2086 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON(" 2087 + Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")" 2088 + " LEFT OUTER JOIN " + Tables.DATA + " ON (" 2089 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")" 2090 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON (" 2091 + DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")" 2092 + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON (" 2093 + DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")" 2094 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON (" 2095 + MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE 2096 + "' AND " + GroupsColumns.CONCRETE_ID + "=" 2097 + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")"; 2098 2099 db.execSQL("CREATE VIEW " + Views.ENTITIES + " AS " 2100 + entitiesSelect); 2101 2102 String dataUsageStatSelect = "SELECT " 2103 + DataUsageStatColumns.CONCRETE_ID + " AS " + DataUsageStatColumns._ID + ", " 2104 + DataUsageStatColumns.DATA_ID + ", " 2105 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", " 2106 + MimetypesColumns.CONCRETE_MIMETYPE + " AS " + Data.MIMETYPE + ", " 2107 + DataUsageStatColumns.USAGE_TYPE_INT + ", " 2108 + DataUsageStatColumns.TIMES_USED + ", " 2109 + DataUsageStatColumns.LAST_TIME_USED 2110 + " FROM " + Tables.DATA_USAGE_STAT 2111 + " JOIN " + Tables.DATA + " ON (" 2112 + DataColumns.CONCRETE_ID + "=" + DataUsageStatColumns.CONCRETE_DATA_ID + ")" 2113 + " JOIN " + Tables.RAW_CONTACTS + " ON (" 2114 + RawContactsColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_RAW_CONTACT_ID 2115 + " )" 2116 + " JOIN " + Tables.MIMETYPES + " ON (" 2117 + MimetypesColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_MIMETYPE_ID + ")"; 2118 2119 db.execSQL("CREATE VIEW " + Views.DATA_USAGE_STAT + " AS " + dataUsageStatSelect); 2120 2121 String streamItemSelect = "SELECT " + 2122 StreamItemsColumns.CONCRETE_ID + ", " + 2123 ContactsColumns.CONCRETE_ID + " AS " + StreamItems.CONTACT_ID + ", " + 2124 ContactsColumns.CONCRETE_LOOKUP_KEY + 2125 " AS " + StreamItems.CONTACT_LOOKUP_KEY + ", " + 2126 AccountsColumns.CONCRETE_ACCOUNT_NAME + ", " + 2127 AccountsColumns.CONCRETE_ACCOUNT_TYPE + ", " + 2128 AccountsColumns.CONCRETE_DATA_SET + ", " + 2129 StreamItemsColumns.CONCRETE_RAW_CONTACT_ID + 2130 " as " + StreamItems.RAW_CONTACT_ID + ", " + 2131 RawContactsColumns.CONCRETE_SOURCE_ID + 2132 " as " + StreamItems.RAW_CONTACT_SOURCE_ID + ", " + 2133 StreamItemsColumns.CONCRETE_PACKAGE + ", " + 2134 StreamItemsColumns.CONCRETE_ICON + ", " + 2135 StreamItemsColumns.CONCRETE_LABEL + ", " + 2136 StreamItemsColumns.CONCRETE_TEXT + ", " + 2137 StreamItemsColumns.CONCRETE_TIMESTAMP + ", " + 2138 StreamItemsColumns.CONCRETE_COMMENTS + ", " + 2139 StreamItemsColumns.CONCRETE_SYNC1 + ", " + 2140 StreamItemsColumns.CONCRETE_SYNC2 + ", " + 2141 StreamItemsColumns.CONCRETE_SYNC3 + ", " + 2142 StreamItemsColumns.CONCRETE_SYNC4 + 2143 " FROM " + Tables.STREAM_ITEMS 2144 + " JOIN " + Tables.RAW_CONTACTS + " ON (" 2145 + StreamItemsColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID 2146 + ")" 2147 + " JOIN " + Tables.ACCOUNTS + " ON (" 2148 + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID 2149 + ")" 2150 + " JOIN " + Tables.CONTACTS + " ON (" 2151 + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"; 2152 2153 db.execSQL("CREATE VIEW " + Views.STREAM_ITEMS + " AS " + streamItemSelect); 2154 } 2155 2156 private static String buildDisplayPhotoUriAlias(String contactIdColumn, String alias) { 2157 return "(CASE WHEN " + Contacts.PHOTO_FILE_ID + " IS NULL THEN (CASE WHEN " 2158 + Contacts.PHOTO_ID + " IS NULL" 2159 + " OR " + Contacts.PHOTO_ID + "=0" 2160 + " THEN NULL" 2161 + " ELSE '" + Contacts.CONTENT_URI + "/'||" 2162 + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'" 2163 + " END) ELSE '" + DisplayPhoto.CONTENT_URI + "/'||" 2164 + Contacts.PHOTO_FILE_ID + " END)" 2165 + " AS " + alias; 2166 } 2167 2168 private static String buildThumbnailPhotoUriAlias(String contactIdColumn, String alias) { 2169 return "(CASE WHEN " 2170 + Contacts.PHOTO_ID + " IS NULL" 2171 + " OR " + Contacts.PHOTO_ID + "=0" 2172 + " THEN NULL" 2173 + " ELSE '" + Contacts.CONTENT_URI + "/'||" 2174 + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'" 2175 + " END)" 2176 + " AS " + alias; 2177 } 2178 2179 /** 2180 * Returns the value to be returned when querying the column indicating that the contact 2181 * or raw contact belongs to the user's personal profile. Overridden in the profile 2182 * DB helper subclass. 2183 */ 2184 protected int dbForProfile() { 2185 return 0; 2186 } 2187 2188 private void createGroupsView(SQLiteDatabase db) { 2189 db.execSQL("DROP VIEW IF EXISTS " + Views.GROUPS + ";"); 2190 2191 String groupsColumns = 2192 GroupsColumns.CONCRETE_ACCOUNT_ID + " AS " + GroupsColumns.ACCOUNT_ID + "," 2193 + AccountsColumns.CONCRETE_ACCOUNT_NAME + " AS " + Groups.ACCOUNT_NAME + "," 2194 + AccountsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + Groups.ACCOUNT_TYPE + "," 2195 + AccountsColumns.CONCRETE_DATA_SET + " AS " + Groups.DATA_SET + "," 2196 + "(CASE WHEN " + AccountsColumns.CONCRETE_DATA_SET 2197 + " IS NULL THEN " + AccountsColumns.CONCRETE_ACCOUNT_TYPE 2198 + " ELSE " + AccountsColumns.CONCRETE_ACCOUNT_TYPE 2199 + "||'/'||" + AccountsColumns.CONCRETE_DATA_SET + " END) AS " 2200 + Groups.ACCOUNT_TYPE_AND_DATA_SET + "," 2201 + Groups.SOURCE_ID + "," 2202 + Groups.VERSION + "," 2203 + Groups.DIRTY + "," 2204 + Groups.TITLE + "," 2205 + Groups.TITLE_RES + "," 2206 + Groups.NOTES + "," 2207 + Groups.SYSTEM_ID + "," 2208 + Groups.DELETED + "," 2209 + Groups.GROUP_VISIBLE + "," 2210 + Groups.SHOULD_SYNC + "," 2211 + Groups.AUTO_ADD + "," 2212 + Groups.FAVORITES + "," 2213 + Groups.GROUP_IS_READ_ONLY + "," 2214 + Groups.SYNC1 + "," 2215 + Groups.SYNC2 + "," 2216 + Groups.SYNC3 + "," 2217 + Groups.SYNC4 + "," 2218 + PackagesColumns.PACKAGE + " AS " + Groups.RES_PACKAGE; 2219 2220 String groupsSelect = "SELECT " 2221 + GroupsColumns.CONCRETE_ID + " AS " + Groups._ID + "," 2222 + groupsColumns 2223 + " FROM " + Tables.GROUPS 2224 + " JOIN " + Tables.ACCOUNTS + " ON (" 2225 + GroupsColumns.CONCRETE_ACCOUNT_ID + "=" + AccountsColumns.CONCRETE_ID + ")" 2226 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON (" 2227 + GroupsColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")"; 2228 2229 db.execSQL("CREATE VIEW " + Views.GROUPS + " AS " + groupsSelect); 2230 } 2231 2232 @Override 2233 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { 2234 Log.i(TAG, "ContactsProvider cannot proceed because downgrading your database is not " + 2235 "supported. To continue, please either re-upgrade to your previous Android " + 2236 "version, or clear all application data in Contacts Storage (this will result " + 2237 "in the loss of all local contacts that are not synced). To avoid data loss, " + 2238 "your contacts database will not be wiped automatically."); 2239 super.onDowngrade(db, oldVersion, newVersion); 2240 } 2241 2242 @Override 2243 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 2244 if (oldVersion < 99) { 2245 Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion 2246 + ", data will be lost!"); 2247 2248 db.execSQL("DROP TABLE IF EXISTS " + Tables.CONTACTS + ";"); 2249 db.execSQL("DROP TABLE IF EXISTS " + Tables.RAW_CONTACTS + ";"); 2250 db.execSQL("DROP TABLE IF EXISTS " + Tables.PACKAGES + ";"); 2251 db.execSQL("DROP TABLE IF EXISTS " + Tables.MIMETYPES + ";"); 2252 db.execSQL("DROP TABLE IF EXISTS " + Tables.DATA + ";"); 2253 db.execSQL("DROP TABLE IF EXISTS " + Tables.PHONE_LOOKUP + ";"); 2254 db.execSQL("DROP TABLE IF EXISTS " + Tables.NAME_LOOKUP + ";"); 2255 db.execSQL("DROP TABLE IF EXISTS " + Tables.NICKNAME_LOOKUP + ";"); 2256 db.execSQL("DROP TABLE IF EXISTS " + Tables.GROUPS + ";"); 2257 db.execSQL("DROP TABLE IF EXISTS activities;"); 2258 db.execSQL("DROP TABLE IF EXISTS " + Tables.CALLS + ";"); 2259 db.execSQL("DROP TABLE IF EXISTS " + Tables.SETTINGS + ";"); 2260 db.execSQL("DROP TABLE IF EXISTS " + Tables.STATUS_UPDATES + ";"); 2261 2262 // TODO: we should not be dropping agg_exceptions and contact_options. In case that 2263 // table's schema changes, we should try to preserve the data, because it was entered 2264 // by the user and has never been synched to the server. 2265 db.execSQL("DROP TABLE IF EXISTS " + Tables.AGGREGATION_EXCEPTIONS + ";"); 2266 2267 onCreate(db); 2268 return; 2269 } 2270 2271 Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion); 2272 2273 boolean upgradeViewsAndTriggers = false; 2274 boolean upgradeNameLookup = false; 2275 boolean upgradeLegacyApiSupport = false; 2276 boolean upgradeSearchIndex = false; 2277 boolean rescanDirectories = false; 2278 boolean rebuildSqliteStats = false; 2279 boolean upgradeLocaleSpecificData = false; 2280 2281 if (oldVersion == 99) { 2282 upgradeViewsAndTriggers = true; 2283 oldVersion++; 2284 } 2285 2286 if (oldVersion == 100) { 2287 db.execSQL("CREATE INDEX IF NOT EXISTS mimetypes_mimetype_index ON " 2288 + Tables.MIMETYPES + " (" 2289 + MimetypesColumns.MIMETYPE + "," 2290 + MimetypesColumns._ID + ");"); 2291 updateIndexStats(db, Tables.MIMETYPES, 2292 "mimetypes_mimetype_index", "50 1 1"); 2293 2294 upgradeViewsAndTriggers = true; 2295 oldVersion++; 2296 } 2297 2298 if (oldVersion == 101) { 2299 upgradeViewsAndTriggers = true; 2300 oldVersion++; 2301 } 2302 2303 if (oldVersion == 102) { 2304 upgradeViewsAndTriggers = true; 2305 oldVersion++; 2306 } 2307 2308 if (oldVersion == 103) { 2309 upgradeViewsAndTriggers = true; 2310 oldVersion++; 2311 } 2312 2313 if (oldVersion == 104 || oldVersion == 201) { 2314 LegacyApiSupport.createSettingsTable(db); 2315 upgradeViewsAndTriggers = true; 2316 oldVersion++; 2317 } 2318 2319 if (oldVersion == 105) { 2320 upgradeToVersion202(db); 2321 upgradeNameLookup = true; 2322 oldVersion = 202; 2323 } 2324 2325 if (oldVersion == 202) { 2326 upgradeToVersion203(db); 2327 upgradeViewsAndTriggers = true; 2328 oldVersion++; 2329 } 2330 2331 if (oldVersion == 203) { 2332 upgradeViewsAndTriggers = true; 2333 oldVersion++; 2334 } 2335 2336 if (oldVersion == 204) { 2337 upgradeToVersion205(db); 2338 upgradeViewsAndTriggers = true; 2339 oldVersion++; 2340 } 2341 2342 if (oldVersion == 205) { 2343 upgrateToVersion206(db); 2344 upgradeViewsAndTriggers = true; 2345 oldVersion++; 2346 } 2347 2348 if (oldVersion == 206) { 2349 // Fix for the bug where name lookup records for organizations would get removed by 2350 // unrelated updates of the data rows. No longer needed. 2351 oldVersion = 300; 2352 } 2353 2354 if (oldVersion == 300) { 2355 upgradeViewsAndTriggers = true; 2356 oldVersion = 301; 2357 } 2358 2359 if (oldVersion == 301) { 2360 upgradeViewsAndTriggers = true; 2361 oldVersion = 302; 2362 } 2363 2364 if (oldVersion == 302) { 2365 upgradeEmailToVersion303(db); 2366 upgradeNicknameToVersion303(db); 2367 oldVersion = 303; 2368 } 2369 2370 if (oldVersion == 303) { 2371 upgradeToVersion304(db); 2372 oldVersion = 304; 2373 } 2374 2375 if (oldVersion == 304) { 2376 upgradeNameLookup = true; 2377 oldVersion = 305; 2378 } 2379 2380 if (oldVersion == 305) { 2381 upgradeToVersion306(db); 2382 oldVersion = 306; 2383 } 2384 2385 if (oldVersion == 306) { 2386 upgradeToVersion307(db); 2387 oldVersion = 307; 2388 } 2389 2390 if (oldVersion == 307) { 2391 upgradeToVersion308(db); 2392 oldVersion = 308; 2393 } 2394 2395 // Gingerbread upgrades. 2396 if (oldVersion < 350) { 2397 upgradeViewsAndTriggers = true; 2398 oldVersion = 351; 2399 } 2400 2401 if (oldVersion == 351) { 2402 upgradeNameLookup = true; 2403 oldVersion = 352; 2404 } 2405 2406 if (oldVersion == 352) { 2407 upgradeToVersion353(db); 2408 oldVersion = 353; 2409 } 2410 2411 // Honeycomb upgrades. 2412 if (oldVersion < 400) { 2413 upgradeViewsAndTriggers = true; 2414 upgradeToVersion400(db); 2415 oldVersion = 400; 2416 } 2417 2418 if (oldVersion == 400) { 2419 upgradeViewsAndTriggers = true; 2420 upgradeToVersion401(db); 2421 oldVersion = 401; 2422 } 2423 2424 if (oldVersion == 401) { 2425 upgradeToVersion402(db); 2426 oldVersion = 402; 2427 } 2428 2429 if (oldVersion == 402) { 2430 upgradeViewsAndTriggers = true; 2431 upgradeToVersion403(db); 2432 oldVersion = 403; 2433 } 2434 2435 if (oldVersion == 403) { 2436 upgradeViewsAndTriggers = true; 2437 oldVersion = 404; 2438 } 2439 2440 if (oldVersion == 404) { 2441 upgradeViewsAndTriggers = true; 2442 upgradeToVersion405(db); 2443 oldVersion = 405; 2444 } 2445 2446 if (oldVersion == 405) { 2447 upgradeViewsAndTriggers = true; 2448 upgradeToVersion406(db); 2449 oldVersion = 406; 2450 } 2451 2452 if (oldVersion == 406) { 2453 upgradeViewsAndTriggers = true; 2454 oldVersion = 407; 2455 } 2456 2457 if (oldVersion == 407) { 2458 oldVersion = 408; // Obsolete. 2459 } 2460 2461 if (oldVersion == 408) { 2462 upgradeViewsAndTriggers = true; 2463 upgradeToVersion409(db); 2464 oldVersion = 409; 2465 } 2466 2467 if (oldVersion == 409) { 2468 upgradeViewsAndTriggers = true; 2469 oldVersion = 410; 2470 } 2471 2472 if (oldVersion == 410) { 2473 upgradeToVersion411(db); 2474 oldVersion = 411; 2475 } 2476 2477 if (oldVersion == 411) { 2478 // Same upgrade as 353, only on Honeycomb devices. 2479 upgradeToVersion353(db); 2480 oldVersion = 412; 2481 } 2482 2483 if (oldVersion == 412) { 2484 upgradeToVersion413(db); 2485 oldVersion = 413; 2486 } 2487 2488 if (oldVersion == 413) { 2489 upgradeNameLookup = true; 2490 oldVersion = 414; 2491 } 2492 2493 if (oldVersion == 414) { 2494 upgradeToVersion415(db); 2495 upgradeViewsAndTriggers = true; 2496 oldVersion = 415; 2497 } 2498 2499 if (oldVersion == 415) { 2500 upgradeToVersion416(db); 2501 oldVersion = 416; 2502 } 2503 2504 if (oldVersion == 416) { 2505 upgradeLegacyApiSupport = true; 2506 oldVersion = 417; 2507 } 2508 2509 // Honeycomb-MR1 upgrades. 2510 if (oldVersion < 500) { 2511 upgradeSearchIndex = true; 2512 } 2513 2514 if (oldVersion < 501) { 2515 upgradeSearchIndex = true; 2516 upgradeToVersion501(db); 2517 oldVersion = 501; 2518 } 2519 2520 if (oldVersion < 502) { 2521 upgradeSearchIndex = true; 2522 upgradeToVersion502(db); 2523 oldVersion = 502; 2524 } 2525 2526 if (oldVersion < 503) { 2527 upgradeSearchIndex = true; 2528 oldVersion = 503; 2529 } 2530 2531 if (oldVersion < 504) { 2532 upgradeToVersion504(db); 2533 oldVersion = 504; 2534 } 2535 2536 if (oldVersion < 600) { 2537 // This change used to add the profile raw contact ID to the Accounts table. That 2538 // column is no longer needed (as of version 614) since the profile records are stored in 2539 // a separate copy of the database for security reasons. So this change is now a no-op. 2540 upgradeViewsAndTriggers = true; 2541 oldVersion = 600; 2542 } 2543 2544 if (oldVersion < 601) { 2545 upgradeToVersion601(db); 2546 oldVersion = 601; 2547 } 2548 2549 if (oldVersion < 602) { 2550 upgradeToVersion602(db); 2551 oldVersion = 602; 2552 } 2553 2554 if (oldVersion < 603) { 2555 upgradeViewsAndTriggers = true; 2556 oldVersion = 603; 2557 } 2558 2559 if (oldVersion < 604) { 2560 upgradeToVersion604(db); 2561 oldVersion = 604; 2562 } 2563 2564 if (oldVersion < 605) { 2565 upgradeViewsAndTriggers = true; 2566 // This version used to create the stream item and stream item photos tables, but 2567 // a newer version of those tables is created in version 609 below. So omitting the 2568 // creation in this upgrade step to avoid a create->drop->create. 2569 oldVersion = 605; 2570 } 2571 2572 if (oldVersion < 606) { 2573 upgradeViewsAndTriggers = true; 2574 upgradeLegacyApiSupport = true; 2575 upgradeToVersion606(db); 2576 oldVersion = 606; 2577 } 2578 2579 if (oldVersion < 607) { 2580 upgradeViewsAndTriggers = true; 2581 // We added "action" and "action_uri" to groups here, but realized this was not a smart 2582 // move. This upgrade step has been removed (all dogfood phones that executed this step 2583 // will have those columns, but that shouldn't hurt. Unfortunately, SQLite makes it 2584 // hard to remove columns). 2585 oldVersion = 607; 2586 } 2587 2588 if (oldVersion < 608) { 2589 upgradeViewsAndTriggers = true; 2590 upgradeToVersion608(db); 2591 oldVersion = 608; 2592 } 2593 2594 if (oldVersion < 609) { 2595 // This version used to create the stream item and stream item photos tables, but a 2596 // newer version of those tables is created in version 613 below. So omitting the 2597 // creation in this upgrade step to avoid a create->drop->create. 2598 oldVersion = 609; 2599 } 2600 2601 if (oldVersion < 610) { 2602 upgradeToVersion610(db); 2603 oldVersion = 610; 2604 } 2605 2606 if (oldVersion < 611) { 2607 upgradeViewsAndTriggers = true; 2608 upgradeToVersion611(db); 2609 oldVersion = 611; 2610 } 2611 2612 if (oldVersion < 612) { 2613 upgradeViewsAndTriggers = true; 2614 upgradeToVersion612(db); 2615 oldVersion = 612; 2616 } 2617 2618 if (oldVersion < 613) { 2619 upgradeToVersion613(db); 2620 oldVersion = 613; 2621 } 2622 2623 if (oldVersion < 614) { 2624 // This creates the "view_stream_items" view. 2625 upgradeViewsAndTriggers = true; 2626 oldVersion = 614; 2627 } 2628 2629 if (oldVersion < 615) { 2630 upgradeToVersion615(db); 2631 oldVersion = 615; 2632 } 2633 2634 if (oldVersion < 616) { 2635 // This updates the "view_stream_items" view. 2636 upgradeViewsAndTriggers = true; 2637 oldVersion = 616; 2638 } 2639 2640 if (oldVersion < 617) { 2641 // This version upgrade obsoleted the profile_raw_contact_id field of the Accounts 2642 // table, but we aren't removing the column because it is very little data (and not 2643 // referenced anymore). We do need to upgrade the views to handle the simplified 2644 // per-database "is profile" columns. 2645 upgradeViewsAndTriggers = true; 2646 oldVersion = 617; 2647 } 2648 2649 if (oldVersion < 618) { 2650 upgradeToVersion618(db); 2651 oldVersion = 618; 2652 } 2653 2654 if (oldVersion < 619) { 2655 upgradeViewsAndTriggers = true; 2656 oldVersion = 619; 2657 } 2658 2659 if (oldVersion < 620) { 2660 upgradeViewsAndTriggers = true; 2661 oldVersion = 620; 2662 } 2663 2664 if (oldVersion < 621) { 2665 upgradeSearchIndex = true; 2666 oldVersion = 621; 2667 } 2668 2669 if (oldVersion < 622) { 2670 upgradeToVersion622(db); 2671 oldVersion = 622; 2672 } 2673 2674 if (oldVersion < 623) { 2675 // Change FTS to normalize names using collation key. 2676 upgradeSearchIndex = true; 2677 oldVersion = 623; 2678 } 2679 2680 if (oldVersion < 624) { 2681 // Upgraded the SQLite index stats. 2682 upgradeViewsAndTriggers = true; 2683 oldVersion = 624; 2684 } 2685 2686 if (oldVersion < 625) { 2687 // Fix for search for hyphenated names 2688 upgradeSearchIndex = true; 2689 oldVersion = 625; 2690 } 2691 2692 if (oldVersion < 626) { 2693 upgradeToVersion626(db); 2694 upgradeViewsAndTriggers = true; 2695 oldVersion = 626; 2696 } 2697 2698 if (oldVersion < 700) { 2699 rescanDirectories = true; 2700 oldVersion = 700; 2701 } 2702 2703 if (oldVersion < 701) { 2704 upgradeToVersion701(db); 2705 oldVersion = 701; 2706 } 2707 2708 if (oldVersion < 702) { 2709 upgradeToVersion702(db); 2710 oldVersion = 702; 2711 } 2712 2713 if (oldVersion < 703) { 2714 // Now names like "L'Image" will be searchable. 2715 upgradeSearchIndex = true; 2716 oldVersion = 703; 2717 } 2718 2719 if (oldVersion < 704) { 2720 db.execSQL("DROP TABLE IF EXISTS activities;"); 2721 oldVersion = 704; 2722 } 2723 2724 if (oldVersion < 705) { 2725 // Before this version, we didn't rebuild the search index on locale changes, so 2726 // if the locale has changed after sync, the index contains gets stale. 2727 // To correct the issue we have to rebuild the index here. 2728 upgradeSearchIndex = true; 2729 oldVersion = 705; 2730 } 2731 2732 if (oldVersion < 706) { 2733 // Prior to this version, we didn't rebuild the stats table after drop operations, 2734 // which resulted in losing some of the rows from the stats table. 2735 rebuildSqliteStats = true; 2736 oldVersion = 706; 2737 } 2738 2739 if (oldVersion < 707) { 2740 upgradeToVersion707(db); 2741 upgradeViewsAndTriggers = true; 2742 oldVersion = 707; 2743 } 2744 2745 if (oldVersion < 708) { 2746 // Sort keys, phonebook labels and buckets, and search keys have 2747 // changed so force a rebuild. 2748 upgradeLocaleSpecificData = true; 2749 oldVersion = 708; 2750 } 2751 if (oldVersion < 709) { 2752 // Added secondary locale phonebook labels; changed Japanese 2753 // and Chinese sort keys. 2754 upgradeLocaleSpecificData = true; 2755 oldVersion = 709; 2756 } 2757 2758 if (oldVersion < 710) { 2759 upgradeToVersion710(db); 2760 upgradeViewsAndTriggers = true; 2761 oldVersion = 710; 2762 } 2763 2764 if (oldVersion < 800) { 2765 upgradeToVersion800(db); 2766 oldVersion = 800; 2767 } 2768 2769 if (oldVersion < 801) { 2770 setProperty(db, DbProperties.DATABASE_TIME_CREATED, String.valueOf( 2771 System.currentTimeMillis())); 2772 oldVersion = 801; 2773 } 2774 2775 if (oldVersion < 802) { 2776 upgradeToVersion802(db); 2777 upgradeViewsAndTriggers = true; 2778 oldVersion = 802; 2779 } 2780 2781 if (oldVersion < 803) { 2782 // Rebuild the search index so that names, organizations and nicknames are 2783 // now indexed as names. 2784 upgradeSearchIndex = true; 2785 oldVersion = 803; 2786 } 2787 2788 if (oldVersion < 804) { 2789 // Reserved. 2790 oldVersion = 804; 2791 } 2792 2793 if (oldVersion < 900) { 2794 upgradeViewsAndTriggers = true; 2795 oldVersion = 900; 2796 } 2797 2798 if (oldVersion < 901) { 2799 // Rebuild the search index to fix any search index that was previously in a 2800 // broken state due to b/11059351 2801 upgradeSearchIndex = true; 2802 oldVersion = 901; 2803 } 2804 2805 if (oldVersion < 902) { 2806 upgradeToVersion902(db); 2807 oldVersion = 902; 2808 } 2809 2810 if (oldVersion < 903) { 2811 upgradeToVersion903(db); 2812 oldVersion = 903; 2813 } 2814 2815 if (oldVersion < 904) { 2816 upgradeToVersion904(db); 2817 oldVersion = 904; 2818 } 2819 2820 if (oldVersion < 905) { 2821 upgradeToVersion905(db); 2822 oldVersion = 905; 2823 } 2824 2825 if (oldVersion < 906) { 2826 upgradeToVersion906(db); 2827 oldVersion = 906; 2828 } 2829 2830 if (oldVersion < 907) { 2831 // Rebuild NAME_LOOKUP. 2832 upgradeNameLookup = true; 2833 oldVersion = 907; 2834 } 2835 2836 if (oldVersion < 908) { 2837 upgradeToVersion908(db); 2838 oldVersion = 908; 2839 } 2840 2841 if (oldVersion < 909) { 2842 upgradeToVersion909(db); 2843 oldVersion = 909; 2844 } 2845 2846 if (oldVersion < 910) { 2847 upgradeToVersion910(db); 2848 oldVersion = 910; 2849 } 2850 if (oldVersion < 1000) { 2851 upgradeToVersion1000(db); 2852 upgradeViewsAndTriggers = true; 2853 oldVersion = 1000; 2854 } 2855 2856 if (oldVersion < 1002) { 2857 rebuildSqliteStats = true; 2858 upgradeToVersion1002(db); 2859 oldVersion = 1002; 2860 } 2861 2862 if (oldVersion < 1003) { 2863 upgradeToVersion1003(db); 2864 oldVersion = 1003; 2865 } 2866 2867 if (oldVersion < 1004) { 2868 upgradeToVersion1004(db); 2869 oldVersion = 1004; 2870 } 2871 2872 if (oldVersion < 1005) { 2873 upgradeToVersion1005(db); 2874 oldVersion = 1005; 2875 } 2876 2877 if (oldVersion < 1006) { 2878 upgradeViewsAndTriggers = true; 2879 oldVersion = 1006; 2880 } 2881 2882 if (oldVersion < 1007) { 2883 upgradeToVersion1007(db); 2884 oldVersion = 1007; 2885 } 2886 2887 if (oldVersion < 1009) { 2888 upgradeToVersion1009(db); 2889 oldVersion = 1009; 2890 } 2891 2892 if (oldVersion < 1010) { 2893 upgradeToVersion1010(db); 2894 rebuildSqliteStats = true; 2895 oldVersion = 1010; 2896 } 2897 2898 if (oldVersion < 1011) { 2899 // There was a merge error, so do step1010 again, and also re-crete views. 2900 // upgradeToVersion1010() is safe to re-run. 2901 upgradeToVersion1010(db); 2902 rebuildSqliteStats = true; 2903 upgradeViewsAndTriggers = true; 2904 oldVersion = 1011; 2905 } 2906 2907 if (upgradeViewsAndTriggers) { 2908 createContactsViews(db); 2909 createGroupsView(db); 2910 createContactsTriggers(db); 2911 createContactsIndexes(db, false /* we build stats table later */); 2912 upgradeLegacyApiSupport = true; 2913 rebuildSqliteStats = true; 2914 } 2915 2916 if (upgradeLegacyApiSupport) { 2917 LegacyApiSupport.createViews(db); 2918 } 2919 2920 if (upgradeLocaleSpecificData) { 2921 upgradeLocaleData(db, false /* we build stats table later */); 2922 // Name lookups are rebuilt as part of the full locale rebuild 2923 upgradeNameLookup = false; 2924 upgradeSearchIndex = true; 2925 rebuildSqliteStats = true; 2926 } 2927 2928 if (upgradeNameLookup) { 2929 rebuildNameLookup(db, false /* we build stats table later */); 2930 rebuildSqliteStats = true; 2931 } 2932 2933 if (upgradeSearchIndex) { 2934 rebuildSearchIndex(db, false /* we build stats table later */); 2935 rebuildSqliteStats = true; 2936 } 2937 2938 if (rescanDirectories) { 2939 // Force the next ContactDirectoryManager.scanAllPackages() to rescan all packages. 2940 // (It's called from the BACKGROUND_TASK_UPDATE_ACCOUNTS background task.) 2941 setProperty(db, DbProperties.DIRECTORY_SCAN_COMPLETE, "0"); 2942 } 2943 2944 if (rebuildSqliteStats) { 2945 updateSqliteStats(db); 2946 } 2947 2948 if (oldVersion != newVersion) { 2949 throw new IllegalStateException( 2950 "error upgrading the database to version " + newVersion); 2951 } 2952 } 2953 2954 private void upgradeToVersion202(SQLiteDatabase db) { 2955 db.execSQL( 2956 "ALTER TABLE " + Tables.PHONE_LOOKUP + 2957 " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;"); 2958 2959 db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" + 2960 PhoneLookupColumns.MIN_MATCH + "," + 2961 PhoneLookupColumns.RAW_CONTACT_ID + "," + 2962 PhoneLookupColumns.DATA_ID + 2963 ");"); 2964 2965 updateIndexStats(db, Tables.PHONE_LOOKUP, 2966 "phone_lookup_min_match_index", "10000 2 2 1"); 2967 2968 SQLiteStatement update = db.compileStatement( 2969 "UPDATE " + Tables.PHONE_LOOKUP + 2970 " SET " + PhoneLookupColumns.MIN_MATCH + "=?" + 2971 " WHERE " + PhoneLookupColumns.DATA_ID + "=?"); 2972 2973 // Populate the new column 2974 Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA + 2975 " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")", 2976 new String[] {Data._ID, Phone.NUMBER}, null, null, null, null, null); 2977 try { 2978 while (c.moveToNext()) { 2979 long dataId = c.getLong(0); 2980 String number = c.getString(1); 2981 if (!TextUtils.isEmpty(number)) { 2982 update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number)); 2983 update.bindLong(2, dataId); 2984 update.execute(); 2985 } 2986 } 2987 } finally { 2988 c.close(); 2989 } 2990 } 2991 2992 private void upgradeToVersion203(SQLiteDatabase db) { 2993 // Garbage-collect first. A bug in Eclair was sometimes leaving 2994 // raw_contacts in the database that no longer had contacts associated 2995 // with them. To avoid failures during this database upgrade, drop 2996 // the orphaned raw_contacts. 2997 db.execSQL( 2998 "DELETE FROM raw_contacts" + 2999 " WHERE contact_id NOT NULL" + 3000 " AND contact_id NOT IN (SELECT _id FROM contacts)"); 3001 3002 db.execSQL( 3003 "ALTER TABLE " + Tables.CONTACTS + 3004 " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)"); 3005 db.execSQL( 3006 "ALTER TABLE " + Tables.RAW_CONTACTS + 3007 " ADD contact_in_visible_group INTEGER NOT NULL DEFAULT 0"); 3008 3009 // For each Contact, find the RawContact that contributed the display name 3010 db.execSQL( 3011 "UPDATE " + Tables.CONTACTS + 3012 " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" + 3013 " SELECT " + RawContacts._ID + 3014 " FROM " + Tables.RAW_CONTACTS + 3015 " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + 3016 " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" + 3017 Tables.CONTACTS + "." + Contacts.DISPLAY_NAME + 3018 " ORDER BY " + RawContacts._ID + 3019 " LIMIT 1)" 3020 ); 3021 3022 db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" + 3023 Contacts.NAME_RAW_CONTACT_ID + 3024 ");"); 3025 3026 // If for some unknown reason we missed some names, let's make sure there are 3027 // no contacts without a name, picking a raw contact "at random". 3028 db.execSQL( 3029 "UPDATE " + Tables.CONTACTS + 3030 " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" + 3031 " SELECT " + RawContacts._ID + 3032 " FROM " + Tables.RAW_CONTACTS + 3033 " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + 3034 " ORDER BY " + RawContacts._ID + 3035 " LIMIT 1)" + 3036 " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL" 3037 ); 3038 3039 // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use. 3040 db.execSQL( 3041 "UPDATE " + Tables.CONTACTS + 3042 " SET " + Contacts.DISPLAY_NAME + "=NULL" 3043 ); 3044 3045 // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow 3046 // indexing on (display_name, in_visible_group) 3047 db.execSQL( 3048 "UPDATE " + Tables.RAW_CONTACTS + 3049 " SET contact_in_visible_group=(" + 3050 "SELECT " + Contacts.IN_VISIBLE_GROUP + 3051 " FROM " + Tables.CONTACTS + 3052 " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" + 3053 " WHERE " + RawContacts.CONTACT_ID + " NOT NULL" 3054 ); 3055 3056 db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" + 3057 "contact_in_visible_group" + "," + 3058 RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" + 3059 ");"); 3060 3061 db.execSQL("DROP INDEX contacts_visible_index"); 3062 db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" + 3063 Contacts.IN_VISIBLE_GROUP + 3064 ");"); 3065 } 3066 3067 private void upgradeToVersion205(SQLiteDatabase db) { 3068 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 3069 + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;"); 3070 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 3071 + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;"); 3072 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 3073 + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;"); 3074 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 3075 + " ADD " + RawContacts.SORT_KEY_PRIMARY 3076 + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";"); 3077 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 3078 + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE 3079 + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";"); 3080 3081 NameSplitter splitter = createNameSplitter(); 3082 3083 SQLiteStatement rawContactUpdate = db.compileStatement( 3084 "UPDATE " + Tables.RAW_CONTACTS + 3085 " SET " + 3086 RawContacts.DISPLAY_NAME_PRIMARY + "=?," + 3087 RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," + 3088 RawContacts.PHONETIC_NAME + "=?," + 3089 RawContacts.PHONETIC_NAME_STYLE + "=?," + 3090 RawContacts.SORT_KEY_PRIMARY + "=?," + 3091 RawContacts.SORT_KEY_ALTERNATIVE + "=?" + 3092 " WHERE " + RawContacts._ID + "=?"); 3093 3094 upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter); 3095 upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter); 3096 3097 db.execSQL("DROP INDEX raw_contact_sort_key1_index"); 3098 db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" + 3099 "contact_in_visible_group" + "," + 3100 RawContacts.SORT_KEY_PRIMARY + 3101 ");"); 3102 3103 db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" + 3104 "contact_in_visible_group" + "," + 3105 RawContacts.SORT_KEY_ALTERNATIVE + 3106 ");"); 3107 } 3108 3109 private void upgradeStructuredNamesToVersion205( 3110 SQLiteDatabase db, SQLiteStatement rawContactUpdate, NameSplitter splitter) { 3111 3112 // Process structured names to detect the style of the full name and phonetic name. 3113 long mMimeType; 3114 try { 3115 mMimeType = DatabaseUtils.longForQuery(db, 3116 "SELECT " + MimetypesColumns._ID + 3117 " FROM " + Tables.MIMETYPES + 3118 " WHERE " + MimetypesColumns.MIMETYPE 3119 + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null); 3120 3121 } catch (SQLiteDoneException e) { 3122 // No structured names in the database. 3123 return; 3124 } 3125 3126 SQLiteStatement structuredNameUpdate = db.compileStatement( 3127 "UPDATE " + Tables.DATA + 3128 " SET " + 3129 StructuredName.FULL_NAME_STYLE + "=?," + 3130 StructuredName.DISPLAY_NAME + "=?," + 3131 StructuredName.PHONETIC_NAME_STYLE + "=?" + 3132 " WHERE " + Data._ID + "=?"); 3133 3134 NameSplitter.Name name = new NameSplitter.Name(); 3135 Cursor cursor = db.query(StructName205Query.TABLE, 3136 StructName205Query.COLUMNS, 3137 DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null); 3138 try { 3139 while (cursor.moveToNext()) { 3140 long dataId = cursor.getLong(StructName205Query.ID); 3141 long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID); 3142 int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE); 3143 3144 name.clear(); 3145 name.prefix = cursor.getString(StructName205Query.PREFIX); 3146 name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME); 3147 name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME); 3148 name.familyName = cursor.getString(StructName205Query.FAMILY_NAME); 3149 name.suffix = cursor.getString(StructName205Query.SUFFIX); 3150 name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME); 3151 name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME); 3152 name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME); 3153 3154 upgradeNameToVersion205(dataId, rawContactId, displayNameSource, name, 3155 structuredNameUpdate, rawContactUpdate, splitter); 3156 } 3157 } finally { 3158 cursor.close(); 3159 } 3160 } 3161 3162 private void upgradeNameToVersion205( 3163 long dataId, 3164 long rawContactId, 3165 int displayNameSource, 3166 NameSplitter.Name name, 3167 SQLiteStatement structuredNameUpdate, 3168 SQLiteStatement rawContactUpdate, 3169 NameSplitter splitter) { 3170 3171 splitter.guessNameStyle(name); 3172 int unadjustedFullNameStyle = name.fullNameStyle; 3173 name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle); 3174 String displayName = splitter.join(name, true, true); 3175 3176 // Don't update database with the adjusted fullNameStyle as it is locale 3177 // related 3178 structuredNameUpdate.bindLong(1, unadjustedFullNameStyle); 3179 DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName); 3180 structuredNameUpdate.bindLong(3, name.phoneticNameStyle); 3181 structuredNameUpdate.bindLong(4, dataId); 3182 structuredNameUpdate.execute(); 3183 3184 if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) { 3185 String displayNameAlternative = splitter.join(name, false, false); 3186 String phoneticName = splitter.joinPhoneticName(name); 3187 String sortKey = null; 3188 String sortKeyAlternative = null; 3189 3190 if (phoneticName != null) { 3191 sortKey = sortKeyAlternative = phoneticName; 3192 } else if (name.fullNameStyle == FullNameStyle.CHINESE || 3193 name.fullNameStyle == FullNameStyle.CJK) { 3194 sortKey = sortKeyAlternative = displayName; 3195 } 3196 3197 if (sortKey == null) { 3198 sortKey = displayName; 3199 sortKeyAlternative = displayNameAlternative; 3200 } 3201 3202 updateRawContact205(rawContactUpdate, rawContactId, displayName, 3203 displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey, 3204 sortKeyAlternative); 3205 } 3206 } 3207 3208 private void upgradeOrganizationsToVersion205( 3209 SQLiteDatabase db, SQLiteStatement rawContactUpdate, NameSplitter splitter) { 3210 3211 final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE); 3212 SQLiteStatement organizationUpdate = db.compileStatement( 3213 "UPDATE " + Tables.DATA + 3214 " SET " + 3215 Organization.PHONETIC_NAME_STYLE + "=?" + 3216 " WHERE " + Data._ID + "=?"); 3217 3218 Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS, 3219 DataColumns.MIMETYPE_ID + "=" + mimeType + " AND " 3220 + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION, 3221 null, null, null, null); 3222 try { 3223 while (cursor.moveToNext()) { 3224 long dataId = cursor.getLong(Organization205Query.ID); 3225 long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID); 3226 String company = cursor.getString(Organization205Query.COMPANY); 3227 String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME); 3228 3229 int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName); 3230 3231 organizationUpdate.bindLong(1, phoneticNameStyle); 3232 organizationUpdate.bindLong(2, dataId); 3233 organizationUpdate.execute(); 3234 3235 String sortKey = company; 3236 3237 updateRawContact205(rawContactUpdate, rawContactId, company, 3238 company, phoneticNameStyle, phoneticName, sortKey, sortKey); 3239 } 3240 } finally { 3241 cursor.close(); 3242 } 3243 } 3244 3245 private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId, 3246 String displayName, String displayNameAlternative, int phoneticNameStyle, 3247 String phoneticName, String sortKeyPrimary, String sortKeyAlternative) { 3248 bindString(rawContactUpdate, 1, displayName); 3249 bindString(rawContactUpdate, 2, displayNameAlternative); 3250 bindString(rawContactUpdate, 3, phoneticName); 3251 rawContactUpdate.bindLong(4, phoneticNameStyle); 3252 bindString(rawContactUpdate, 5, sortKeyPrimary); 3253 bindString(rawContactUpdate, 6, sortKeyAlternative); 3254 rawContactUpdate.bindLong(7, rawContactId); 3255 rawContactUpdate.execute(); 3256 } 3257 3258 private void upgrateToVersion206(SQLiteDatabase db) { 3259 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 3260 + " ADD name_verified INTEGER NOT NULL DEFAULT 0;"); 3261 } 3262 3263 /** 3264 * The {@link ContactsProvider2#update} method was deleting name lookup for new 3265 * emails during the sync. We need to restore the lost name lookup rows. 3266 */ 3267 private void upgradeEmailToVersion303(SQLiteDatabase db) { 3268 final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE); 3269 if (mimeTypeId == -1) { 3270 return; 3271 } 3272 3273 ContentValues values = new ContentValues(); 3274 3275 // Find all data rows with the mime type "email" that are missing name lookup 3276 Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS, 3277 Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 3278 null, null, null); 3279 try { 3280 while (cursor.moveToNext()) { 3281 long dataId = cursor.getLong(Upgrade303Query.ID); 3282 long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID); 3283 String value = cursor.getString(Upgrade303Query.DATA1); 3284 value = extractHandleFromEmailAddress(value); 3285 3286 if (value != null) { 3287 values.put(NameLookupColumns.DATA_ID, dataId); 3288 values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId); 3289 values.put(NameLookupColumns.NAME_TYPE, NameLookupType.EMAIL_BASED_NICKNAME); 3290 values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value)); 3291 db.insert(Tables.NAME_LOOKUP, null, values); 3292 } 3293 } 3294 } finally { 3295 cursor.close(); 3296 } 3297 } 3298 3299 /** 3300 * The {@link ContactsProvider2#update} method was deleting name lookup for new 3301 * nicknames during the sync. We need to restore the lost name lookup rows. 3302 */ 3303 private void upgradeNicknameToVersion303(SQLiteDatabase db) { 3304 final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE); 3305 if (mimeTypeId == -1) { 3306 return; 3307 } 3308 3309 ContentValues values = new ContentValues(); 3310 3311 // Find all data rows with the mime type "nickname" that are missing name lookup 3312 Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS, 3313 Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 3314 null, null, null); 3315 try { 3316 while (cursor.moveToNext()) { 3317 long dataId = cursor.getLong(Upgrade303Query.ID); 3318 long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID); 3319 String value = cursor.getString(Upgrade303Query.DATA1); 3320 3321 values.put(NameLookupColumns.DATA_ID, dataId); 3322 values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId); 3323 values.put(NameLookupColumns.NAME_TYPE, NameLookupType.NICKNAME); 3324 values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value)); 3325 db.insert(Tables.NAME_LOOKUP, null, values); 3326 } 3327 } finally { 3328 cursor.close(); 3329 } 3330 } 3331 3332 private void upgradeToVersion304(SQLiteDatabase db) { 3333 // Mimetype table requires an index on mime type. 3334 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" + 3335 MimetypesColumns.MIMETYPE + 3336 ");"); 3337 } 3338 3339 private void upgradeToVersion306(SQLiteDatabase db) { 3340 // Fix invalid lookup that was used for Exchange contacts (it was not escaped) 3341 // It happened when a new contact was created AND synchronized 3342 final StringBuilder lookupKeyBuilder = new StringBuilder(); 3343 final SQLiteStatement updateStatement = db.compileStatement( 3344 "UPDATE contacts " + 3345 "SET lookup=? " + 3346 "WHERE _id=?"); 3347 final Cursor contactIdCursor = db.rawQuery( 3348 "SELECT DISTINCT contact_id " + 3349 "FROM raw_contacts " + 3350 "WHERE deleted=0 AND account_type='com.android.exchange'", 3351 null); 3352 try { 3353 while (contactIdCursor.moveToNext()) { 3354 final long contactId = contactIdCursor.getLong(0); 3355 lookupKeyBuilder.setLength(0); 3356 final Cursor c = db.rawQuery( 3357 "SELECT account_type, account_name, _id, sourceid, display_name " + 3358 "FROM raw_contacts " + 3359 "WHERE contact_id=? " + 3360 "ORDER BY _id", 3361 new String[] {String.valueOf(contactId)}); 3362 try { 3363 while (c.moveToNext()) { 3364 ContactLookupKey.appendToLookupKey(lookupKeyBuilder, 3365 c.getString(0), 3366 c.getString(1), 3367 c.getLong(2), 3368 c.getString(3), 3369 c.getString(4)); 3370 } 3371 } finally { 3372 c.close(); 3373 } 3374 3375 if (lookupKeyBuilder.length() == 0) { 3376 updateStatement.bindNull(1); 3377 } else { 3378 updateStatement.bindString(1, Uri.encode(lookupKeyBuilder.toString())); 3379 } 3380 updateStatement.bindLong(2, contactId); 3381 3382 updateStatement.execute(); 3383 } 3384 } finally { 3385 updateStatement.close(); 3386 contactIdCursor.close(); 3387 } 3388 } 3389 3390 private void upgradeToVersion307(SQLiteDatabase db) { 3391 db.execSQL("CREATE TABLE properties (" + 3392 "property_key TEXT PRIMARY_KEY, " + 3393 "property_value TEXT" + 3394 ");"); 3395 } 3396 3397 private void upgradeToVersion308(SQLiteDatabase db) { 3398 db.execSQL("CREATE TABLE accounts (" + 3399 "account_name TEXT, " + 3400 "account_type TEXT " + 3401 ");"); 3402 3403 db.execSQL("INSERT INTO accounts " + 3404 "SELECT DISTINCT account_name, account_type FROM raw_contacts"); 3405 } 3406 3407 private void upgradeToVersion400(SQLiteDatabase db) { 3408 db.execSQL("ALTER TABLE " + Tables.GROUPS 3409 + " ADD " + Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0;"); 3410 db.execSQL("ALTER TABLE " + Tables.GROUPS 3411 + " ADD " + Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0;"); 3412 } 3413 3414 private void upgradeToVersion353(SQLiteDatabase db) { 3415 db.execSQL("DELETE FROM contacts " + 3416 "WHERE NOT EXISTS (SELECT 1 FROM raw_contacts WHERE contact_id=contacts._id)"); 3417 } 3418 3419 private void rebuildNameLookup(SQLiteDatabase db, boolean rebuildSqliteStats) { 3420 db.execSQL("DROP INDEX IF EXISTS name_lookup_index"); 3421 insertNameLookup(db); 3422 createContactsIndexes(db, rebuildSqliteStats); 3423 } 3424 3425 protected void rebuildSearchIndex() { 3426 rebuildSearchIndex(getWritableDatabase(), true); 3427 } 3428 3429 private void rebuildSearchIndex(SQLiteDatabase db, boolean rebuildSqliteStats) { 3430 createSearchIndexTable(db, rebuildSqliteStats); 3431 setProperty(db, SearchIndexManager.PROPERTY_SEARCH_INDEX_VERSION, "0"); 3432 } 3433 3434 /** 3435 * Checks whether the current ICU code version matches that used to build 3436 * the locale specific data in the ContactsDB. 3437 */ 3438 public boolean needsToUpdateLocaleData(LocaleSet locales) { 3439 final String dbLocale = getProperty(DbProperties.LOCALE, ""); 3440 if (!dbLocale.equals(locales.toString())) { 3441 return true; 3442 } 3443 final String curICUVersion = ICU.getIcuVersion(); 3444 final String dbICUVersion = getProperty(DbProperties.ICU_VERSION, 3445 "(unknown)"); 3446 if (!curICUVersion.equals(dbICUVersion)) { 3447 Log.i(TAG, "ICU version has changed. Current version is " 3448 + curICUVersion + "; DB was built with " + dbICUVersion); 3449 return true; 3450 } 3451 return false; 3452 } 3453 3454 private void upgradeLocaleData(SQLiteDatabase db, boolean rebuildSqliteStats) { 3455 final LocaleSet locales = LocaleSet.getDefault(); 3456 Log.i(TAG, "Upgrading locale data for " + locales 3457 + " (ICU v" + ICU.getIcuVersion() + ")"); 3458 final long start = SystemClock.elapsedRealtime(); 3459 initializeCache(db); 3460 rebuildLocaleData(db, locales, rebuildSqliteStats); 3461 Log.i(TAG, "Locale update completed in " + (SystemClock.elapsedRealtime() - start) + "ms"); 3462 } 3463 3464 private void rebuildLocaleData(SQLiteDatabase db, LocaleSet locales, boolean rebuildSqliteStats) { 3465 db.execSQL("DROP INDEX raw_contact_sort_key1_index"); 3466 db.execSQL("DROP INDEX raw_contact_sort_key2_index"); 3467 db.execSQL("DROP INDEX IF EXISTS name_lookup_index"); 3468 3469 loadNicknameLookupTable(db); 3470 insertNameLookup(db); 3471 rebuildSortKeys(db); 3472 createContactsIndexes(db, rebuildSqliteStats); 3473 3474 FastScrollingIndexCache.getInstance(mContext).invalidate(); 3475 // Update the ICU version used to generate the locale derived data 3476 // so we can tell when we need to rebuild with new ICU versions. 3477 setProperty(db, DbProperties.ICU_VERSION, ICU.getIcuVersion()); 3478 setProperty(db, DbProperties.LOCALE, locales.toString()); 3479 } 3480 3481 /** 3482 * Regenerates all locale-sensitive data if needed: 3483 * nickname_lookup, name_lookup and sort keys. Invalidates the fast 3484 * scrolling index cache. 3485 */ 3486 public void setLocale(LocaleSet locales) { 3487 if (!needsToUpdateLocaleData(locales)) { 3488 return; 3489 } 3490 Log.i(TAG, "Switching to locale " + locales 3491 + " (ICU v" + ICU.getIcuVersion() + ")"); 3492 3493 final long start = SystemClock.elapsedRealtime(); 3494 SQLiteDatabase db = getWritableDatabase(); 3495 db.setLocale(locales.getPrimaryLocale()); 3496 db.beginTransaction(); 3497 try { 3498 rebuildLocaleData(db, locales, true); 3499 db.setTransactionSuccessful(); 3500 } finally { 3501 db.endTransaction(); 3502 } 3503 3504 Log.i(TAG, "Locale change completed in " + (SystemClock.elapsedRealtime() - start) + "ms"); 3505 } 3506 3507 /** 3508 * Regenerates sort keys for all contacts. 3509 */ 3510 private void rebuildSortKeys(SQLiteDatabase db) { 3511 Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[] {RawContacts._ID}, 3512 null, null, null, null, null); 3513 try { 3514 while (cursor.moveToNext()) { 3515 long rawContactId = cursor.getLong(0); 3516 updateRawContactDisplayName(db, rawContactId); 3517 } 3518 } finally { 3519 cursor.close(); 3520 } 3521 } 3522 3523 private void insertNameLookup(SQLiteDatabase db) { 3524 db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP); 3525 3526 SQLiteStatement nameLookupInsert = db.compileStatement( 3527 "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "(" 3528 + NameLookupColumns.RAW_CONTACT_ID + "," 3529 + NameLookupColumns.DATA_ID + "," 3530 + NameLookupColumns.NAME_TYPE + "," 3531 + NameLookupColumns.NORMALIZED_NAME + 3532 ") VALUES (?,?,?,?)"); 3533 3534 try { 3535 insertStructuredNameLookup(db, nameLookupInsert); 3536 insertEmailLookup(db, nameLookupInsert); 3537 insertNicknameLookup(db, nameLookupInsert); 3538 } finally { 3539 nameLookupInsert.close(); 3540 } 3541 } 3542 3543 /** 3544 * Inserts name lookup rows for all structured names in the database. 3545 */ 3546 private void insertStructuredNameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) { 3547 NameSplitter nameSplitter = createNameSplitter(); 3548 NameLookupBuilder nameLookupBuilder = new StructuredNameLookupBuilder(nameSplitter, 3549 new CommonNicknameCache(db), nameLookupInsert); 3550 final long mimeTypeId = lookupMimeTypeId(db, StructuredName.CONTENT_ITEM_TYPE); 3551 Cursor cursor = db.query(StructuredNameQuery.TABLE, StructuredNameQuery.COLUMNS, 3552 StructuredNameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 3553 null, null, null); 3554 try { 3555 while (cursor.moveToNext()) { 3556 long dataId = cursor.getLong(StructuredNameQuery.ID); 3557 long rawContactId = cursor.getLong(StructuredNameQuery.RAW_CONTACT_ID); 3558 String name = cursor.getString(StructuredNameQuery.DISPLAY_NAME); 3559 int fullNameStyle = nameSplitter.guessFullNameStyle(name); 3560 fullNameStyle = nameSplitter.getAdjustedFullNameStyle(fullNameStyle); 3561 nameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle); 3562 } 3563 } finally { 3564 cursor.close(); 3565 } 3566 } 3567 3568 /** 3569 * Inserts name lookup rows for all email addresses in the database. 3570 */ 3571 private void insertEmailLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) { 3572 final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE); 3573 Cursor cursor = db.query(EmailQuery.TABLE, EmailQuery.COLUMNS, 3574 EmailQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 3575 null, null, null); 3576 try { 3577 while (cursor.moveToNext()) { 3578 long dataId = cursor.getLong(EmailQuery.ID); 3579 long rawContactId = cursor.getLong(EmailQuery.RAW_CONTACT_ID); 3580 String address = cursor.getString(EmailQuery.ADDRESS); 3581 address = extractHandleFromEmailAddress(address); 3582 insertNameLookup(nameLookupInsert, rawContactId, dataId, 3583 NameLookupType.EMAIL_BASED_NICKNAME, address); 3584 } 3585 } finally { 3586 cursor.close(); 3587 } 3588 } 3589 3590 /** 3591 * Inserts name lookup rows for all nicknames in the database. 3592 */ 3593 private void insertNicknameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) { 3594 final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE); 3595 Cursor cursor = db.query(NicknameQuery.TABLE, NicknameQuery.COLUMNS, 3596 NicknameQuery.SELECTION, new String[]{String.valueOf(mimeTypeId)}, 3597 null, null, null); 3598 try { 3599 while (cursor.moveToNext()) { 3600 long dataId = cursor.getLong(NicknameQuery.ID); 3601 long rawContactId = cursor.getLong(NicknameQuery.RAW_CONTACT_ID); 3602 String nickname = cursor.getString(NicknameQuery.NAME); 3603 insertNameLookup(nameLookupInsert, rawContactId, dataId, 3604 NameLookupType.NICKNAME, nickname); 3605 } 3606 } finally { 3607 cursor.close(); 3608 } 3609 } 3610 3611 /** 3612 * Inserts a record in the {@link Tables#NAME_LOOKUP} table. 3613 */ 3614 public void insertNameLookup(SQLiteStatement stmt, long rawContactId, long dataId, 3615 int lookupType, String name) { 3616 if (TextUtils.isEmpty(name)) { 3617 return; 3618 } 3619 3620 String normalized = NameNormalizer.normalize(name); 3621 if (TextUtils.isEmpty(normalized)) { 3622 return; 3623 } 3624 3625 insertNormalizedNameLookup(stmt, rawContactId, dataId, lookupType, normalized); 3626 } 3627 3628 private void insertNormalizedNameLookup(SQLiteStatement stmt, long rawContactId, long dataId, 3629 int lookupType, String normalizedName) { 3630 stmt.bindLong(1, rawContactId); 3631 stmt.bindLong(2, dataId); 3632 stmt.bindLong(3, lookupType); 3633 stmt.bindString(4, normalizedName); 3634 stmt.executeInsert(); 3635 } 3636 3637 /** 3638 * Changing the VISIBLE bit from a field on both RawContacts and Contacts to a separate table. 3639 */ 3640 private void upgradeToVersion401(SQLiteDatabase db) { 3641 db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" + 3642 Contacts._ID + " INTEGER PRIMARY KEY" + 3643 ");"); 3644 db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS + 3645 " SELECT " + Contacts._ID + 3646 " FROM " + Tables.CONTACTS + 3647 " WHERE " + Contacts.IN_VISIBLE_GROUP + "!=0"); 3648 db.execSQL("DROP INDEX contacts_visible_index"); 3649 } 3650 3651 /** 3652 * Introducing a new table: directories. 3653 */ 3654 private void upgradeToVersion402(SQLiteDatabase db) { 3655 createDirectoriesTable(db); 3656 } 3657 3658 private void upgradeToVersion403(SQLiteDatabase db) { 3659 db.execSQL("DROP TABLE IF EXISTS directories;"); 3660 createDirectoriesTable(db); 3661 3662 db.execSQL("ALTER TABLE raw_contacts" 3663 + " ADD raw_contact_is_read_only INTEGER NOT NULL DEFAULT 0;"); 3664 3665 db.execSQL("ALTER TABLE data" 3666 + " ADD is_read_only INTEGER NOT NULL DEFAULT 0;"); 3667 } 3668 3669 private void upgradeToVersion405(SQLiteDatabase db) { 3670 db.execSQL("DROP TABLE IF EXISTS phone_lookup;"); 3671 // Private phone numbers table used for lookup 3672 db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" + 3673 PhoneLookupColumns.DATA_ID 3674 + " INTEGER REFERENCES data(_id) NOT NULL," + 3675 PhoneLookupColumns.RAW_CONTACT_ID 3676 + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 3677 PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," + 3678 PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" + 3679 ");"); 3680 3681 db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" + 3682 PhoneLookupColumns.NORMALIZED_NUMBER + "," + 3683 PhoneLookupColumns.RAW_CONTACT_ID + "," + 3684 PhoneLookupColumns.DATA_ID + 3685 ");"); 3686 3687 db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" + 3688 PhoneLookupColumns.MIN_MATCH + "," + 3689 PhoneLookupColumns.RAW_CONTACT_ID + "," + 3690 PhoneLookupColumns.DATA_ID + 3691 ");"); 3692 3693 final long mimeTypeId = lookupMimeTypeId(db, Phone.CONTENT_ITEM_TYPE); 3694 if (mimeTypeId == -1) { 3695 return; 3696 } 3697 3698 Cursor cursor = db.rawQuery( 3699 "SELECT _id, " + Phone.RAW_CONTACT_ID + ", " + Phone.NUMBER + 3700 " FROM " + Tables.DATA + 3701 " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimeTypeId 3702 + " AND " + Phone.NUMBER + " NOT NULL", null); 3703 3704 ContentValues phoneValues = new ContentValues(); 3705 try { 3706 while (cursor.moveToNext()) { 3707 long dataID = cursor.getLong(0); 3708 long rawContactID = cursor.getLong(1); 3709 String number = cursor.getString(2); 3710 String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); 3711 if (!TextUtils.isEmpty(normalizedNumber)) { 3712 phoneValues.clear(); 3713 phoneValues.put(PhoneLookupColumns.RAW_CONTACT_ID, rawContactID); 3714 phoneValues.put(PhoneLookupColumns.DATA_ID, dataID); 3715 phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, normalizedNumber); 3716 phoneValues.put(PhoneLookupColumns.MIN_MATCH, 3717 PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber)); 3718 db.insert(Tables.PHONE_LOOKUP, null, phoneValues); 3719 } 3720 } 3721 } finally { 3722 cursor.close(); 3723 } 3724 } 3725 3726 private void upgradeToVersion406(SQLiteDatabase db) { 3727 db.execSQL("ALTER TABLE calls ADD countryiso TEXT;"); 3728 } 3729 3730 private void upgradeToVersion409(SQLiteDatabase db) { 3731 db.execSQL("DROP TABLE IF EXISTS directories;"); 3732 createDirectoriesTable(db); 3733 } 3734 3735 /** 3736 * Adding DEFAULT_DIRECTORY table. 3737 * DEFAULT_DIRECTORY should contain every contact which should be shown to users in default. 3738 * - if a contact doesn't belong to any account (local contact), it should be in 3739 * default_directory 3740 * - if a contact belongs to an account that doesn't have a "default" group, it should be in 3741 * default_directory 3742 * - if a contact belongs to an account that has a "default" group (like Google directory, 3743 * which has "My contacts" group as default), it should be in default_directory. 3744 * 3745 * This logic assumes that accounts with the "default" group should have at least one 3746 * group with AUTO_ADD (implying it is the default group) flag in the groups table. 3747 */ 3748 private void upgradeToVersion411(SQLiteDatabase db) { 3749 db.execSQL("DROP TABLE IF EXISTS " + Tables.DEFAULT_DIRECTORY); 3750 db.execSQL("CREATE TABLE default_directory (_id INTEGER PRIMARY KEY);"); 3751 3752 // Process contacts without an account 3753 db.execSQL("INSERT OR IGNORE INTO default_directory " + 3754 " SELECT contact_id " + 3755 " FROM raw_contacts " + 3756 " WHERE raw_contacts.account_name IS NULL " + 3757 " AND raw_contacts.account_type IS NULL "); 3758 3759 // Process accounts that don't have a default group (e.g. Exchange). 3760 db.execSQL("INSERT OR IGNORE INTO default_directory " + 3761 " SELECT contact_id " + 3762 " FROM raw_contacts " + 3763 " WHERE NOT EXISTS" + 3764 " (SELECT _id " + 3765 " FROM groups " + 3766 " WHERE raw_contacts.account_name = groups.account_name" + 3767 " AND raw_contacts.account_type = groups.account_type" + 3768 " AND groups.auto_add != 0)"); 3769 3770 final long mimetype = lookupMimeTypeId(db, GroupMembership.CONTENT_ITEM_TYPE); 3771 3772 // Process accounts that do have a default group (e.g. Google) 3773 db.execSQL("INSERT OR IGNORE INTO default_directory " + 3774 " SELECT contact_id " + 3775 " FROM raw_contacts " + 3776 " JOIN data " + 3777 " ON (raw_contacts._id=raw_contact_id)" + 3778 " WHERE mimetype_id=" + mimetype + 3779 " AND EXISTS" + 3780 " (SELECT _id" + 3781 " FROM groups" + 3782 " WHERE raw_contacts.account_name = groups.account_name" + 3783 " AND raw_contacts.account_type = groups.account_type" + 3784 " AND groups.auto_add != 0)"); 3785 } 3786 3787 private void upgradeToVersion413(SQLiteDatabase db) { 3788 db.execSQL("DROP TABLE IF EXISTS directories;"); 3789 createDirectoriesTable(db); 3790 } 3791 3792 private void upgradeToVersion415(SQLiteDatabase db) { 3793 db.execSQL( 3794 "ALTER TABLE " + Tables.GROUPS + 3795 " ADD " + Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0"); 3796 db.execSQL( 3797 "UPDATE " + Tables.GROUPS + 3798 " SET " + Groups.GROUP_IS_READ_ONLY + "=1" + 3799 " WHERE " + Groups.SYSTEM_ID + " NOT NULL"); 3800 } 3801 3802 private void upgradeToVersion416(SQLiteDatabase db) { 3803 db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP + 3804 " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");"); 3805 } 3806 3807 private void upgradeToVersion501(SQLiteDatabase db) { 3808 // Remove organization rows from the name lookup, we now use search index for that 3809 db.execSQL("DELETE FROM name_lookup WHERE name_type=5"); 3810 } 3811 3812 private void upgradeToVersion502(SQLiteDatabase db) { 3813 // Remove Chinese and Korean name lookup - this data is now in the search index 3814 db.execSQL("DELETE FROM name_lookup WHERE name_type IN (6, 7)"); 3815 } 3816 3817 private void upgradeToVersion504(SQLiteDatabase db) { 3818 initializeCache(db); 3819 3820 // Find all names with prefixes and recreate display name 3821 Cursor cursor = db.rawQuery( 3822 "SELECT " + StructuredName.RAW_CONTACT_ID + 3823 " FROM " + Tables.DATA + 3824 " WHERE " + DataColumns.MIMETYPE_ID + "=?" 3825 + " AND " + StructuredName.PREFIX + " NOT NULL", 3826 new String[] {String.valueOf(mMimeTypeIdStructuredName)}); 3827 3828 try { 3829 while(cursor.moveToNext()) { 3830 long rawContactId = cursor.getLong(0); 3831 updateRawContactDisplayName(db, rawContactId); 3832 } 3833 3834 } finally { 3835 cursor.close(); 3836 } 3837 } 3838 3839 private void upgradeToVersion601(SQLiteDatabase db) { 3840 db.execSQL("CREATE TABLE data_usage_stat(" + 3841 "stat_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3842 "data_id INTEGER NOT NULL, " + 3843 "usage_type INTEGER NOT NULL DEFAULT 0, " + 3844 "times_used INTEGER NOT NULL DEFAULT 0, " + 3845 "last_time_used INTERGER NOT NULL DEFAULT 0, " + 3846 "FOREIGN KEY(data_id) REFERENCES data(_id));"); 3847 db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " + 3848 "data_usage_stat (data_id, usage_type)"); 3849 } 3850 3851 private void upgradeToVersion602(SQLiteDatabase db) { 3852 db.execSQL("ALTER TABLE calls ADD voicemail_uri TEXT;"); 3853 db.execSQL("ALTER TABLE calls ADD _data TEXT;"); 3854 db.execSQL("ALTER TABLE calls ADD has_content INTEGER;"); 3855 db.execSQL("ALTER TABLE calls ADD mime_type TEXT;"); 3856 db.execSQL("ALTER TABLE calls ADD source_data TEXT;"); 3857 db.execSQL("ALTER TABLE calls ADD source_package TEXT;"); 3858 db.execSQL("ALTER TABLE calls ADD state INTEGER;"); 3859 } 3860 3861 private void upgradeToVersion604(SQLiteDatabase db) { 3862 db.execSQL("CREATE TABLE voicemail_status (" + 3863 "_id INTEGER PRIMARY KEY AUTOINCREMENT," + 3864 "source_package TEXT UNIQUE NOT NULL," + 3865 "settings_uri TEXT," + 3866 "voicemail_access_uri TEXT," + 3867 "configuration_state INTEGER," + 3868 "data_channel_state INTEGER," + 3869 "notification_channel_state INTEGER" + 3870 ");"); 3871 } 3872 3873 private void upgradeToVersion606(SQLiteDatabase db) { 3874 db.execSQL("DROP VIEW IF EXISTS view_contacts_restricted;"); 3875 db.execSQL("DROP VIEW IF EXISTS view_data_restricted;"); 3876 db.execSQL("DROP VIEW IF EXISTS view_raw_contacts_restricted;"); 3877 db.execSQL("DROP VIEW IF EXISTS view_raw_entities_restricted;"); 3878 db.execSQL("DROP VIEW IF EXISTS view_entities_restricted;"); 3879 db.execSQL("DROP VIEW IF EXISTS view_data_usage_stat_restricted;"); 3880 db.execSQL("DROP INDEX IF EXISTS contacts_restricted_index"); 3881 3882 // We should remove the restricted columns here as well, but unfortunately SQLite doesn't 3883 // provide ALTER TABLE DROP COLUMN. As they have DEFAULT 0, we can keep but ignore them 3884 } 3885 3886 private void upgradeToVersion608(SQLiteDatabase db) { 3887 db.execSQL("ALTER TABLE contacts ADD photo_file_id INTEGER REFERENCES photo_files(_id);"); 3888 3889 db.execSQL("CREATE TABLE photo_files(" + 3890 "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3891 "height INTEGER NOT NULL, " + 3892 "width INTEGER NOT NULL, " + 3893 "filesize INTEGER NOT NULL);"); 3894 } 3895 3896 private void upgradeToVersion610(SQLiteDatabase db) { 3897 db.execSQL("ALTER TABLE calls ADD is_read INTEGER;"); 3898 } 3899 3900 private void upgradeToVersion611(SQLiteDatabase db) { 3901 db.execSQL("ALTER TABLE raw_contacts ADD data_set TEXT DEFAULT NULL;"); 3902 db.execSQL("ALTER TABLE groups ADD data_set TEXT DEFAULT NULL;"); 3903 db.execSQL("ALTER TABLE accounts ADD data_set TEXT DEFAULT NULL;"); 3904 3905 db.execSQL("CREATE INDEX raw_contacts_source_id_data_set_index ON raw_contacts " + 3906 "(sourceid, account_type, account_name, data_set);"); 3907 3908 db.execSQL("CREATE INDEX groups_source_id_data_set_index ON groups " + 3909 "(sourceid, account_type, account_name, data_set);"); 3910 } 3911 3912 private void upgradeToVersion612(SQLiteDatabase db) { 3913 db.execSQL("ALTER TABLE calls ADD geocoded_location TEXT DEFAULT NULL;"); 3914 // Old calls will not have a geocoded location; new calls will get it when inserted. 3915 } 3916 3917 private void upgradeToVersion613(SQLiteDatabase db) { 3918 // The stream item and stream item photos APIs were not in-use by anyone in the time 3919 // between their initial creation (in v609) and this update. So we're just dropping 3920 // and re-creating them to get appropriate columns. The delta is as follows: 3921 // - In stream_items, package_id was replaced by res_package. 3922 // - In stream_item_photos, picture was replaced by photo_file_id. 3923 // - Instead of resource IDs for icon and label, we use resource name strings now 3924 // - Added sync columns 3925 // - Removed action and action_uri 3926 // - Text and comments are now nullable 3927 3928 db.execSQL("DROP TABLE IF EXISTS stream_items"); 3929 db.execSQL("DROP TABLE IF EXISTS stream_item_photos"); 3930 3931 db.execSQL("CREATE TABLE stream_items(" + 3932 "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3933 "raw_contact_id INTEGER NOT NULL, " + 3934 "res_package TEXT, " + 3935 "icon TEXT, " + 3936 "label TEXT, " + 3937 "text TEXT, " + 3938 "timestamp INTEGER NOT NULL, " + 3939 "comments TEXT, " + 3940 "stream_item_sync1 TEXT, " + 3941 "stream_item_sync2 TEXT, " + 3942 "stream_item_sync3 TEXT, " + 3943 "stream_item_sync4 TEXT, " + 3944 "FOREIGN KEY(raw_contact_id) REFERENCES raw_contacts(_id));"); 3945 3946 db.execSQL("CREATE TABLE stream_item_photos(" + 3947 "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3948 "stream_item_id INTEGER NOT NULL, " + 3949 "sort_index INTEGER, " + 3950 "photo_file_id INTEGER NOT NULL, " + 3951 "stream_item_photo_sync1 TEXT, " + 3952 "stream_item_photo_sync2 TEXT, " + 3953 "stream_item_photo_sync3 TEXT, " + 3954 "stream_item_photo_sync4 TEXT, " + 3955 "FOREIGN KEY(stream_item_id) REFERENCES stream_items(_id));"); 3956 } 3957 3958 private void upgradeToVersion615(SQLiteDatabase db) { 3959 // Old calls will not have up to date values for these columns, they will be filled in 3960 // as needed. 3961 db.execSQL("ALTER TABLE calls ADD lookup_uri TEXT DEFAULT NULL;"); 3962 db.execSQL("ALTER TABLE calls ADD matched_number TEXT DEFAULT NULL;"); 3963 db.execSQL("ALTER TABLE calls ADD normalized_number TEXT DEFAULT NULL;"); 3964 db.execSQL("ALTER TABLE calls ADD photo_id INTEGER NOT NULL DEFAULT 0;"); 3965 } 3966 3967 private void upgradeToVersion618(SQLiteDatabase db) { 3968 // The Settings table needs a data_set column which technically should be part of the 3969 // primary key but can't be because it may be null. Since SQLite doesn't support nuking 3970 // the primary key, we'll drop the old table, re-create it, and copy the settings back in. 3971 db.execSQL("CREATE TEMPORARY TABLE settings_backup(" + 3972 "account_name STRING NOT NULL," + 3973 "account_type STRING NOT NULL," + 3974 "ungrouped_visible INTEGER NOT NULL DEFAULT 0," + 3975 "should_sync INTEGER NOT NULL DEFAULT 1" + 3976 ");"); 3977 db.execSQL("INSERT INTO settings_backup " + 3978 "SELECT account_name, account_type, ungrouped_visible, should_sync" + 3979 " FROM settings"); 3980 db.execSQL("DROP TABLE settings"); 3981 db.execSQL("CREATE TABLE settings (" + 3982 "account_name STRING NOT NULL," + 3983 "account_type STRING NOT NULL," + 3984 "data_set STRING," + 3985 "ungrouped_visible INTEGER NOT NULL DEFAULT 0," + 3986 "should_sync INTEGER NOT NULL DEFAULT 1" + 3987 ");"); 3988 db.execSQL("INSERT INTO settings " + 3989 "SELECT account_name, account_type, NULL, ungrouped_visible, should_sync " + 3990 "FROM settings_backup"); 3991 db.execSQL("DROP TABLE settings_backup"); 3992 } 3993 3994 private void upgradeToVersion622(SQLiteDatabase db) { 3995 db.execSQL("ALTER TABLE calls ADD formatted_number TEXT DEFAULT NULL;"); 3996 } 3997 3998 private void upgradeToVersion626(SQLiteDatabase db) { 3999 db.execSQL("DROP TABLE IF EXISTS accounts"); 4000 4001 db.execSQL("CREATE TABLE accounts (" + 4002 "_id INTEGER PRIMARY KEY AUTOINCREMENT," + 4003 "account_name TEXT, " + 4004 "account_type TEXT, " + 4005 "data_set TEXT" + 4006 ");"); 4007 4008 // Add "account_id" column to groups and raw_contacts 4009 db.execSQL("ALTER TABLE raw_contacts ADD " + 4010 "account_id INTEGER REFERENCES accounts(_id)"); 4011 db.execSQL("ALTER TABLE groups ADD " + 4012 "account_id INTEGER REFERENCES accounts(_id)"); 4013 4014 // Update indexes. 4015 db.execSQL("DROP INDEX IF EXISTS raw_contacts_source_id_index"); 4016 db.execSQL("DROP INDEX IF EXISTS raw_contacts_source_id_data_set_index"); 4017 db.execSQL("DROP INDEX IF EXISTS groups_source_id_index"); 4018 db.execSQL("DROP INDEX IF EXISTS groups_source_id_data_set_index"); 4019 4020 db.execSQL("CREATE INDEX raw_contacts_source_id_account_id_index ON raw_contacts (" 4021 + "sourceid, account_id);"); 4022 db.execSQL("CREATE INDEX groups_source_id_account_id_index ON groups (" 4023 + "sourceid, account_id);"); 4024 4025 // Migrate account_name/account_type/data_set to accounts table 4026 4027 final Set<AccountWithDataSet> accountsWithDataSets = Sets.newHashSet(); 4028 upgradeToVersion626_findAccountsWithDataSets(accountsWithDataSets, db, "raw_contacts"); 4029 upgradeToVersion626_findAccountsWithDataSets(accountsWithDataSets, db, "groups"); 4030 4031 for (AccountWithDataSet accountWithDataSet : accountsWithDataSets) { 4032 db.execSQL("INSERT INTO accounts (account_name,account_type,data_set)VALUES(?, ?, ?)", 4033 new String[] { 4034 accountWithDataSet.getAccountName(), 4035 accountWithDataSet.getAccountType(), 4036 accountWithDataSet.getDataSet() 4037 }); 4038 } 4039 upgradeToVersion626_fillAccountId(db, "raw_contacts"); 4040 upgradeToVersion626_fillAccountId(db, "groups"); 4041 } 4042 4043 private static void upgradeToVersion626_findAccountsWithDataSets( 4044 Set<AccountWithDataSet> result, SQLiteDatabase db, String table) { 4045 Cursor c = db.rawQuery( 4046 "SELECT DISTINCT account_name, account_type, data_set FROM " + table, null); 4047 try { 4048 while (c.moveToNext()) { 4049 result.add(AccountWithDataSet.get(c.getString(0), c.getString(1), c.getString(2))); 4050 } 4051 } finally { 4052 c.close(); 4053 } 4054 } 4055 4056 private static void upgradeToVersion626_fillAccountId(SQLiteDatabase db, String table) { 4057 StringBuilder sb = new StringBuilder(); 4058 4059 // Set account_id and null out account_name, account_type and data_set 4060 4061 sb.append("UPDATE " + table + " SET account_id = (SELECT _id FROM accounts WHERE "); 4062 4063 addJoinExpressionAllowingNull(sb, table + ".account_name", "accounts.account_name"); 4064 sb.append("AND"); 4065 addJoinExpressionAllowingNull(sb, table + ".account_type", "accounts.account_type"); 4066 sb.append("AND"); 4067 addJoinExpressionAllowingNull(sb, table + ".data_set", "accounts.data_set"); 4068 4069 sb.append("), account_name = null, account_type = null, data_set = null"); 4070 db.execSQL(sb.toString()); 4071 } 4072 4073 private void upgradeToVersion701(SQLiteDatabase db) { 4074 db.execSQL("UPDATE raw_contacts SET last_time_contacted =" + 4075 " max(ifnull(last_time_contacted, 0), " + 4076 " ifnull((SELECT max(last_time_used) " + 4077 " FROM data JOIN data_usage_stat ON (data._id = data_usage_stat.data_id)" + 4078 " WHERE data.raw_contact_id = raw_contacts._id), 0))"); 4079 // Replace 0 with null. This isn't really necessary, but we do this anyway for consistency. 4080 db.execSQL("UPDATE raw_contacts SET last_time_contacted = null" + 4081 " where last_time_contacted = 0"); 4082 } 4083 4084 /** 4085 * Pre-HC devices don't have correct "NORMALIZED_NUMBERS". Clear them up. 4086 */ 4087 private void upgradeToVersion702(SQLiteDatabase db) { 4088 // All the "correct" Phone.NORMALIZED_NUMBERS should begin with "+". The upgraded data 4089 // don't. Find all Phone.NORMALIZED_NUMBERS that don't begin with "+". 4090 final int count; 4091 final long[] dataIds; 4092 final long[] rawContactIds; 4093 final String[] phoneNumbers; 4094 final StringBuilder sbDataIds; 4095 final Cursor c = db.rawQuery( 4096 "SELECT _id, raw_contact_id, data1 FROM data " + 4097 " WHERE mimetype_id=" + 4098 "(SELECT _id FROM mimetypes" + 4099 " WHERE mimetype='vnd.android.cursor.item/phone_v2')" + 4100 " AND data4 not like '+%'", // "Not like" will exclude nulls too. 4101 null); 4102 try { 4103 count = c.getCount(); 4104 if (count == 0) { 4105 return; 4106 } 4107 dataIds = new long[count]; 4108 rawContactIds = new long[count]; 4109 phoneNumbers = new String[count]; 4110 sbDataIds = new StringBuilder(); 4111 4112 c.moveToPosition(-1); 4113 while (c.moveToNext()) { 4114 final int i = c.getPosition(); 4115 dataIds[i] = c.getLong(0); 4116 rawContactIds[i] = c.getLong(1); 4117 phoneNumbers[i] = c.getString(2); 4118 4119 if (sbDataIds.length() > 0) { 4120 sbDataIds.append(","); 4121 } 4122 sbDataIds.append(dataIds[i]); 4123 } 4124 } finally { 4125 c.close(); 4126 } 4127 4128 final String dataIdList = sbDataIds.toString(); 4129 4130 // Then, update the Data and PhoneLookup tables. 4131 4132 // First, just null out all Phone.NORMALIZED_NUMBERS for those. 4133 db.execSQL("UPDATE data SET data4 = null" + 4134 " WHERE _id IN (" + dataIdList + ")"); 4135 4136 // Then, re-create phone_lookup for them. 4137 db.execSQL("DELETE FROM phone_lookup" + 4138 " WHERE data_id IN (" + dataIdList + ")"); 4139 4140 for (int i = 0; i < count; i++) { 4141 // Mimic how DataRowHandlerForPhoneNumber.insert() works when it can't normalize 4142 // numbers. 4143 final String phoneNumber = phoneNumbers[i]; 4144 if (TextUtils.isEmpty(phoneNumber)) continue; 4145 4146 final String normalized = PhoneNumberUtils.normalizeNumber(phoneNumber); 4147 if (!TextUtils.isEmpty(normalized)) { 4148 db.execSQL("INSERT INTO phone_lookup" + 4149 "(data_id, raw_contact_id, normalized_number, min_match)" + 4150 " VALUES(?,?,?,?)", 4151 new String[] { 4152 String.valueOf(dataIds[i]), 4153 String.valueOf(rawContactIds[i]), 4154 normalized, 4155 PhoneNumberUtils.toCallerIDMinMatch(normalized)}); 4156 } 4157 } 4158 } 4159 4160 private void upgradeToVersion707(SQLiteDatabase db) { 4161 db.execSQL("ALTER TABLE raw_contacts ADD phonebook_label TEXT;"); 4162 db.execSQL("ALTER TABLE raw_contacts ADD phonebook_bucket INTEGER;"); 4163 db.execSQL("ALTER TABLE raw_contacts ADD phonebook_label_alt TEXT;"); 4164 db.execSQL("ALTER TABLE raw_contacts ADD phonebook_bucket_alt INTEGER;"); 4165 } 4166 4167 private void upgradeToVersion710(SQLiteDatabase db) { 4168 4169 // Adding timestamp to contacts table. 4170 db.execSQL("ALTER TABLE contacts" 4171 + " ADD contact_last_updated_timestamp INTEGER;"); 4172 4173 db.execSQL("UPDATE contacts" 4174 + " SET contact_last_updated_timestamp" 4175 + " = " + System.currentTimeMillis()); 4176 4177 db.execSQL("CREATE INDEX contacts_contact_last_updated_timestamp_index " 4178 + "ON contacts(contact_last_updated_timestamp)"); 4179 4180 // New deleted contacts table. 4181 db.execSQL("CREATE TABLE deleted_contacts (" + 4182 "contact_id INTEGER PRIMARY KEY," + 4183 "contact_deleted_timestamp INTEGER NOT NULL default 0" 4184 + ");"); 4185 4186 db.execSQL("CREATE INDEX deleted_contacts_contact_deleted_timestamp_index " 4187 + "ON deleted_contacts(contact_deleted_timestamp)"); 4188 } 4189 4190 private void upgradeToVersion800(SQLiteDatabase db) { 4191 // Default Calls.PRESENTATION_ALLOWED=1 4192 db.execSQL("ALTER TABLE calls ADD presentation INTEGER NOT NULL DEFAULT 1;"); 4193 4194 // Re-map CallerInfo.{..}_NUMBER strings to Calls.PRESENTATION_{..} ints 4195 // PRIVATE_NUMBER="-2" -> PRESENTATION_RESTRICTED=2 4196 // UNKNOWN_NUMBER="-1" -> PRESENTATION_UNKNOWN =3 4197 // PAYPHONE_NUMBER="-3" -> PRESENTATION_PAYPHONE =4 4198 db.execSQL("UPDATE calls SET presentation=2, number='' WHERE number='-2';"); 4199 db.execSQL("UPDATE calls SET presentation=3, number='' WHERE number='-1';"); 4200 db.execSQL("UPDATE calls SET presentation=4, number='' WHERE number='-3';"); 4201 } 4202 4203 private void upgradeToVersion802(SQLiteDatabase db) { 4204 db.execSQL("ALTER TABLE contacts ADD pinned INTEGER NOT NULL DEFAULT " + 4205 ContactsContract.PinnedPositions.UNPINNED + ";"); 4206 db.execSQL("ALTER TABLE raw_contacts ADD pinned INTEGER NOT NULL DEFAULT " + 4207 ContactsContract.PinnedPositions.UNPINNED + ";"); 4208 } 4209 4210 private void upgradeToVersion902(SQLiteDatabase db) { 4211 // adding account identifier to call log table 4212 db.execSQL("ALTER TABLE calls ADD subscription_component_name TEXT;"); 4213 db.execSQL("ALTER TABLE calls ADD subscription_id TEXT;"); 4214 } 4215 4216 /** 4217 * Searches for any calls in the call log with no normalized phone number and attempts to add 4218 * one if the number can be normalized. 4219 * 4220 * @param db The database. 4221 */ 4222 private void upgradeToVersion903(SQLiteDatabase db) { 4223 // Find the calls in the call log with no normalized phone number. 4224 final Cursor c = db.rawQuery( 4225 "SELECT _id, number, countryiso FROM calls " + 4226 " WHERE (normalized_number is null OR normalized_number = '') " + 4227 " AND countryiso != '' AND countryiso is not null " + 4228 " AND number != '' AND number is not null;", 4229 null 4230 ); 4231 4232 try { 4233 if (c.getCount() == 0) { 4234 return; 4235 } 4236 4237 db.beginTransaction(); 4238 try { 4239 c.moveToPosition(-1); 4240 while (c.moveToNext()) { 4241 final long callId = c.getLong(0); 4242 final String unNormalizedNumber = c.getString(1); 4243 final String countryIso = c.getString(2); 4244 4245 // Attempt to get normalized number. 4246 String normalizedNumber = PhoneNumberUtils 4247 .formatNumberToE164(unNormalizedNumber, countryIso); 4248 4249 if (!TextUtils.isEmpty(normalizedNumber)) { 4250 db.execSQL("UPDATE calls set normalized_number = ? " + 4251 "where _id = ?;", 4252 new String[]{ 4253 normalizedNumber, 4254 String.valueOf(callId), 4255 } 4256 ); 4257 } 4258 } 4259 4260 db.setTransactionSuccessful(); 4261 } finally { 4262 db.endTransaction(); 4263 } 4264 } finally { 4265 c.close(); 4266 } 4267 } 4268 4269 /** 4270 * Updates the calls table in the database to include the call_duration and features columns. 4271 * @param db The database to update. 4272 */ 4273 private void upgradeToVersion904(SQLiteDatabase db) { 4274 db.execSQL("ALTER TABLE calls ADD features INTEGER NOT NULL DEFAULT 0;"); 4275 db.execSQL("ALTER TABLE calls ADD data_usage INTEGER;"); 4276 } 4277 4278 /** 4279 * Adds the voicemail transcription to the Table.Calls 4280 */ 4281 private void upgradeToVersion905(SQLiteDatabase db) { 4282 db.execSQL("ALTER TABLE calls ADD transcription TEXT;"); 4283 } 4284 4285 /** 4286 * Upgrades the database with the new value for {@link PinnedPositions#UNPINNED}. In this 4287 * database version upgrade, the value is changed from 2147483647 (Integer.MAX_VALUE) to 0. 4288 * 4289 * The first pinned contact now starts from position 1. 4290 */ 4291 @VisibleForTesting 4292 public void upgradeToVersion906(SQLiteDatabase db) { 4293 db.execSQL("UPDATE contacts SET pinned = pinned + 1" 4294 + " WHERE pinned >= 0 AND pinned < 2147483647;"); 4295 db.execSQL("UPDATE raw_contacts SET pinned = pinned + 1" 4296 + " WHERE pinned >= 0 AND pinned < 2147483647;"); 4297 4298 db.execSQL("UPDATE contacts SET pinned = 0" 4299 + " WHERE pinned = 2147483647;"); 4300 db.execSQL("UPDATE raw_contacts SET pinned = 0" 4301 + " WHERE pinned = 2147483647;"); 4302 } 4303 4304 private void upgradeToVersion908(SQLiteDatabase db) { 4305 db.execSQL("UPDATE contacts SET pinned = 0 WHERE pinned = 2147483647;"); 4306 db.execSQL("UPDATE raw_contacts SET pinned = 0 WHERE pinned = 2147483647;"); 4307 } 4308 4309 private void upgradeToVersion909(SQLiteDatabase db) { 4310 try { 4311 db.execSQL("ALTER TABLE calls ADD sub_id INTEGER DEFAULT -1;"); 4312 } catch (SQLiteException e) { 4313 // The column already exists--copy over data 4314 db.execSQL("UPDATE calls SET subscription_component_name='com.android.phone/" 4315 + "com.android.services.telephony.TelephonyConnectionService';"); 4316 db.execSQL("UPDATE calls SET subscription_id=sub_id;"); 4317 } 4318 } 4319 4320 /** 4321 * Delete any remaining rows in the calls table if the user is a profile of another user. 4322 * b/17096027 4323 */ 4324 @VisibleForTesting 4325 public void upgradeToVersion910(SQLiteDatabase db) { 4326 final UserManager userManager = (UserManager) mContext.getSystemService( 4327 Context.USER_SERVICE); 4328 final UserInfo user = userManager.getUserInfo(userManager.getUserHandle()); 4329 if (user.isManagedProfile()) { 4330 db.execSQL("DELETE FROM calls;"); 4331 } 4332 } 4333 4334 /** 4335 * Add backup_id column to raw_contacts table and hash_id column to data table. 4336 */ 4337 private void upgradeToVersion1000(SQLiteDatabase db) { 4338 db.execSQL("ALTER TABLE raw_contacts ADD backup_id TEXT;"); 4339 db.execSQL("ALTER TABLE data ADD hash_id TEXT;"); 4340 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS raw_contacts_backup_id_account_id_index ON " + 4341 "raw_contacts (backup_id, account_id);"); 4342 db.execSQL("CREATE INDEX IF NOT EXISTS data_hash_id_index ON data (hash_id);"); 4343 } 4344 4345 @VisibleForTesting 4346 public void upgradeToVersion1002(SQLiteDatabase db) { 4347 db.execSQL("DROP TABLE IF EXISTS pre_authorized_uris;"); 4348 db.execSQL("CREATE TABLE pre_authorized_uris ("+ 4349 "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 4350 "uri STRING NOT NULL, " + 4351 "expiration INTEGER NOT NULL DEFAULT 0);"); 4352 } 4353 4354 public void upgradeToVersion1003(SQLiteDatabase db) { 4355 db.execSQL("ALTER TABLE calls ADD phone_account_address TEXT;"); 4356 4357 // After version 1003, we are using the ICC ID as the phone-account ID. This code updates 4358 // any existing telephony connection-service calllog entries to the ICC ID from the 4359 // previously used subscription ID. 4360 // TODO: This is inconsistent, depending on the initialization state of SubscriptionManager. 4361 // Sometimes it returns zero subscriptions. May want to move this upgrade to run after 4362 // ON_BOOT_COMPLETE instead of PRE_BOOT_COMPLETE. 4363 SubscriptionManager sm = SubscriptionManager.from(mContext); 4364 if (sm != null) { 4365 Log.i(TAG, "count: " + sm.getAllSubscriptionInfoCount()); 4366 for (SubscriptionInfo info : sm.getAllSubscriptionInfoList()) { 4367 String iccId = info.getIccId(); 4368 int subId = info.getSubscriptionId(); 4369 if (!TextUtils.isEmpty(iccId) && 4370 subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) { 4371 StringBuilder sb = new StringBuilder(); 4372 sb.append("UPDATE calls SET subscription_id="); 4373 DatabaseUtils.appendEscapedSQLString(sb, iccId); 4374 sb.append(" WHERE subscription_id="); 4375 sb.append(subId); 4376 sb.append(" AND subscription_component_name='com.android.phone/" 4377 + "com.android.services.telephony.TelephonyConnectionService';"); 4378 4379 db.execSQL(sb.toString()); 4380 } 4381 } 4382 } 4383 } 4384 4385 /** 4386 * Add a "hidden" column for call log entries we want to hide after an upgrade until the user 4387 * adds the right phone account to the device. 4388 */ 4389 public void upgradeToVersion1004(SQLiteDatabase db) { 4390 db.execSQL("ALTER TABLE calls ADD phone_account_hidden INTEGER NOT NULL DEFAULT 0;"); 4391 } 4392 4393 public void upgradeToVersion1005(SQLiteDatabase db) { 4394 db.execSQL("ALTER TABLE calls ADD photo_uri TEXT;"); 4395 } 4396 4397 /** 4398 * The try/catch pattern exists because some devices have the upgrade and some do not. This is 4399 * because the below updates were merged into version 1005 after some devices had already 4400 * upgraded to version 1005 and hence did not receive the below upgrades. 4401 */ 4402 public void upgradeToVersion1007(SQLiteDatabase db) { 4403 try { 4404 // Add multi-sim fields 4405 db.execSQL("ALTER TABLE voicemail_status ADD phone_account_component_name TEXT;"); 4406 db.execSQL("ALTER TABLE voicemail_status ADD phone_account_id TEXT;"); 4407 4408 // For use by the sync adapter 4409 db.execSQL("ALTER TABLE calls ADD dirty INTEGER NOT NULL DEFAULT 0;"); 4410 db.execSQL("ALTER TABLE calls ADD deleted INTEGER NOT NULL DEFAULT 0;"); 4411 } catch (SQLiteException e) { 4412 // These columns already exist. Do nothing. 4413 // Log verbose because this should be the majority case. 4414 Log.v(TAG, "Version 1007: Columns already exist, skipping upgrade steps."); 4415 } 4416 } 4417 4418 public void upgradeToVersion1009(SQLiteDatabase db) { 4419 db.execSQL("ALTER TABLE data ADD carrier_presence INTEGER NOT NULL DEFAULT 0"); 4420 } 4421 4422 public void upgradeToVersion1010(SQLiteDatabase db) { 4423 db.execSQL("DROP TABLE IF EXISTS metadata_sync"); 4424 } 4425 4426 public String extractHandleFromEmailAddress(String email) { 4427 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email); 4428 if (tokens.length == 0) { 4429 return null; 4430 } 4431 4432 String address = tokens[0].getAddress(); 4433 int index = address.indexOf('@'); 4434 if (index != -1) { 4435 return address.substring(0, index); 4436 } 4437 return null; 4438 } 4439 4440 public String extractAddressFromEmailAddress(String email) { 4441 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email); 4442 if (tokens.length == 0) { 4443 return null; 4444 } 4445 return tokens[0].getAddress().trim(); 4446 } 4447 4448 private static long lookupMimeTypeId(SQLiteDatabase db, String mimeType) { 4449 try { 4450 return DatabaseUtils.longForQuery(db, 4451 "SELECT " + MimetypesColumns._ID + 4452 " FROM " + Tables.MIMETYPES + 4453 " WHERE " + MimetypesColumns.MIMETYPE 4454 + "='" + mimeType + "'", null); 4455 } catch (SQLiteDoneException e) { 4456 // No rows of this type in the database. 4457 return -1; 4458 } 4459 } 4460 4461 private void bindString(SQLiteStatement stmt, int index, String value) { 4462 if (value == null) { 4463 stmt.bindNull(index); 4464 } else { 4465 stmt.bindString(index, value); 4466 } 4467 } 4468 4469 private void bindLong(SQLiteStatement stmt, int index, Number value) { 4470 if (value == null) { 4471 stmt.bindNull(index); 4472 } else { 4473 stmt.bindLong(index, value.longValue()); 4474 } 4475 } 4476 4477 /** 4478 * Add a string like "(((column1) = (column2)) OR ((column1) IS NULL AND (column2) IS NULL))" 4479 */ 4480 private static StringBuilder addJoinExpressionAllowingNull( 4481 StringBuilder sb, String column1, String column2) { 4482 4483 sb.append("(((").append(column1).append(")=(").append(column2); 4484 sb.append("))OR(("); 4485 sb.append(column1).append(") IS NULL AND (").append(column2).append(") IS NULL))"); 4486 return sb; 4487 } 4488 4489 /** 4490 * Adds index stats into the SQLite database to force it to always use the lookup indexes. 4491 * 4492 * Note if you drop a table or an index, the corresponding row will be removed from this table. 4493 * Make sure to call this method after such operations. 4494 */ 4495 private void updateSqliteStats(SQLiteDatabase db) { 4496 if (!mDatabaseOptimizationEnabled) { 4497 return; // We don't use sqlite_stat1 during tests. 4498 } 4499 4500 // Specific stats strings are based on an actual large database after running ANALYZE 4501 // Important here are relative sizes. Raw-Contacts is slightly bigger than Contacts 4502 // Warning: Missing tables in here will make SQLite assume to contain 1000000 rows, 4503 // which can lead to catastrophic query plans for small tables 4504 4505 // What these numbers mean is described in this file. 4506 // http://www.sqlite.org/cgi/src/finfo?name=src/analyze.c 4507 4508 // Excerpt: 4509 /* 4510 ** Format of sqlite_stat1: 4511 ** 4512 ** There is normally one row per index, with the index identified by the 4513 ** name in the idx column. The tbl column is the name of the table to 4514 ** which the index belongs. In each such row, the stat column will be 4515 ** a string consisting of a list of integers. The first integer in this 4516 ** list is the number of rows in the index and in the table. The second 4517 ** integer is the average number of rows in the index that have the same 4518 ** value in the first column of the index. The third integer is the average 4519 ** number of rows in the index that have the same value for the first two 4520 ** columns. The N-th integer (for N>1) is the average number of rows in 4521 ** the index which have the same value for the first N-1 columns. For 4522 ** a K-column index, there will be K+1 integers in the stat column. If 4523 ** the index is unique, then the last integer will be 1. 4524 ** 4525 ** The list of integers in the stat column can optionally be followed 4526 ** by the keyword "unordered". The "unordered" keyword, if it is present, 4527 ** must be separated from the last integer by a single space. If the 4528 ** "unordered" keyword is present, then the query planner assumes that 4529 ** the index is unordered and will not use the index for a range query. 4530 ** 4531 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat 4532 ** column contains a single integer which is the (estimated) number of 4533 ** rows in the table identified by sqlite_stat1.tbl. 4534 */ 4535 4536 try { 4537 db.execSQL("DELETE FROM sqlite_stat1"); 4538 updateIndexStats(db, Tables.CONTACTS, 4539 "contacts_has_phone_index", "9000 500"); 4540 updateIndexStats(db, Tables.CONTACTS, 4541 "contacts_name_raw_contact_id_index", "9000 1"); 4542 updateIndexStats(db, Tables.CONTACTS, MoreDatabaseUtils.buildIndexName(Tables.CONTACTS, 4543 Contacts.CONTACT_LAST_UPDATED_TIMESTAMP), "9000 10"); 4544 4545 updateIndexStats(db, Tables.RAW_CONTACTS, 4546 "raw_contacts_contact_id_index", "10000 2"); 4547 updateIndexStats(db, Tables.RAW_CONTACTS, 4548 "raw_contact_sort_key2_index", "10000 2"); 4549 updateIndexStats(db, Tables.RAW_CONTACTS, 4550 "raw_contact_sort_key1_index", "10000 2"); 4551 updateIndexStats(db, Tables.RAW_CONTACTS, 4552 "raw_contacts_source_id_account_id_index", "10000 1 1"); 4553 4554 updateIndexStats(db, Tables.NAME_LOOKUP, 4555 "name_lookup_raw_contact_id_index", "35000 4"); 4556 updateIndexStats(db, Tables.NAME_LOOKUP, 4557 "name_lookup_index", "35000 2 2 2 1"); 4558 updateIndexStats(db, Tables.NAME_LOOKUP, 4559 "sqlite_autoindex_name_lookup_1", "35000 3 2 1"); 4560 4561 updateIndexStats(db, Tables.PHONE_LOOKUP, 4562 "phone_lookup_index", "3500 3 2 1"); 4563 updateIndexStats(db, Tables.PHONE_LOOKUP, 4564 "phone_lookup_min_match_index", "3500 3 2 2"); 4565 updateIndexStats(db, Tables.PHONE_LOOKUP, 4566 "phone_lookup_data_id_min_match_index", "3500 2 2"); 4567 4568 updateIndexStats(db, Tables.DATA, 4569 "data_mimetype_data1_index", "60000 5000 2"); 4570 updateIndexStats(db, Tables.DATA, 4571 "data_raw_contact_id", "60000 10"); 4572 4573 updateIndexStats(db, Tables.GROUPS, 4574 "groups_source_id_account_id_index", "50 2 2 1 1"); 4575 4576 updateIndexStats(db, Tables.NICKNAME_LOOKUP, 4577 "nickname_lookup_index", "500 2 1"); 4578 4579 updateIndexStats(db, Tables.CALLS, 4580 null, "250"); 4581 4582 updateIndexStats(db, Tables.STATUS_UPDATES, 4583 null, "100"); 4584 4585 updateIndexStats(db, Tables.STREAM_ITEMS, 4586 null, "500"); 4587 updateIndexStats(db, Tables.STREAM_ITEM_PHOTOS, 4588 null, "50"); 4589 4590 updateIndexStats(db, Tables.VOICEMAIL_STATUS, 4591 null, "5"); 4592 4593 updateIndexStats(db, Tables.ACCOUNTS, 4594 null, "3"); 4595 4596 updateIndexStats(db, Tables.PRE_AUTHORIZED_URIS, 4597 null, "1"); 4598 4599 updateIndexStats(db, Tables.VISIBLE_CONTACTS, 4600 null, "2000"); 4601 4602 updateIndexStats(db, Tables.PHOTO_FILES, 4603 null, "50"); 4604 4605 updateIndexStats(db, Tables.DEFAULT_DIRECTORY, 4606 null, "1500"); 4607 4608 updateIndexStats(db, Tables.MIMETYPES, 4609 "mime_type", "18 1"); 4610 4611 updateIndexStats(db, Tables.DATA_USAGE_STAT, 4612 "data_usage_stat_index", "20 2 1"); 4613 4614 // Tiny tables 4615 updateIndexStats(db, Tables.AGGREGATION_EXCEPTIONS, 4616 null, "10"); 4617 updateIndexStats(db, Tables.SETTINGS, 4618 null, "10"); 4619 updateIndexStats(db, Tables.PACKAGES, 4620 null, "0"); 4621 updateIndexStats(db, Tables.DIRECTORIES, 4622 null, "3"); 4623 updateIndexStats(db, LegacyApiSupport.LegacyTables.SETTINGS, 4624 null, "0"); 4625 updateIndexStats(db, "android_metadata", 4626 null, "1"); 4627 updateIndexStats(db, "_sync_state", 4628 "sqlite_autoindex__sync_state_1", "2 1 1"); 4629 updateIndexStats(db, "_sync_state_metadata", 4630 null, "1"); 4631 updateIndexStats(db, "properties", 4632 "sqlite_autoindex_properties_1", "4 1"); 4633 4634 // Search index 4635 updateIndexStats(db, "search_index_docsize", 4636 null, "9000"); 4637 updateIndexStats(db, "search_index_content", 4638 null, "9000"); 4639 updateIndexStats(db, "search_index_stat", 4640 null, "1"); 4641 updateIndexStats(db, "search_index_segments", 4642 null, "450"); 4643 updateIndexStats(db, "search_index_segdir", 4644 "sqlite_autoindex_search_index_segdir_1", "9 5 1"); 4645 4646 // Force SQLite to reload sqlite_stat1. 4647 db.execSQL("ANALYZE sqlite_master;"); 4648 } catch (SQLException e) { 4649 Log.e(TAG, "Could not update index stats", e); 4650 } 4651 } 4652 4653 /** 4654 * Stores statistics for a given index. 4655 * 4656 * @param stats has the following structure: the first index is the expected size of 4657 * the table. The following integer(s) are the expected number of records selected with the 4658 * index. There should be one integer per indexed column. 4659 */ 4660 private void updateIndexStats(SQLiteDatabase db, String table, String index, String stats) { 4661 if (index == null) { 4662 db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl=? AND idx IS NULL", 4663 new String[] {table}); 4664 } else { 4665 db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl=? AND idx=?", 4666 new String[] {table, index}); 4667 } 4668 db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat) VALUES (?,?,?)", 4669 new String[] {table, index, stats}); 4670 } 4671 4672 /** 4673 * Wipes all data except mime type and package lookup tables. 4674 */ 4675 public void wipeData() { 4676 SQLiteDatabase db = getWritableDatabase(); 4677 4678 db.execSQL("DELETE FROM " + Tables.ACCOUNTS + ";"); 4679 db.execSQL("DELETE FROM " + Tables.CONTACTS + ";"); 4680 db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";"); 4681 db.execSQL("DELETE FROM " + Tables.STREAM_ITEMS + ";"); 4682 db.execSQL("DELETE FROM " + Tables.STREAM_ITEM_PHOTOS + ";"); 4683 db.execSQL("DELETE FROM " + Tables.PHOTO_FILES + ";"); 4684 db.execSQL("DELETE FROM " + Tables.DATA + ";"); 4685 db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";"); 4686 db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";"); 4687 db.execSQL("DELETE FROM " + Tables.GROUPS + ";"); 4688 db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";"); 4689 db.execSQL("DELETE FROM " + Tables.SETTINGS + ";"); 4690 db.execSQL("DELETE FROM " + Tables.CALLS + ";"); 4691 db.execSQL("DELETE FROM " + Tables.DIRECTORIES + ";"); 4692 db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + ";"); 4693 db.execSQL("DELETE FROM " + Tables.DELETED_CONTACTS + ";"); 4694 db.execSQL("DELETE FROM " + Tables.MIMETYPES + ";"); 4695 db.execSQL("DELETE FROM " + Tables.PACKAGES + ";"); 4696 4697 initializeCache(db); 4698 4699 // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP 4700 } 4701 4702 public NameSplitter createNameSplitter() { 4703 return createNameSplitter(Locale.getDefault()); 4704 } 4705 4706 public NameSplitter createNameSplitter(Locale locale) { 4707 mNameSplitter = new NameSplitter( 4708 mContext.getString(com.android.internal.R.string.common_name_prefixes), 4709 mContext.getString(com.android.internal.R.string.common_last_name_prefixes), 4710 mContext.getString(com.android.internal.R.string.common_name_suffixes), 4711 mContext.getString(com.android.internal.R.string.common_name_conjunctions), 4712 locale); 4713 return mNameSplitter; 4714 } 4715 4716 /** 4717 * Return the {@link ApplicationInfo#uid} for the given package name. 4718 */ 4719 public static int getUidForPackageName(PackageManager pm, String packageName) { 4720 try { 4721 ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */); 4722 return clientInfo.uid; 4723 } catch (NameNotFoundException e) { 4724 throw new RuntimeException(e); 4725 } 4726 } 4727 4728 /** 4729 * Internal method used by {@link #getPackageId} and {@link #getMimeTypeId}. 4730 * 4731 * Note in the contacts provider we avoid using synchronization because it could risk deadlocks. 4732 * So here, instead of using locks, we use ConcurrentHashMap + retry. 4733 * 4734 * Note we can't use a transaction here becuause this method is called from 4735 * onCommitTransaction() too, unfortunately. 4736 */ 4737 private static long getIdCached(SQLiteDatabase db, ConcurrentHashMap<String, Long> cache, 4738 String querySql, String insertSql, String value) { 4739 // First, try the in-memory cache. 4740 if (cache.containsKey(value)) { 4741 return cache.get(value); 4742 } 4743 4744 // Then, try the database. 4745 long id = queryIdWithOneArg(db, querySql, value); 4746 if (id >= 0) { 4747 cache.put(value, id); 4748 return id; 4749 } 4750 4751 // Not found in the database. Try inserting. 4752 id = insertWithOneArgAndReturnId(db, insertSql, value); 4753 if (id >= 0) { 4754 cache.put(value, id); 4755 return id; 4756 } 4757 4758 // Insert failed, which means a race. Let's retry... 4759 4760 // We log here to detect an infinity loop (which shouldn't happen). 4761 // Conflicts should be pretty rare, so it shouldn't spam logcat. 4762 Log.i(TAG, "Cache conflict detected: value=" + value); 4763 try { 4764 Thread.sleep(1); // Just wait a little bit before retry. 4765 } catch (InterruptedException ignore) { 4766 } 4767 return getIdCached(db, cache, querySql, insertSql, value); 4768 } 4769 4770 @VisibleForTesting 4771 static long queryIdWithOneArg(SQLiteDatabase db, String sql, String sqlArgument) { 4772 final SQLiteStatement query = db.compileStatement(sql); 4773 try { 4774 DatabaseUtils.bindObjectToProgram(query, 1, sqlArgument); 4775 try { 4776 return query.simpleQueryForLong(); 4777 } catch (SQLiteDoneException notFound) { 4778 return -1; 4779 } 4780 } finally { 4781 query.close(); 4782 } 4783 } 4784 4785 @VisibleForTesting 4786 static long insertWithOneArgAndReturnId(SQLiteDatabase db, String sql, String sqlArgument) { 4787 final SQLiteStatement insert = db.compileStatement(sql); 4788 try { 4789 DatabaseUtils.bindObjectToProgram(insert, 1, sqlArgument); 4790 try { 4791 return insert.executeInsert(); 4792 } catch (SQLiteConstraintException conflict) { 4793 return -1; 4794 } 4795 } finally { 4796 insert.close(); 4797 } 4798 } 4799 4800 /** 4801 * Convert a package name into an integer, using {@link Tables#PACKAGES} for 4802 * lookups and possible allocation of new IDs as needed. 4803 */ 4804 public long getPackageId(String packageName) { 4805 final String query = 4806 "SELECT " + PackagesColumns._ID + 4807 " FROM " + Tables.PACKAGES + 4808 " WHERE " + PackagesColumns.PACKAGE + "=?"; 4809 4810 final String insert = 4811 "INSERT INTO " + Tables.PACKAGES + "(" 4812 + PackagesColumns.PACKAGE + 4813 ") VALUES (?)"; 4814 return getIdCached(getWritableDatabase(), mPackageCache, query, insert, packageName); 4815 } 4816 4817 /** 4818 * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for 4819 * lookups and possible allocation of new IDs as needed. 4820 */ 4821 public long getMimeTypeId(String mimetype) { 4822 return lookupMimeTypeId(mimetype, getWritableDatabase()); 4823 } 4824 4825 private long lookupMimeTypeId(String mimetype, SQLiteDatabase db) { 4826 final String query = 4827 "SELECT " + MimetypesColumns._ID + 4828 " FROM " + Tables.MIMETYPES + 4829 " WHERE " + MimetypesColumns.MIMETYPE + "=?"; 4830 4831 final String insert = 4832 "INSERT INTO " + Tables.MIMETYPES + "(" 4833 + MimetypesColumns.MIMETYPE + 4834 ") VALUES (?)"; 4835 4836 return getIdCached(db, mMimetypeCache, query, insert, mimetype); 4837 } 4838 4839 public long getMimeTypeIdForStructuredName() { 4840 return mMimeTypeIdStructuredName; 4841 } 4842 4843 public long getMimeTypeIdForStructuredPostal() { 4844 return mMimeTypeIdStructuredPostal; 4845 } 4846 4847 public long getMimeTypeIdForOrganization() { 4848 return mMimeTypeIdOrganization; 4849 } 4850 4851 public long getMimeTypeIdForIm() { 4852 return mMimeTypeIdIm; 4853 } 4854 4855 public long getMimeTypeIdForEmail() { 4856 return mMimeTypeIdEmail; 4857 } 4858 4859 public long getMimeTypeIdForPhone() { 4860 return mMimeTypeIdPhone; 4861 } 4862 4863 public long getMimeTypeIdForSip() { 4864 return mMimeTypeIdSip; 4865 } 4866 4867 /** 4868 * Returns a {@link ContactsContract.DisplayNameSources} value based on {@param mimeTypeId}. 4869 * This does not return {@link ContactsContract.DisplayNameSources#STRUCTURED_PHONETIC_NAME}. 4870 * The calling client needs to inspect the structured name itself to distinguish between 4871 * {@link ContactsContract.DisplayNameSources#STRUCTURED_NAME} and 4872 * {@code STRUCTURED_PHONETIC_NAME}. 4873 */ 4874 private int getDisplayNameSourceForMimeTypeId(int mimeTypeId) { 4875 if (mimeTypeId == mMimeTypeIdStructuredName) { 4876 return DisplayNameSources.STRUCTURED_NAME; 4877 } 4878 if (mimeTypeId == mMimeTypeIdEmail) { 4879 return DisplayNameSources.EMAIL; 4880 } 4881 if (mimeTypeId == mMimeTypeIdPhone) { 4882 return DisplayNameSources.PHONE; 4883 } 4884 if (mimeTypeId == mMimeTypeIdOrganization) { 4885 return DisplayNameSources.ORGANIZATION; 4886 } 4887 if (mimeTypeId == mMimeTypeIdNickname) { 4888 return DisplayNameSources.NICKNAME; 4889 } 4890 return DisplayNameSources.UNDEFINED; 4891 } 4892 4893 /** 4894 * Find the mimetype for the given {@link Data#_ID}. 4895 */ 4896 public String getDataMimeType(long dataId) { 4897 if (mDataMimetypeQuery == null) { 4898 mDataMimetypeQuery = getWritableDatabase().compileStatement( 4899 "SELECT " + MimetypesColumns.MIMETYPE + 4900 " FROM " + Tables.DATA_JOIN_MIMETYPES + 4901 " WHERE " + Tables.DATA + "." + Data._ID + "=?"); 4902 } 4903 try { 4904 // Try database query to find mimetype 4905 DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId); 4906 String mimetype = mDataMimetypeQuery.simpleQueryForString(); 4907 return mimetype; 4908 } catch (SQLiteDoneException e) { 4909 // No valid mapping found, so return null 4910 return null; 4911 } 4912 } 4913 4914 public void invalidateAllCache() { 4915 Log.w(TAG, "invalidateAllCache: [" + getClass().getSimpleName() + "]"); 4916 4917 mMimetypeCache.clear(); 4918 mPackageCache.clear(); 4919 } 4920 4921 /** 4922 * Gets all accounts in the accounts table. 4923 */ 4924 public Set<AccountWithDataSet> getAllAccountsWithDataSets() { 4925 final Set<AccountWithDataSet> result = Sets.newHashSet(); 4926 Cursor c = getReadableDatabase().rawQuery( 4927 "SELECT DISTINCT " + AccountsColumns._ID + "," + AccountsColumns.ACCOUNT_NAME + 4928 "," + AccountsColumns.ACCOUNT_TYPE + "," + AccountsColumns.DATA_SET + 4929 " FROM " + Tables.ACCOUNTS, null); 4930 try { 4931 while (c.moveToNext()) { 4932 result.add(AccountWithDataSet.get(c.getString(1), c.getString(2), c.getString(3))); 4933 } 4934 } finally { 4935 c.close(); 4936 } 4937 return result; 4938 } 4939 4940 /** 4941 * @return ID of the specified account, or null if the account doesn't exist. 4942 */ 4943 public Long getAccountIdOrNull(AccountWithDataSet accountWithDataSet) { 4944 if (accountWithDataSet == null) { 4945 accountWithDataSet = AccountWithDataSet.LOCAL; 4946 } 4947 final SQLiteStatement select = getWritableDatabase().compileStatement( 4948 "SELECT " + AccountsColumns._ID + 4949 " FROM " + Tables.ACCOUNTS + 4950 " WHERE " + 4951 "((?1 IS NULL AND " + AccountsColumns.ACCOUNT_NAME + " IS NULL) OR " + 4952 "(" + AccountsColumns.ACCOUNT_NAME + "=?1)) AND " + 4953 "((?2 IS NULL AND " + AccountsColumns.ACCOUNT_TYPE + " IS NULL) OR " + 4954 "(" + AccountsColumns.ACCOUNT_TYPE + "=?2)) AND " + 4955 "((?3 IS NULL AND " + AccountsColumns.DATA_SET + " IS NULL) OR " + 4956 "(" + AccountsColumns.DATA_SET + "=?3))"); 4957 try { 4958 DatabaseUtils.bindObjectToProgram(select, 1, accountWithDataSet.getAccountName()); 4959 DatabaseUtils.bindObjectToProgram(select, 2, accountWithDataSet.getAccountType()); 4960 DatabaseUtils.bindObjectToProgram(select, 3, accountWithDataSet.getDataSet()); 4961 try { 4962 return select.simpleQueryForLong(); 4963 } catch (SQLiteDoneException notFound) { 4964 return null; 4965 } 4966 } finally { 4967 select.close(); 4968 } 4969 } 4970 4971 /** 4972 * @return ID of the specified account. This method will create a record in the accounts table 4973 * if the account doesn't exist in the accounts table. 4974 * 4975 * This must be used in a transaction, so there's no need for synchronization. 4976 */ 4977 public long getOrCreateAccountIdInTransaction(AccountWithDataSet accountWithDataSet) { 4978 if (accountWithDataSet == null) { 4979 accountWithDataSet = AccountWithDataSet.LOCAL; 4980 } 4981 Long id = getAccountIdOrNull(accountWithDataSet); 4982 if (id != null) { 4983 return id; 4984 } 4985 final SQLiteStatement insert = getWritableDatabase().compileStatement( 4986 "INSERT INTO " + Tables.ACCOUNTS + 4987 " (" + AccountsColumns.ACCOUNT_NAME + ", " + 4988 AccountsColumns.ACCOUNT_TYPE + ", " + 4989 AccountsColumns.DATA_SET + ") VALUES (?, ?, ?)"); 4990 try { 4991 DatabaseUtils.bindObjectToProgram(insert, 1, accountWithDataSet.getAccountName()); 4992 DatabaseUtils.bindObjectToProgram(insert, 2, accountWithDataSet.getAccountType()); 4993 DatabaseUtils.bindObjectToProgram(insert, 3, accountWithDataSet.getDataSet()); 4994 id = insert.executeInsert(); 4995 } finally { 4996 insert.close(); 4997 } 4998 4999 return id; 5000 } 5001 5002 /** 5003 * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts. 5004 */ 5005 public void updateAllVisible() { 5006 updateCustomContactVisibility(getWritableDatabase(), -1); 5007 } 5008 5009 /** 5010 * Updates contact visibility and return true iff the visibility was actually changed. 5011 */ 5012 public boolean updateContactVisibleOnlyIfChanged(TransactionContext txContext, long contactId) { 5013 return updateContactVisible(txContext, contactId, true); 5014 } 5015 5016 /** 5017 * Update {@link Contacts#IN_VISIBLE_GROUP} and 5018 * {@link Tables#DEFAULT_DIRECTORY} for a specific contact. 5019 */ 5020 public void updateContactVisible(TransactionContext txContext, long contactId) { 5021 updateContactVisible(txContext, contactId, false); 5022 } 5023 5024 public boolean updateContactVisible( 5025 TransactionContext txContext, long contactId, boolean onlyIfChanged) { 5026 SQLiteDatabase db = getWritableDatabase(); 5027 updateCustomContactVisibility(db, contactId); 5028 5029 String contactIdAsString = String.valueOf(contactId); 5030 long mimetype = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); 5031 5032 // The contact will be included in the default directory if contains a raw contact that is 5033 // in any group or in an account that does not have any AUTO_ADD groups. 5034 boolean newVisibility = DatabaseUtils.longForQuery(db, 5035 "SELECT EXISTS (" + 5036 "SELECT " + RawContacts.CONTACT_ID + 5037 " FROM " + Tables.RAW_CONTACTS + 5038 " JOIN " + Tables.DATA + 5039 " ON (" + RawContactsColumns.CONCRETE_ID + "=" 5040 + Data.RAW_CONTACT_ID + ")" + 5041 " WHERE " + RawContacts.CONTACT_ID + "=?1" + 5042 " AND " + DataColumns.MIMETYPE_ID + "=?2" + 5043 ") OR EXISTS (" + 5044 "SELECT " + RawContacts._ID + 5045 " FROM " + Tables.RAW_CONTACTS + 5046 " WHERE " + RawContacts.CONTACT_ID + "=?1" + 5047 " AND NOT EXISTS" + 5048 " (SELECT " + Groups._ID + 5049 " FROM " + Tables.GROUPS + 5050 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_ID + " = " 5051 + GroupsColumns.CONCRETE_ACCOUNT_ID + 5052 " AND " + Groups.AUTO_ADD + " != 0" + 5053 ")" + 5054 ") OR EXISTS (" + 5055 "SELECT " + RawContacts._ID + 5056 " FROM " + Tables.RAW_CONTACTS + 5057 " WHERE " + RawContacts.CONTACT_ID + "=?1" + 5058 " AND " + RawContactsColumns.CONCRETE_ACCOUNT_ID + "=" + 5059 Clauses.LOCAL_ACCOUNT_ID + 5060 ")", 5061 new String[] { 5062 contactIdAsString, 5063 String.valueOf(mimetype) 5064 }) != 0; 5065 5066 if (onlyIfChanged) { 5067 boolean oldVisibility = isContactInDefaultDirectory(db, contactId); 5068 if (oldVisibility == newVisibility) { 5069 return false; 5070 } 5071 } 5072 5073 if (newVisibility) { 5074 db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " VALUES(?)", 5075 new String[] {contactIdAsString}); 5076 txContext.invalidateSearchIndexForContact(contactId); 5077 } else { 5078 db.execSQL("DELETE FROM " + Tables.DEFAULT_DIRECTORY + 5079 " WHERE " + Contacts._ID + "=?", 5080 new String[] {contactIdAsString}); 5081 db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + 5082 " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", 5083 new String[] {contactIdAsString}); 5084 } 5085 return true; 5086 } 5087 5088 public boolean isContactInDefaultDirectory(SQLiteDatabase db, long contactId) { 5089 if (mContactInDefaultDirectoryQuery == null) { 5090 mContactInDefaultDirectoryQuery = db.compileStatement( 5091 "SELECT EXISTS (" + 5092 "SELECT 1 FROM " + Tables.DEFAULT_DIRECTORY + 5093 " WHERE " + Contacts._ID + "=?)"); 5094 } 5095 mContactInDefaultDirectoryQuery.bindLong(1, contactId); 5096 return mContactInDefaultDirectoryQuery.simpleQueryForLong() != 0; 5097 } 5098 5099 /** 5100 * Update the visible_contacts table according to the current visibility of contacts, which 5101 * is defined by {@link Clauses#CONTACT_IS_VISIBLE}. 5102 * 5103 * If {@code optionalContactId} is non-negative, it'll update only for the specified contact. 5104 */ 5105 private void updateCustomContactVisibility(SQLiteDatabase db, long optionalContactId) { 5106 final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); 5107 String[] selectionArgs = new String[] {String.valueOf(groupMembershipMimetypeId)}; 5108 5109 final String contactIdSelect = (optionalContactId < 0) ? "" : 5110 (Contacts._ID + "=" + optionalContactId + " AND "); 5111 5112 // First delete what needs to be deleted, then insert what needs to be added. 5113 // Since flash writes are very expensive, this approach is much better than 5114 // delete-all-insert-all. 5115 db.execSQL( 5116 "DELETE FROM " + Tables.VISIBLE_CONTACTS + 5117 " WHERE " + Contacts._ID + " IN" + 5118 "(SELECT " + Contacts._ID + 5119 " FROM " + Tables.CONTACTS + 5120 " WHERE " + contactIdSelect + "(" + Clauses.CONTACT_IS_VISIBLE + ")=0) ", 5121 selectionArgs); 5122 5123 db.execSQL( 5124 "INSERT INTO " + Tables.VISIBLE_CONTACTS + 5125 " SELECT " + Contacts._ID + 5126 " FROM " + Tables.CONTACTS + 5127 " WHERE " + 5128 contactIdSelect + 5129 Contacts._ID + " NOT IN " + Tables.VISIBLE_CONTACTS + 5130 " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=1 ", 5131 selectionArgs); 5132 } 5133 5134 /** 5135 * Returns contact ID for the given contact or zero if it is NULL. 5136 */ 5137 public long getContactId(long rawContactId) { 5138 if (mContactIdQuery == null) { 5139 mContactIdQuery = getWritableDatabase().compileStatement( 5140 "SELECT " + RawContacts.CONTACT_ID + 5141 " FROM " + Tables.RAW_CONTACTS + 5142 " WHERE " + RawContacts._ID + "=?"); 5143 } 5144 try { 5145 DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId); 5146 return mContactIdQuery.simpleQueryForLong(); 5147 } catch (SQLiteDoneException e) { 5148 return 0; // No valid mapping found. 5149 } 5150 } 5151 5152 public int getAggregationMode(long rawContactId) { 5153 if (mAggregationModeQuery == null) { 5154 mAggregationModeQuery = getWritableDatabase().compileStatement( 5155 "SELECT " + RawContacts.AGGREGATION_MODE + 5156 " FROM " + Tables.RAW_CONTACTS + 5157 " WHERE " + RawContacts._ID + "=?"); 5158 } 5159 try { 5160 DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId); 5161 return (int)mAggregationModeQuery.simpleQueryForLong(); 5162 } catch (SQLiteDoneException e) { 5163 return RawContacts.AGGREGATION_MODE_DISABLED; // No valid row found. 5164 } 5165 } 5166 5167 public void buildPhoneLookupAndContactQuery( 5168 SQLiteQueryBuilder qb, String normalizedNumber, String numberE164) { 5169 5170 String minMatch = PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber); 5171 StringBuilder sb = new StringBuilder(); 5172 appendPhoneLookupTables(sb, minMatch, true); 5173 qb.setTables(sb.toString()); 5174 5175 sb = new StringBuilder(); 5176 appendPhoneLookupSelection(sb, normalizedNumber, numberE164); 5177 qb.appendWhere(sb.toString()); 5178 } 5179 5180 /** 5181 * Phone lookup method that uses the custom SQLite function phone_number_compare_loose 5182 * that serves as a fallback in case the regular lookup does not return any results. 5183 * @param qb The query builder. 5184 * @param number The phone number to search for. 5185 */ 5186 public void buildFallbackPhoneLookupAndContactQuery(SQLiteQueryBuilder qb, String number) { 5187 final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number); 5188 final StringBuilder sb = new StringBuilder(); 5189 // Append lookup tables. 5190 sb.append(Tables.RAW_CONTACTS); 5191 sb.append(" JOIN " + Views.CONTACTS + " as contacts_view" 5192 + " ON (contacts_view._id = " + Tables.RAW_CONTACTS 5193 + "." + RawContacts.CONTACT_ID + ")" + 5194 " JOIN (SELECT " + PhoneLookupColumns.DATA_ID + "," + 5195 PhoneLookupColumns.NORMALIZED_NUMBER + " FROM "+ Tables.PHONE_LOOKUP + " " 5196 + "WHERE (" + Tables.PHONE_LOOKUP + "." + PhoneLookupColumns.MIN_MATCH + " = '"); 5197 sb.append(minMatch); 5198 sb.append("')) AS lookup " + 5199 "ON lookup." + PhoneLookupColumns.DATA_ID + "=" + Tables.DATA + "." + Data._ID 5200 + " JOIN " + Tables.DATA + " " 5201 + "ON " + Tables.DATA + "." + Data.RAW_CONTACT_ID + "=" + Tables.RAW_CONTACTS + "." 5202 + RawContacts._ID); 5203 5204 qb.setTables(sb.toString()); 5205 5206 sb.setLength(0); 5207 sb.append("PHONE_NUMBERS_EQUAL(" + Tables.DATA + "." + Phone.NUMBER + ", "); 5208 DatabaseUtils.appendEscapedSQLString(sb, number); 5209 sb.append(mUseStrictPhoneNumberComparison ? ", 1)" : ", 0)"); 5210 qb.appendWhere(sb.toString()); 5211 } 5212 5213 /** 5214 * Adds query for selecting the contact with the given {@code sipAddress} to the given 5215 * {@link StringBuilder}. 5216 * 5217 * @return the query arguments to be passed in with the query 5218 */ 5219 public String[] buildSipContactQuery(StringBuilder sb, String sipAddress) { 5220 sb.append("upper("); 5221 sb.append(Data.DATA1); 5222 sb.append(")=upper(?) AND "); 5223 sb.append(DataColumns.MIMETYPE_ID); 5224 sb.append("="); 5225 sb.append(Long.toString(getMimeTypeIdForSip())); 5226 // Return the arguments to be passed to the query. 5227 return new String[] {sipAddress}; 5228 } 5229 5230 public String buildPhoneLookupAsNestedQuery(String number) { 5231 StringBuilder sb = new StringBuilder(); 5232 final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number); 5233 sb.append("(SELECT DISTINCT raw_contact_id" + " FROM "); 5234 appendPhoneLookupTables(sb, minMatch, false); 5235 sb.append(" WHERE "); 5236 appendPhoneLookupSelection(sb, number, null); 5237 sb.append(")"); 5238 return sb.toString(); 5239 } 5240 5241 private void appendPhoneLookupTables( 5242 StringBuilder sb, final String minMatch, boolean joinContacts) { 5243 5244 sb.append(Tables.RAW_CONTACTS); 5245 if (joinContacts) { 5246 sb.append(" JOIN " + Views.CONTACTS + " contacts_view" 5247 + " ON (contacts_view._id = raw_contacts.contact_id)"); 5248 } 5249 sb.append(", (SELECT data_id, normalized_number, length(normalized_number) as len " 5250 + " FROM phone_lookup " + " WHERE (" + Tables.PHONE_LOOKUP + "." 5251 + PhoneLookupColumns.MIN_MATCH + " = '"); 5252 sb.append(minMatch); 5253 sb.append("')) AS lookup, " + Tables.DATA); 5254 } 5255 5256 private void appendPhoneLookupSelection(StringBuilder sb, String number, String numberE164) { 5257 sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id"); 5258 boolean hasNumberE164 = !TextUtils.isEmpty(numberE164); 5259 boolean hasNumber = !TextUtils.isEmpty(number); 5260 if (hasNumberE164 || hasNumber) { 5261 sb.append(" AND ( "); 5262 if (hasNumberE164) { 5263 sb.append(" lookup.normalized_number = "); 5264 DatabaseUtils.appendEscapedSQLString(sb, numberE164); 5265 } 5266 if (hasNumberE164 && hasNumber) { 5267 sb.append(" OR "); 5268 } 5269 if (hasNumber) { 5270 // Skip the suffix match entirely if we are using strict number comparison. 5271 if (!mUseStrictPhoneNumberComparison) { 5272 int numberLen = number.length(); 5273 sb.append(" lookup.len <= "); 5274 sb.append(numberLen); 5275 sb.append(" AND substr("); 5276 DatabaseUtils.appendEscapedSQLString(sb, number); 5277 sb.append(','); 5278 sb.append(numberLen); 5279 sb.append(" - lookup.len + 1) = lookup.normalized_number"); 5280 5281 // Some countries (e.g. Brazil) can have incoming calls which contain only 5282 // the local number (no country calling code and no area code). This case 5283 // is handled below, see b/5197612. 5284 // This also handles a Gingerbread -> ICS upgrade issue; see b/5638376. 5285 sb.append(" OR ("); 5286 sb.append(" lookup.len > "); 5287 sb.append(numberLen); 5288 sb.append(" AND substr(lookup.normalized_number,"); 5289 sb.append("lookup.len + 1 - "); 5290 sb.append(numberLen); 5291 sb.append(") = "); 5292 DatabaseUtils.appendEscapedSQLString(sb, number); 5293 sb.append(")"); 5294 } else { 5295 sb.append("0"); 5296 } 5297 } 5298 sb.append(')'); 5299 } 5300 } 5301 5302 public String getUseStrictPhoneNumberComparisonParameter() { 5303 return mUseStrictPhoneNumberComparison ? "1" : "0"; 5304 } 5305 5306 /** 5307 * Loads common nickname mappings into the database. 5308 */ 5309 private void loadNicknameLookupTable(SQLiteDatabase db) { 5310 db.execSQL("DELETE FROM " + Tables.NICKNAME_LOOKUP); 5311 5312 String[] strings = mContext.getResources().getStringArray( 5313 com.android.internal.R.array.common_nicknames); 5314 if (strings == null || strings.length == 0) { 5315 return; 5316 } 5317 5318 SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO " 5319 + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + "," 5320 + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)"); 5321 5322 try { 5323 for (int clusterId = 0; clusterId < strings.length; clusterId++) { 5324 String[] names = strings[clusterId].split(","); 5325 for (String name : names) { 5326 String normalizedName = NameNormalizer.normalize(name); 5327 try { 5328 DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, normalizedName); 5329 DatabaseUtils.bindObjectToProgram( 5330 nicknameLookupInsert, 2, String.valueOf(clusterId)); 5331 nicknameLookupInsert.executeInsert(); 5332 } catch (SQLiteException e) { 5333 // Print the exception and keep going (this is not a fatal error). 5334 Log.e(TAG, "Cannot insert nickname: " + name, e); 5335 } 5336 } 5337 } 5338 } finally { 5339 nicknameLookupInsert.close(); 5340 } 5341 } 5342 5343 public static void copyStringValue( 5344 ContentValues toValues, String toKey, ContentValues fromValues, String fromKey) { 5345 5346 if (fromValues.containsKey(fromKey)) { 5347 toValues.put(toKey, fromValues.getAsString(fromKey)); 5348 } 5349 } 5350 5351 public static void copyLongValue( 5352 ContentValues toValues, String toKey, ContentValues fromValues, String fromKey) { 5353 5354 if (fromValues.containsKey(fromKey)) { 5355 long longValue; 5356 Object value = fromValues.get(fromKey); 5357 if (value instanceof Boolean) { 5358 longValue = (Boolean) value ? 1 : 0; 5359 } else if (value instanceof String) { 5360 longValue = Long.parseLong((String)value); 5361 } else { 5362 longValue = ((Number)value).longValue(); 5363 } 5364 toValues.put(toKey, longValue); 5365 } 5366 } 5367 5368 public SyncStateContentProviderHelper getSyncState() { 5369 return mSyncState; 5370 } 5371 5372 /** 5373 * Returns the value from the {@link Tables#PROPERTIES} table. 5374 */ 5375 public String getProperty(String key, String defaultValue) { 5376 return getProperty(getReadableDatabase(), key, defaultValue); 5377 } 5378 5379 public String getProperty(SQLiteDatabase db, String key, String defaultValue) { 5380 Cursor cursor = db.query(Tables.PROPERTIES, 5381 new String[] {PropertiesColumns.PROPERTY_VALUE}, 5382 PropertiesColumns.PROPERTY_KEY + "=?", 5383 new String[] {key}, null, null, null); 5384 String value = null; 5385 try { 5386 if (cursor.moveToFirst()) { 5387 value = cursor.getString(0); 5388 } 5389 } finally { 5390 cursor.close(); 5391 } 5392 5393 return value != null ? value : defaultValue; 5394 } 5395 5396 /** 5397 * Stores a key-value pair in the {@link Tables#PROPERTIES} table. 5398 */ 5399 public void setProperty(String key, String value) { 5400 setProperty(getWritableDatabase(), key, value); 5401 } 5402 5403 private void setProperty(SQLiteDatabase db, String key, String value) { 5404 ContentValues values = new ContentValues(); 5405 values.put(PropertiesColumns.PROPERTY_KEY, key); 5406 values.put(PropertiesColumns.PROPERTY_VALUE, value); 5407 db.replace(Tables.PROPERTIES, null, values); 5408 } 5409 5410 /** 5411 * Test if the given column appears in the given projection. 5412 */ 5413 public static boolean isInProjection(String[] projection, String column) { 5414 if (projection == null) { 5415 return true; // Null means "all columns". We can't really tell if it's in there. 5416 } 5417 for (String test : projection) { 5418 if (column.equals(test)) { 5419 return true; 5420 } 5421 } 5422 return false; 5423 } 5424 5425 /** 5426 * Tests if any of the columns appear in the given projection. 5427 */ 5428 public static boolean isInProjection(String[] projection, String... columns) { 5429 if (projection == null) { 5430 return true; 5431 } 5432 5433 // Optimized for a single-column test 5434 if (columns.length == 1) { 5435 return isInProjection(projection, columns[0]); 5436 } 5437 for (String test : projection) { 5438 for (String column : columns) { 5439 if (column.equals(test)) { 5440 return true; 5441 } 5442 } 5443 } 5444 return false; 5445 } 5446 5447 /** 5448 * Returns a detailed exception message for the supplied URI. It includes the calling 5449 * user and calling package(s). 5450 */ 5451 public String exceptionMessage(Uri uri) { 5452 return exceptionMessage(null, uri); 5453 } 5454 5455 /** 5456 * Returns a detailed exception message for the supplied URI. It includes the calling 5457 * user and calling package(s). 5458 */ 5459 public String exceptionMessage(String message, Uri uri) { 5460 StringBuilder sb = new StringBuilder(); 5461 if (message != null) { 5462 sb.append(message).append("; "); 5463 } 5464 sb.append("URI: ").append(uri); 5465 final PackageManager pm = mContext.getPackageManager(); 5466 int callingUid = Binder.getCallingUid(); 5467 sb.append(", calling user: "); 5468 String userName = pm.getNameForUid(callingUid); 5469 sb.append(userName == null ? callingUid : userName); 5470 5471 final String[] callerPackages = pm.getPackagesForUid(callingUid); 5472 if (callerPackages != null && callerPackages.length > 0) { 5473 if (callerPackages.length == 1) { 5474 sb.append(", calling package:"); 5475 sb.append(callerPackages[0]); 5476 } else { 5477 sb.append(", calling package is one of: ["); 5478 for (int i = 0; i < callerPackages.length; i++) { 5479 if (i != 0) { 5480 sb.append(", "); 5481 } 5482 sb.append(callerPackages[i]); 5483 } 5484 sb.append("]"); 5485 } 5486 } 5487 return sb.toString(); 5488 } 5489 5490 public void deleteStatusUpdate(long dataId) { 5491 if (mStatusUpdateDelete == null) { 5492 mStatusUpdateDelete = getWritableDatabase().compileStatement( 5493 "DELETE FROM " + Tables.STATUS_UPDATES + 5494 " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"); 5495 } 5496 mStatusUpdateDelete.bindLong(1, dataId); 5497 mStatusUpdateDelete.execute(); 5498 } 5499 5500 public void replaceStatusUpdate(Long dataId, long timestamp, String status, String resPackage, 5501 Integer iconResource, Integer labelResource) { 5502 if (mStatusUpdateReplace == null) { 5503 mStatusUpdateReplace = getWritableDatabase().compileStatement( 5504 "INSERT OR REPLACE INTO " + Tables.STATUS_UPDATES + "(" 5505 + StatusUpdatesColumns.DATA_ID + ", " 5506 + StatusUpdates.STATUS_TIMESTAMP + "," 5507 + StatusUpdates.STATUS + "," 5508 + StatusUpdates.STATUS_RES_PACKAGE + "," 5509 + StatusUpdates.STATUS_ICON + "," 5510 + StatusUpdates.STATUS_LABEL + ")" + 5511 " VALUES (?,?,?,?,?,?)"); 5512 } 5513 mStatusUpdateReplace.bindLong(1, dataId); 5514 mStatusUpdateReplace.bindLong(2, timestamp); 5515 bindString(mStatusUpdateReplace, 3, status); 5516 bindString(mStatusUpdateReplace, 4, resPackage); 5517 bindLong(mStatusUpdateReplace, 5, iconResource); 5518 bindLong(mStatusUpdateReplace, 6, labelResource); 5519 mStatusUpdateReplace.execute(); 5520 } 5521 5522 public void insertStatusUpdate(Long dataId, String status, String resPackage, 5523 Integer iconResource, Integer labelResource) { 5524 if (mStatusUpdateInsert == null) { 5525 mStatusUpdateInsert = getWritableDatabase().compileStatement( 5526 "INSERT INTO " + Tables.STATUS_UPDATES + "(" 5527 + StatusUpdatesColumns.DATA_ID + ", " 5528 + StatusUpdates.STATUS + "," 5529 + StatusUpdates.STATUS_RES_PACKAGE + "," 5530 + StatusUpdates.STATUS_ICON + "," 5531 + StatusUpdates.STATUS_LABEL + ")" + 5532 " VALUES (?,?,?,?,?)"); 5533 } 5534 try { 5535 mStatusUpdateInsert.bindLong(1, dataId); 5536 bindString(mStatusUpdateInsert, 2, status); 5537 bindString(mStatusUpdateInsert, 3, resPackage); 5538 bindLong(mStatusUpdateInsert, 4, iconResource); 5539 bindLong(mStatusUpdateInsert, 5, labelResource); 5540 mStatusUpdateInsert.executeInsert(); 5541 } catch (SQLiteConstraintException e) { 5542 // The row already exists - update it 5543 if (mStatusUpdateAutoTimestamp == null) { 5544 mStatusUpdateAutoTimestamp = getWritableDatabase().compileStatement( 5545 "UPDATE " + Tables.STATUS_UPDATES + 5546 " SET " + StatusUpdates.STATUS_TIMESTAMP + "=?," 5547 + StatusUpdates.STATUS + "=?" + 5548 " WHERE " + StatusUpdatesColumns.DATA_ID + "=?" 5549 + " AND " + StatusUpdates.STATUS + "!=?"); 5550 } 5551 5552 long timestamp = System.currentTimeMillis(); 5553 mStatusUpdateAutoTimestamp.bindLong(1, timestamp); 5554 bindString(mStatusUpdateAutoTimestamp, 2, status); 5555 mStatusUpdateAutoTimestamp.bindLong(3, dataId); 5556 bindString(mStatusUpdateAutoTimestamp, 4, status); 5557 mStatusUpdateAutoTimestamp.execute(); 5558 5559 if (mStatusAttributionUpdate == null) { 5560 mStatusAttributionUpdate = getWritableDatabase().compileStatement( 5561 "UPDATE " + Tables.STATUS_UPDATES + 5562 " SET " + StatusUpdates.STATUS_RES_PACKAGE + "=?," 5563 + StatusUpdates.STATUS_ICON + "=?," 5564 + StatusUpdates.STATUS_LABEL + "=?" + 5565 " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"); 5566 } 5567 bindString(mStatusAttributionUpdate, 1, resPackage); 5568 bindLong(mStatusAttributionUpdate, 2, iconResource); 5569 bindLong(mStatusAttributionUpdate, 3, labelResource); 5570 mStatusAttributionUpdate.bindLong(4, dataId); 5571 mStatusAttributionUpdate.execute(); 5572 } 5573 } 5574 5575 /** 5576 * Updates a raw contact display name based on data rows, e.g. structured name, 5577 * organization, email etc. 5578 */ 5579 public void updateRawContactDisplayName(SQLiteDatabase db, long rawContactId) { 5580 if (mNameSplitter == null) { 5581 createNameSplitter(); 5582 } 5583 5584 int bestDisplayNameSource = DisplayNameSources.UNDEFINED; 5585 NameSplitter.Name bestName = null; 5586 String bestDisplayName = null; 5587 String bestPhoneticName = null; 5588 int bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED; 5589 5590 mSelectionArgs1[0] = String.valueOf(rawContactId); 5591 Cursor c = db.rawQuery(RawContactNameQuery.RAW_SQL, mSelectionArgs1); 5592 try { 5593 while (c.moveToNext()) { 5594 int mimeType = c.getInt(RawContactNameQuery.MIMETYPE); 5595 int source = getDisplayNameSourceForMimeTypeId(mimeType); 5596 5597 if (source == DisplayNameSources.STRUCTURED_NAME) { 5598 final String given = c.getString(RawContactNameQuery.GIVEN_NAME); 5599 final String middle = c.getString(RawContactNameQuery.MIDDLE_NAME); 5600 final String family = c.getString(RawContactNameQuery.FAMILY_NAME); 5601 final String suffix = c.getString(RawContactNameQuery.SUFFIX); 5602 final String prefix = c.getString(RawContactNameQuery.PREFIX); 5603 if (TextUtils.isEmpty(given) && TextUtils.isEmpty(middle) 5604 && TextUtils.isEmpty(family) && TextUtils.isEmpty(suffix) 5605 && TextUtils.isEmpty(prefix)) { 5606 // Every non-phonetic name component is empty. Therefore, lets lower the 5607 // source score to STRUCTURED_PHONETIC_NAME. 5608 source = DisplayNameSources.STRUCTURED_PHONETIC_NAME; 5609 } 5610 } 5611 5612 if (source < bestDisplayNameSource || source == DisplayNameSources.UNDEFINED) { 5613 continue; 5614 } 5615 5616 if (source == bestDisplayNameSource 5617 && c.getInt(RawContactNameQuery.IS_PRIMARY) == 0) { 5618 continue; 5619 } 5620 5621 if (mimeType == getMimeTypeIdForStructuredName()) { 5622 NameSplitter.Name name; 5623 if (bestName != null) { 5624 name = new NameSplitter.Name(); 5625 } else { 5626 name = mName; 5627 name.clear(); 5628 } 5629 name.prefix = c.getString(RawContactNameQuery.PREFIX); 5630 name.givenNames = c.getString(RawContactNameQuery.GIVEN_NAME); 5631 name.middleName = c.getString(RawContactNameQuery.MIDDLE_NAME); 5632 name.familyName = c.getString(RawContactNameQuery.FAMILY_NAME); 5633 name.suffix = c.getString(RawContactNameQuery.SUFFIX); 5634 name.fullNameStyle = c.isNull(RawContactNameQuery.FULL_NAME_STYLE) 5635 ? FullNameStyle.UNDEFINED 5636 : c.getInt(RawContactNameQuery.FULL_NAME_STYLE); 5637 name.phoneticFamilyName = c.getString(RawContactNameQuery.PHONETIC_FAMILY_NAME); 5638 name.phoneticMiddleName = c.getString(RawContactNameQuery.PHONETIC_MIDDLE_NAME); 5639 name.phoneticGivenName = c.getString(RawContactNameQuery.PHONETIC_GIVEN_NAME); 5640 name.phoneticNameStyle = c.isNull(RawContactNameQuery.PHONETIC_NAME_STYLE) 5641 ? PhoneticNameStyle.UNDEFINED 5642 : c.getInt(RawContactNameQuery.PHONETIC_NAME_STYLE); 5643 if (!name.isEmpty()) { 5644 bestDisplayNameSource = source; 5645 bestName = name; 5646 } 5647 } else if (mimeType == getMimeTypeIdForOrganization()) { 5648 mCharArrayBuffer.sizeCopied = 0; 5649 c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer); 5650 if (mCharArrayBuffer.sizeCopied != 0) { 5651 bestDisplayNameSource = source; 5652 bestDisplayName = new String(mCharArrayBuffer.data, 0, 5653 mCharArrayBuffer.sizeCopied); 5654 bestPhoneticName = c.getString( 5655 RawContactNameQuery.ORGANIZATION_PHONETIC_NAME); 5656 bestPhoneticNameStyle = 5657 c.isNull(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE) 5658 ? PhoneticNameStyle.UNDEFINED 5659 : c.getInt(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE); 5660 } else { 5661 c.copyStringToBuffer(RawContactNameQuery.TITLE, mCharArrayBuffer); 5662 if (mCharArrayBuffer.sizeCopied != 0) { 5663 bestDisplayNameSource = source; 5664 bestDisplayName = new String(mCharArrayBuffer.data, 0, 5665 mCharArrayBuffer.sizeCopied); 5666 bestPhoneticName = null; 5667 bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED; 5668 } 5669 } 5670 } else { 5671 // Display name is at DATA1 in all other types. 5672 // This is ensured in the constructor. 5673 5674 mCharArrayBuffer.sizeCopied = 0; 5675 c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer); 5676 if (mCharArrayBuffer.sizeCopied != 0) { 5677 bestDisplayNameSource = source; 5678 bestDisplayName = new String(mCharArrayBuffer.data, 0, 5679 mCharArrayBuffer.sizeCopied); 5680 bestPhoneticName = null; 5681 bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED; 5682 } 5683 } 5684 } 5685 5686 } finally { 5687 c.close(); 5688 } 5689 5690 String displayNamePrimary; 5691 String displayNameAlternative; 5692 String sortNamePrimary; 5693 String sortNameAlternative; 5694 String sortKeyPrimary = null; 5695 String sortKeyAlternative = null; 5696 int displayNameStyle = FullNameStyle.UNDEFINED; 5697 5698 if (bestDisplayNameSource == DisplayNameSources.STRUCTURED_NAME 5699 || bestDisplayNameSource == DisplayNameSources.STRUCTURED_PHONETIC_NAME) { 5700 displayNameStyle = bestName.fullNameStyle; 5701 if (displayNameStyle == FullNameStyle.CJK 5702 || displayNameStyle == FullNameStyle.UNDEFINED) { 5703 displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle); 5704 bestName.fullNameStyle = displayNameStyle; 5705 } 5706 5707 displayNamePrimary = mNameSplitter.join(bestName, true, true); 5708 displayNameAlternative = mNameSplitter.join(bestName, false, true); 5709 5710 if (TextUtils.isEmpty(bestName.prefix)) { 5711 sortNamePrimary = displayNamePrimary; 5712 sortNameAlternative = displayNameAlternative; 5713 } else { 5714 sortNamePrimary = mNameSplitter.join(bestName, true, false); 5715 sortNameAlternative = mNameSplitter.join(bestName, false, false); 5716 } 5717 5718 bestPhoneticName = mNameSplitter.joinPhoneticName(bestName); 5719 bestPhoneticNameStyle = bestName.phoneticNameStyle; 5720 } else { 5721 displayNamePrimary = displayNameAlternative = bestDisplayName; 5722 sortNamePrimary = sortNameAlternative = bestDisplayName; 5723 } 5724 5725 if (bestPhoneticName != null) { 5726 if (displayNamePrimary == null) { 5727 displayNamePrimary = bestPhoneticName; 5728 } 5729 if (displayNameAlternative == null) { 5730 displayNameAlternative = bestPhoneticName; 5731 } 5732 // Phonetic names disregard name order so displayNamePrimary and displayNameAlternative 5733 // are the same. 5734 sortKeyPrimary = sortKeyAlternative = bestPhoneticName; 5735 if (bestPhoneticNameStyle == PhoneticNameStyle.UNDEFINED) { 5736 bestPhoneticNameStyle = mNameSplitter.guessPhoneticNameStyle(bestPhoneticName); 5737 } 5738 } else { 5739 bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED; 5740 if (displayNameStyle == FullNameStyle.UNDEFINED) { 5741 displayNameStyle = mNameSplitter.guessFullNameStyle(bestDisplayName); 5742 if (displayNameStyle == FullNameStyle.UNDEFINED 5743 || displayNameStyle == FullNameStyle.CJK) { 5744 displayNameStyle = mNameSplitter.getAdjustedNameStyleBasedOnPhoneticNameStyle( 5745 displayNameStyle, bestPhoneticNameStyle); 5746 } 5747 displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle); 5748 } 5749 if (displayNameStyle == FullNameStyle.CHINESE || 5750 displayNameStyle == FullNameStyle.CJK) { 5751 sortKeyPrimary = sortKeyAlternative = sortNamePrimary; 5752 } 5753 } 5754 5755 if (sortKeyPrimary == null) { 5756 sortKeyPrimary = sortNamePrimary; 5757 sortKeyAlternative = sortNameAlternative; 5758 } 5759 5760 String phonebookLabelPrimary = ""; 5761 String phonebookLabelAlternative = ""; 5762 int phonebookBucketPrimary = 0; 5763 int phonebookBucketAlternative = 0; 5764 ContactLocaleUtils localeUtils = ContactLocaleUtils.getInstance(); 5765 5766 if (sortKeyPrimary != null) { 5767 phonebookBucketPrimary = localeUtils.getBucketIndex(sortKeyPrimary); 5768 phonebookLabelPrimary = localeUtils.getBucketLabel(phonebookBucketPrimary); 5769 } 5770 if (sortKeyAlternative != null) { 5771 phonebookBucketAlternative = localeUtils.getBucketIndex(sortKeyAlternative); 5772 phonebookLabelAlternative = localeUtils.getBucketLabel(phonebookBucketAlternative); 5773 } 5774 5775 if (mRawContactDisplayNameUpdate == null) { 5776 mRawContactDisplayNameUpdate = db.compileStatement( 5777 "UPDATE " + Tables.RAW_CONTACTS + 5778 " SET " + 5779 RawContacts.DISPLAY_NAME_SOURCE + "=?," + 5780 RawContacts.DISPLAY_NAME_PRIMARY + "=?," + 5781 RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," + 5782 RawContacts.PHONETIC_NAME + "=?," + 5783 RawContacts.PHONETIC_NAME_STYLE + "=?," + 5784 RawContacts.SORT_KEY_PRIMARY + "=?," + 5785 RawContactsColumns.PHONEBOOK_LABEL_PRIMARY + "=?," + 5786 RawContactsColumns.PHONEBOOK_BUCKET_PRIMARY + "=?," + 5787 RawContacts.SORT_KEY_ALTERNATIVE + "=?," + 5788 RawContactsColumns.PHONEBOOK_LABEL_ALTERNATIVE + "=?," + 5789 RawContactsColumns.PHONEBOOK_BUCKET_ALTERNATIVE + "=?" + 5790 " WHERE " + RawContacts._ID + "=?"); 5791 } 5792 5793 mRawContactDisplayNameUpdate.bindLong(1, bestDisplayNameSource); 5794 bindString(mRawContactDisplayNameUpdate, 2, displayNamePrimary); 5795 bindString(mRawContactDisplayNameUpdate, 3, displayNameAlternative); 5796 bindString(mRawContactDisplayNameUpdate, 4, bestPhoneticName); 5797 mRawContactDisplayNameUpdate.bindLong(5, bestPhoneticNameStyle); 5798 bindString(mRawContactDisplayNameUpdate, 6, sortKeyPrimary); 5799 bindString(mRawContactDisplayNameUpdate, 7, phonebookLabelPrimary); 5800 mRawContactDisplayNameUpdate.bindLong(8, phonebookBucketPrimary); 5801 bindString(mRawContactDisplayNameUpdate, 9, sortKeyAlternative); 5802 bindString(mRawContactDisplayNameUpdate, 10, phonebookLabelAlternative); 5803 mRawContactDisplayNameUpdate.bindLong(11, phonebookBucketAlternative); 5804 mRawContactDisplayNameUpdate.bindLong(12, rawContactId); 5805 mRawContactDisplayNameUpdate.execute(); 5806 } 5807 5808 /** 5809 * Sets the given dataId record in the "data" table to primary, and resets all data records of 5810 * the same mimetype and under the same contact to not be primary. 5811 * 5812 * @param dataId the id of the data record to be set to primary. Pass -1 to clear the primary 5813 * flag of all data items of this raw contacts 5814 */ 5815 public void setIsPrimary(long rawContactId, long dataId, long mimeTypeId) { 5816 if (mSetPrimaryStatement == null) { 5817 mSetPrimaryStatement = getWritableDatabase().compileStatement( 5818 "UPDATE " + Tables.DATA + 5819 " SET " + Data.IS_PRIMARY + "=(_id=?)" + 5820 " WHERE " + DataColumns.MIMETYPE_ID + "=?" + 5821 " AND " + Data.RAW_CONTACT_ID + "=?"); 5822 } 5823 mSetPrimaryStatement.bindLong(1, dataId); 5824 mSetPrimaryStatement.bindLong(2, mimeTypeId); 5825 mSetPrimaryStatement.bindLong(3, rawContactId); 5826 mSetPrimaryStatement.execute(); 5827 } 5828 5829 /** 5830 * Clears the super primary of all data items of the given raw contact. does not touch 5831 * other raw contacts of the same joined aggregate 5832 */ 5833 public void clearSuperPrimary(long rawContactId, long mimeTypeId) { 5834 if (mClearSuperPrimaryStatement == null) { 5835 mClearSuperPrimaryStatement = getWritableDatabase().compileStatement( 5836 "UPDATE " + Tables.DATA + 5837 " SET " + Data.IS_SUPER_PRIMARY + "=0" + 5838 " WHERE " + DataColumns.MIMETYPE_ID + "=?" + 5839 " AND " + Data.RAW_CONTACT_ID + "=?"); 5840 } 5841 mClearSuperPrimaryStatement.bindLong(1, mimeTypeId); 5842 mClearSuperPrimaryStatement.bindLong(2, rawContactId); 5843 mClearSuperPrimaryStatement.execute(); 5844 } 5845 5846 /** 5847 * Sets the given dataId record in the "data" table to "super primary", and resets all data 5848 * records of the same mimetype and under the same aggregate to not be "super primary". 5849 * 5850 * @param dataId the id of the data record to be set to primary. 5851 */ 5852 public void setIsSuperPrimary(long rawContactId, long dataId, long mimeTypeId) { 5853 if (mSetSuperPrimaryStatement == null) { 5854 mSetSuperPrimaryStatement = getWritableDatabase().compileStatement( 5855 "UPDATE " + Tables.DATA + 5856 " SET " + Data.IS_SUPER_PRIMARY + "=(" + Data._ID + "=?)" + 5857 " WHERE " + DataColumns.MIMETYPE_ID + "=?" + 5858 " AND " + Data.RAW_CONTACT_ID + " IN (" + 5859 "SELECT " + RawContacts._ID + 5860 " FROM " + Tables.RAW_CONTACTS + 5861 " WHERE " + RawContacts.CONTACT_ID + " =(" + 5862 "SELECT " + RawContacts.CONTACT_ID + 5863 " FROM " + Tables.RAW_CONTACTS + 5864 " WHERE " + RawContacts._ID + "=?))"); 5865 } 5866 mSetSuperPrimaryStatement.bindLong(1, dataId); 5867 mSetSuperPrimaryStatement.bindLong(2, mimeTypeId); 5868 mSetSuperPrimaryStatement.bindLong(3, rawContactId); 5869 mSetSuperPrimaryStatement.execute(); 5870 } 5871 5872 /** 5873 * Inserts a record in the {@link Tables#NAME_LOOKUP} table. 5874 */ 5875 public void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) { 5876 if (TextUtils.isEmpty(name)) { 5877 return; 5878 } 5879 5880 if (mNameLookupInsert == null) { 5881 mNameLookupInsert = getWritableDatabase().compileStatement( 5882 "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "(" 5883 + NameLookupColumns.RAW_CONTACT_ID + "," 5884 + NameLookupColumns.DATA_ID + "," 5885 + NameLookupColumns.NAME_TYPE + "," 5886 + NameLookupColumns.NORMALIZED_NAME 5887 + ") VALUES (?,?,?,?)"); 5888 } 5889 mNameLookupInsert.bindLong(1, rawContactId); 5890 mNameLookupInsert.bindLong(2, dataId); 5891 mNameLookupInsert.bindLong(3, lookupType); 5892 bindString(mNameLookupInsert, 4, name); 5893 mNameLookupInsert.executeInsert(); 5894 } 5895 5896 /** 5897 * Deletes all {@link Tables#NAME_LOOKUP} table rows associated with the specified data element. 5898 */ 5899 public void deleteNameLookup(long dataId) { 5900 if (mNameLookupDelete == null) { 5901 mNameLookupDelete = getWritableDatabase().compileStatement( 5902 "DELETE FROM " + Tables.NAME_LOOKUP + 5903 " WHERE " + NameLookupColumns.DATA_ID + "=?"); 5904 } 5905 mNameLookupDelete.bindLong(1, dataId); 5906 mNameLookupDelete.execute(); 5907 } 5908 5909 public String insertNameLookupForEmail(long rawContactId, long dataId, String email) { 5910 if (TextUtils.isEmpty(email)) { 5911 return null; 5912 } 5913 5914 String address = extractHandleFromEmailAddress(email); 5915 if (address == null) { 5916 return null; 5917 } 5918 5919 insertNameLookup(rawContactId, dataId, 5920 NameLookupType.EMAIL_BASED_NICKNAME, NameNormalizer.normalize(address)); 5921 return address; 5922 } 5923 5924 /** 5925 * Normalizes the nickname and inserts it in the name lookup table. 5926 */ 5927 public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) { 5928 if (!TextUtils.isEmpty(nickname)) { 5929 insertNameLookup(rawContactId, dataId, 5930 NameLookupType.NICKNAME, NameNormalizer.normalize(nickname)); 5931 } 5932 } 5933 5934 /** 5935 * Performs a query and returns true if any Data item of the raw contact with the given 5936 * id and mimetype is marked as super-primary 5937 */ 5938 public boolean rawContactHasSuperPrimary(long rawContactId, long mimeTypeId) { 5939 final Cursor existsCursor = getReadableDatabase().rawQuery( 5940 "SELECT EXISTS(SELECT 1 FROM " + Tables.DATA + 5941 " WHERE " + Data.RAW_CONTACT_ID + "=?" + 5942 " AND " + DataColumns.MIMETYPE_ID + "=?" + 5943 " AND " + Data.IS_SUPER_PRIMARY + "<>0)", 5944 new String[] {String.valueOf(rawContactId), String.valueOf(mimeTypeId)}); 5945 try { 5946 if (!existsCursor.moveToFirst()) throw new IllegalStateException(); 5947 return existsCursor.getInt(0) != 0; 5948 } finally { 5949 existsCursor.close(); 5950 } 5951 } 5952 5953 public String getCurrentCountryIso() { 5954 return mCountryMonitor.getCountryIso(); 5955 } 5956 5957 @NeededForTesting 5958 /* package */ void setUseStrictPhoneNumberComparisonForTest(boolean useStrict) { 5959 mUseStrictPhoneNumberComparison = useStrict; 5960 } 5961 5962 @NeededForTesting 5963 /* package */ boolean getUseStrictPhoneNumberComparisonForTest() { 5964 return mUseStrictPhoneNumberComparison; 5965 } 5966 5967 @NeededForTesting 5968 /* package */ String querySearchIndexContentForTest(long contactId) { 5969 return DatabaseUtils.stringForQuery(getReadableDatabase(), 5970 "SELECT " + SearchIndexColumns.CONTENT + 5971 " FROM " + Tables.SEARCH_INDEX + 5972 " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", 5973 new String[] {String.valueOf(contactId)}); 5974 } 5975 5976 @NeededForTesting 5977 /* package */ String querySearchIndexTokensForTest(long contactId) { 5978 return DatabaseUtils.stringForQuery(getReadableDatabase(), 5979 "SELECT " + SearchIndexColumns.TOKENS + 5980 " FROM " + Tables.SEARCH_INDEX + 5981 " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", 5982 new String[] {String.valueOf(contactId)}); 5983 } 5984} 5985