ContactsDatabaseHelper.java revision 4c6e300d8cc5c62e74763454f61f9b10690cc618
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17package com.android.providers.contacts; 18 19import com.android.common.content.SyncStateContentProviderHelper; 20 21import android.content.ContentResolver; 22import android.content.ContentValues; 23import android.content.Context; 24import android.content.pm.ApplicationInfo; 25import android.content.pm.PackageManager; 26import android.content.pm.PackageManager.NameNotFoundException; 27import android.content.res.Resources; 28import android.database.CharArrayBuffer; 29import android.database.Cursor; 30import android.database.DatabaseUtils; 31import android.database.SQLException; 32import android.database.sqlite.SQLiteConstraintException; 33import android.database.sqlite.SQLiteDatabase; 34import android.database.sqlite.SQLiteDoneException; 35import android.database.sqlite.SQLiteException; 36import android.database.sqlite.SQLiteOpenHelper; 37import android.database.sqlite.SQLiteQueryBuilder; 38import android.database.sqlite.SQLiteStatement; 39import android.location.CountryDetector; 40import android.net.Uri; 41import android.os.Binder; 42import android.os.Bundle; 43import android.os.SystemClock; 44import android.provider.BaseColumns; 45import android.provider.CallLog.Calls; 46import android.provider.ContactsContract; 47import android.provider.ContactsContract.AggregationExceptions; 48import android.provider.ContactsContract.CommonDataKinds.Email; 49import android.provider.ContactsContract.CommonDataKinds.GroupMembership; 50import android.provider.ContactsContract.CommonDataKinds.Im; 51import android.provider.ContactsContract.CommonDataKinds.Nickname; 52import android.provider.ContactsContract.CommonDataKinds.Organization; 53import android.provider.ContactsContract.CommonDataKinds.Phone; 54import android.provider.ContactsContract.CommonDataKinds.SipAddress; 55import android.provider.ContactsContract.CommonDataKinds.StructuredName; 56import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; 57import android.provider.ContactsContract.Contacts; 58import android.provider.ContactsContract.Contacts.Photo; 59import android.provider.ContactsContract.Data; 60import android.provider.ContactsContract.Directory; 61import android.provider.ContactsContract.DisplayNameSources; 62import android.provider.ContactsContract.DisplayPhoto; 63import android.provider.ContactsContract.FullNameStyle; 64import android.provider.ContactsContract.Groups; 65import android.provider.ContactsContract.PhoneticNameStyle; 66import android.provider.ContactsContract.PhotoFiles; 67import android.provider.ContactsContract.RawContacts; 68import android.provider.ContactsContract.Settings; 69import android.provider.ContactsContract.StatusUpdates; 70import android.provider.ContactsContract.StreamItemPhotos; 71import android.provider.ContactsContract.StreamItems; 72import android.provider.SocialContract.Activities; 73import android.provider.VoicemailContract; 74import android.provider.VoicemailContract.Voicemails; 75import android.telephony.PhoneNumberUtils; 76import android.text.TextUtils; 77import android.text.util.Rfc822Token; 78import android.text.util.Rfc822Tokenizer; 79import android.util.Log; 80 81import java.util.HashMap; 82import java.util.Locale; 83 84/** 85 * Database helper for contacts. Designed as a singleton to make sure that all 86 * {@link android.content.ContentProvider} users get the same reference. 87 * Provides handy methods for maintaining package and mime-type lookup tables. 88 */ 89/* package */ class ContactsDatabaseHelper extends SQLiteOpenHelper { 90 private static final String TAG = "ContactsDatabaseHelper"; 91 92 /** 93 * Contacts DB version ranges: 94 * <pre> 95 * 0-98 Cupcake/Donut 96 * 100-199 Eclair 97 * 200-299 Eclair-MR1 98 * 300-349 Froyo 99 * 350-399 Gingerbread 100 * 400-499 Honeycomb 101 * 500-549 Honeycomb-MR1 102 * 550-599 Honeycomb-MR2 103 * 600-699 Ice Cream Sandwich 104 * </pre> 105 */ 106 static final int DATABASE_VERSION = 620; 107 108 private static final String DATABASE_NAME = "contacts2.db"; 109 private static final String DATABASE_PRESENCE = "presence_db"; 110 111 112 113 public interface Tables { 114 public static final String CONTACTS = "contacts"; 115 public static final String RAW_CONTACTS = "raw_contacts"; 116 public static final String STREAM_ITEMS = "stream_items"; 117 public static final String STREAM_ITEM_PHOTOS = "stream_item_photos"; 118 public static final String PHOTO_FILES = "photo_files"; 119 public static final String PACKAGES = "packages"; 120 public static final String MIMETYPES = "mimetypes"; 121 public static final String PHONE_LOOKUP = "phone_lookup"; 122 public static final String NAME_LOOKUP = "name_lookup"; 123 public static final String AGGREGATION_EXCEPTIONS = "agg_exceptions"; 124 public static final String SETTINGS = "settings"; 125 public static final String DATA = "data"; 126 public static final String GROUPS = "groups"; 127 public static final String PRESENCE = "presence"; 128 public static final String AGGREGATED_PRESENCE = "agg_presence"; 129 public static final String NICKNAME_LOOKUP = "nickname_lookup"; 130 public static final String CALLS = "calls"; 131 public static final String STATUS_UPDATES = "status_updates"; 132 public static final String PROPERTIES = "properties"; 133 public static final String ACCOUNTS = "accounts"; 134 public static final String VISIBLE_CONTACTS = "visible_contacts"; 135 public static final String DIRECTORIES = "directories"; 136 public static final String DEFAULT_DIRECTORY = "default_directory"; 137 public static final String SEARCH_INDEX = "search_index"; 138 public static final String VOICEMAIL_STATUS = "voicemail_status"; 139 140 // This list of tables contains auto-incremented sequences. 141 public static final String[] SEQUENCE_TABLES = new String[] { 142 CONTACTS, 143 RAW_CONTACTS, 144 STREAM_ITEMS, 145 STREAM_ITEM_PHOTOS, 146 PHOTO_FILES, 147 DATA, 148 GROUPS, 149 CALLS, 150 DIRECTORIES 151 }; 152 153 /** 154 * For {@link ContactsContract.DataUsageFeedback}. The table structure itself 155 * is not exposed outside. 156 */ 157 public static final String DATA_USAGE_STAT = "data_usage_stat"; 158 159 public static final String DATA_JOIN_MIMETYPES = "data " 160 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id)"; 161 162 public static final String DATA_JOIN_RAW_CONTACTS = "data " 163 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)"; 164 165 public static final String DATA_JOIN_MIMETYPE_RAW_CONTACTS = "data " 166 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) " 167 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id)"; 168 169 // NOTE: This requires late binding of GroupMembership MIME-type 170 public static final String RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS = "raw_contacts " 171 + "LEFT OUTER JOIN settings ON (" 172 + "raw_contacts.account_name = settings.account_name AND " 173 + "raw_contacts.account_type = settings.account_type AND " 174 + "((raw_contacts.data_set IS NULL AND settings.data_set IS NULL) " 175 + "OR (raw_contacts.data_set = settings.data_set))) " 176 + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND " 177 + "data.raw_contact_id = raw_contacts._id) " 178 + "LEFT OUTER JOIN groups ON (groups._id = data." + GroupMembership.GROUP_ROW_ID 179 + ")"; 180 181 // NOTE: This requires late binding of GroupMembership MIME-type 182 public static final String SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS = "settings " 183 + "LEFT OUTER JOIN raw_contacts ON (" 184 + "raw_contacts.account_name = settings.account_name AND " 185 + "raw_contacts.account_type = settings.account_type) " 186 + "LEFT OUTER JOIN data ON (data.mimetype_id=? AND " 187 + "data.raw_contact_id = raw_contacts._id) " 188 + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)"; 189 190 public static final String CONTACTS_JOIN_RAW_CONTACTS_DATA_FILTERED_BY_GROUPMEMBERSHIP = 191 Tables.CONTACTS 192 + " INNER JOIN " + Tables.RAW_CONTACTS 193 + " ON (" + RawContactsColumns.CONCRETE_CONTACT_ID + "=" 194 + ContactsColumns.CONCRETE_ID 195 + ")" 196 + " INNER JOIN " + Tables.DATA 197 + " ON (" + DataColumns.CONCRETE_DATA1 + "=" + GroupsColumns.CONCRETE_ID 198 + " AND " 199 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID 200 + " AND " 201 + DataColumns.CONCRETE_MIMETYPE_ID + "=" 202 + "(SELECT " + MimetypesColumns._ID 203 + " FROM " + Tables.MIMETYPES 204 + " WHERE " 205 + MimetypesColumns.CONCRETE_MIMETYPE + "=" 206 + "'" + GroupMembership.CONTENT_ITEM_TYPE + "'" 207 + ")" 208 + ")"; 209 210 public static final String DATA_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_GROUPS = "data " 211 + "JOIN mimetypes ON (data.mimetype_id = mimetypes._id) " 212 + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) " 213 + "LEFT OUTER JOIN packages ON (data.package_id = packages._id) " 214 + "LEFT OUTER JOIN groups " 215 + " ON (mimetypes.mimetype='" + GroupMembership.CONTENT_ITEM_TYPE + "' " 216 + " AND groups._id = data." + GroupMembership.GROUP_ROW_ID + ") "; 217 218 public static final String GROUPS_JOIN_PACKAGES = "groups " 219 + "LEFT OUTER JOIN packages ON (groups.package_id = packages._id)"; 220 221 222 public static final String ACTIVITIES = "activities"; 223 224 public static final String ACTIVITIES_JOIN_MIMETYPES = "activities " 225 + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id)"; 226 227 public static final String ACTIVITIES_JOIN_PACKAGES_MIMETYPES_RAW_CONTACTS_CONTACTS = 228 "activities " 229 + "LEFT OUTER JOIN packages ON (activities.package_id = packages._id) " 230 + "LEFT OUTER JOIN mimetypes ON (activities.mimetype_id = mimetypes._id) " 231 + "LEFT OUTER JOIN raw_contacts ON (activities.author_contact_id = " + 232 "raw_contacts._id) " 233 + "LEFT OUTER JOIN contacts ON (raw_contacts.contact_id = contacts._id)"; 234 235 public static final String NAME_LOOKUP_JOIN_RAW_CONTACTS = "name_lookup " 236 + "INNER JOIN view_raw_contacts ON (name_lookup.raw_contact_id = " 237 + "view_raw_contacts._id)"; 238 } 239 240 public interface Views { 241 public static final String DATA = "view_data"; 242 public static final String RAW_CONTACTS = "view_raw_contacts"; 243 public static final String CONTACTS = "view_contacts"; 244 public static final String ENTITIES = "view_entities"; 245 public static final String RAW_ENTITIES = "view_raw_entities"; 246 public static final String GROUPS = "view_groups"; 247 public static final String DATA_USAGE_STAT = "view_data_usage_stat"; 248 public static final String STREAM_ITEMS = "view_stream_items"; 249 } 250 251 public interface Clauses { 252 final String HAVING_NO_GROUPS = "COUNT(" + DataColumns.CONCRETE_GROUP_ID + ") == 0"; 253 254 final String GROUP_BY_ACCOUNT_CONTACT_ID = SettingsColumns.CONCRETE_ACCOUNT_NAME + "," 255 + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "," + RawContacts.CONTACT_ID; 256 257 final String RAW_CONTACT_IS_LOCAL = RawContactsColumns.CONCRETE_ACCOUNT_NAME 258 + " IS NULL AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL AND " 259 + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL"; 260 261 final String ZERO_GROUP_MEMBERSHIPS = "COUNT(" + GroupsColumns.CONCRETE_ID + ")=0"; 262 263 final String OUTER_RAW_CONTACTS = "outer_raw_contacts"; 264 final String OUTER_RAW_CONTACTS_ID = OUTER_RAW_CONTACTS + "." + RawContacts._ID; 265 266 final String CONTACT_IS_VISIBLE = 267 "SELECT " + 268 "MAX((SELECT (CASE WHEN " + 269 "(CASE" + 270 " WHEN " + RAW_CONTACT_IS_LOCAL + 271 " THEN 1 " + 272 " WHEN " + ZERO_GROUP_MEMBERSHIPS + 273 " THEN " + Settings.UNGROUPED_VISIBLE + 274 " ELSE MAX(" + Groups.GROUP_VISIBLE + ")" + 275 "END)=1 THEN 1 ELSE 0 END)" + 276 " FROM " + Tables.RAW_CONTACTS_JOIN_SETTINGS_DATA_GROUPS + 277 " WHERE " + RawContactsColumns.CONCRETE_ID + "=" + OUTER_RAW_CONTACTS_ID + "))" + 278 " FROM " + Tables.RAW_CONTACTS + " AS " + OUTER_RAW_CONTACTS + 279 " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + 280 " GROUP BY " + RawContacts.CONTACT_ID; 281 282 final String GROUP_HAS_ACCOUNT_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND " 283 + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=? AND " 284 + Groups.DATA_SET + " IS NULL"; 285 286 final String GROUP_HAS_ACCOUNT_AND_DATA_SET_AND_SOURCE_ID = Groups.SOURCE_ID + "=? AND " 287 + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=? AND " 288 + Groups.DATA_SET + "=?"; 289 290 public static final String CONTACT_VISIBLE = 291 "EXISTS (SELECT _id FROM " + Tables.VISIBLE_CONTACTS 292 + " WHERE " + Tables.CONTACTS +"." + Contacts._ID 293 + "=" + Tables.VISIBLE_CONTACTS +"." + Contacts._ID + ")"; 294 } 295 296 public interface ContactsColumns { 297 public static final String LAST_STATUS_UPDATE_ID = "status_update_id"; 298 299 public static final String CONCRETE_ID = Tables.CONTACTS + "." + BaseColumns._ID; 300 301 public static final String CONCRETE_PHOTO_FILE_ID = Tables.CONTACTS + "." 302 + Contacts.PHOTO_FILE_ID; 303 public static final String CONCRETE_TIMES_CONTACTED = Tables.CONTACTS + "." 304 + Contacts.TIMES_CONTACTED; 305 public static final String CONCRETE_LAST_TIME_CONTACTED = Tables.CONTACTS + "." 306 + Contacts.LAST_TIME_CONTACTED; 307 public static final String CONCRETE_STARRED = Tables.CONTACTS + "." + Contacts.STARRED; 308 public static final String CONCRETE_CUSTOM_RINGTONE = Tables.CONTACTS + "." 309 + Contacts.CUSTOM_RINGTONE; 310 public static final String CONCRETE_SEND_TO_VOICEMAIL = Tables.CONTACTS + "." 311 + Contacts.SEND_TO_VOICEMAIL; 312 public static final String CONCRETE_LOOKUP_KEY = Tables.CONTACTS + "." 313 + Contacts.LOOKUP_KEY; 314 } 315 316 public interface RawContactsColumns { 317 public static final String CONCRETE_ID = 318 Tables.RAW_CONTACTS + "." + BaseColumns._ID; 319 public static final String CONCRETE_ACCOUNT_NAME = 320 Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_NAME; 321 public static final String CONCRETE_ACCOUNT_TYPE = 322 Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE; 323 public static final String CONCRETE_DATA_SET = 324 Tables.RAW_CONTACTS + "." + RawContacts.DATA_SET; 325 public static final String CONCRETE_ACCOUNT_TYPE_AND_DATA_SET = 326 Tables.RAW_CONTACTS + "." + RawContacts.ACCOUNT_TYPE_AND_DATA_SET; 327 public static final String CONCRETE_SOURCE_ID = 328 Tables.RAW_CONTACTS + "." + RawContacts.SOURCE_ID; 329 public static final String CONCRETE_VERSION = 330 Tables.RAW_CONTACTS + "." + RawContacts.VERSION; 331 public static final String CONCRETE_DIRTY = 332 Tables.RAW_CONTACTS + "." + RawContacts.DIRTY; 333 public static final String CONCRETE_DELETED = 334 Tables.RAW_CONTACTS + "." + RawContacts.DELETED; 335 public static final String CONCRETE_SYNC1 = 336 Tables.RAW_CONTACTS + "." + RawContacts.SYNC1; 337 public static final String CONCRETE_SYNC2 = 338 Tables.RAW_CONTACTS + "." + RawContacts.SYNC2; 339 public static final String CONCRETE_SYNC3 = 340 Tables.RAW_CONTACTS + "." + RawContacts.SYNC3; 341 public static final String CONCRETE_SYNC4 = 342 Tables.RAW_CONTACTS + "." + RawContacts.SYNC4; 343 public static final String CONCRETE_CUSTOM_RINGTONE = 344 Tables.RAW_CONTACTS + "." + RawContacts.CUSTOM_RINGTONE; 345 public static final String CONCRETE_SEND_TO_VOICEMAIL = 346 Tables.RAW_CONTACTS + "." + RawContacts.SEND_TO_VOICEMAIL; 347 public static final String CONCRETE_LAST_TIME_CONTACTED = 348 Tables.RAW_CONTACTS + "." + RawContacts.LAST_TIME_CONTACTED; 349 public static final String CONCRETE_TIMES_CONTACTED = 350 Tables.RAW_CONTACTS + "." + RawContacts.TIMES_CONTACTED; 351 public static final String CONCRETE_STARRED = 352 Tables.RAW_CONTACTS + "." + RawContacts.STARRED; 353 354 public static final String DISPLAY_NAME = RawContacts.DISPLAY_NAME_PRIMARY; 355 public static final String DISPLAY_NAME_SOURCE = RawContacts.DISPLAY_NAME_SOURCE; 356 public static final String AGGREGATION_NEEDED = "aggregation_needed"; 357 358 public static final String CONCRETE_DISPLAY_NAME = 359 Tables.RAW_CONTACTS + "." + DISPLAY_NAME; 360 public static final String CONCRETE_CONTACT_ID = 361 Tables.RAW_CONTACTS + "." + RawContacts.CONTACT_ID; 362 public static final String CONCRETE_NAME_VERIFIED = 363 Tables.RAW_CONTACTS + "." + RawContacts.NAME_VERIFIED; 364 } 365 366 public interface DataColumns { 367 public static final String PACKAGE_ID = "package_id"; 368 public static final String MIMETYPE_ID = "mimetype_id"; 369 370 public static final String CONCRETE_ID = Tables.DATA + "." + BaseColumns._ID; 371 public static final String CONCRETE_MIMETYPE_ID = Tables.DATA + "." + MIMETYPE_ID; 372 public static final String CONCRETE_RAW_CONTACT_ID = Tables.DATA + "." 373 + Data.RAW_CONTACT_ID; 374 public static final String CONCRETE_GROUP_ID = Tables.DATA + "." 375 + GroupMembership.GROUP_ROW_ID; 376 377 public static final String CONCRETE_DATA1 = Tables.DATA + "." + Data.DATA1; 378 public static final String CONCRETE_DATA2 = Tables.DATA + "." + Data.DATA2; 379 public static final String CONCRETE_DATA3 = Tables.DATA + "." + Data.DATA3; 380 public static final String CONCRETE_DATA4 = Tables.DATA + "." + Data.DATA4; 381 public static final String CONCRETE_DATA5 = Tables.DATA + "." + Data.DATA5; 382 public static final String CONCRETE_DATA6 = Tables.DATA + "." + Data.DATA6; 383 public static final String CONCRETE_DATA7 = Tables.DATA + "." + Data.DATA7; 384 public static final String CONCRETE_DATA8 = Tables.DATA + "." + Data.DATA8; 385 public static final String CONCRETE_DATA9 = Tables.DATA + "." + Data.DATA9; 386 public static final String CONCRETE_DATA10 = Tables.DATA + "." + Data.DATA10; 387 public static final String CONCRETE_DATA11 = Tables.DATA + "." + Data.DATA11; 388 public static final String CONCRETE_DATA12 = Tables.DATA + "." + Data.DATA12; 389 public static final String CONCRETE_DATA13 = Tables.DATA + "." + Data.DATA13; 390 public static final String CONCRETE_DATA14 = Tables.DATA + "." + Data.DATA14; 391 public static final String CONCRETE_DATA15 = Tables.DATA + "." + Data.DATA15; 392 public static final String CONCRETE_IS_PRIMARY = Tables.DATA + "." + Data.IS_PRIMARY; 393 public static final String CONCRETE_PACKAGE_ID = Tables.DATA + "." + PACKAGE_ID; 394 } 395 396 // Used only for legacy API support 397 public interface ExtensionsColumns { 398 public static final String NAME = Data.DATA1; 399 public static final String VALUE = Data.DATA2; 400 } 401 402 public interface GroupMembershipColumns { 403 public static final String RAW_CONTACT_ID = Data.RAW_CONTACT_ID; 404 public static final String GROUP_ROW_ID = GroupMembership.GROUP_ROW_ID; 405 } 406 407 public interface PhoneColumns { 408 public static final String NORMALIZED_NUMBER = Data.DATA4; 409 public static final String CONCRETE_NORMALIZED_NUMBER = DataColumns.CONCRETE_DATA4; 410 } 411 412 public interface GroupsColumns { 413 public static final String PACKAGE_ID = "package_id"; 414 415 public static final String CONCRETE_ID = Tables.GROUPS + "." + BaseColumns._ID; 416 public static final String CONCRETE_SOURCE_ID = Tables.GROUPS + "." + Groups.SOURCE_ID; 417 public static final String CONCRETE_ACCOUNT_NAME = 418 Tables.GROUPS + "." + Groups.ACCOUNT_NAME; 419 public static final String CONCRETE_ACCOUNT_TYPE = 420 Tables.GROUPS + "." + Groups.ACCOUNT_TYPE; 421 public static final String CONCRETE_DATA_SET = Tables.GROUPS + "." + Groups.DATA_SET; 422 public static final String CONCRETE_ACCOUNT_TYPE_AND_DATA_SET = Tables.GROUPS + "." + 423 Groups.ACCOUNT_TYPE_AND_DATA_SET; 424 } 425 426 public interface ActivitiesColumns { 427 public static final String PACKAGE_ID = "package_id"; 428 public static final String MIMETYPE_ID = "mimetype_id"; 429 } 430 431 public interface PhoneLookupColumns { 432 public static final String _ID = BaseColumns._ID; 433 public static final String DATA_ID = "data_id"; 434 public static final String RAW_CONTACT_ID = "raw_contact_id"; 435 public static final String NORMALIZED_NUMBER = "normalized_number"; 436 public static final String MIN_MATCH = "min_match"; 437 } 438 439 public interface NameLookupColumns { 440 public static final String RAW_CONTACT_ID = "raw_contact_id"; 441 public static final String DATA_ID = "data_id"; 442 public static final String NORMALIZED_NAME = "normalized_name"; 443 public static final String NAME_TYPE = "name_type"; 444 } 445 446 public final static class NameLookupType { 447 public static final int NAME_EXACT = 0; 448 public static final int NAME_VARIANT = 1; 449 public static final int NAME_COLLATION_KEY = 2; 450 public static final int NICKNAME = 3; 451 public static final int EMAIL_BASED_NICKNAME = 4; 452 453 // This is the highest name lookup type code plus one 454 public static final int TYPE_COUNT = 5; 455 456 public static boolean isBasedOnStructuredName(int nameLookupType) { 457 return nameLookupType == NameLookupType.NAME_EXACT 458 || nameLookupType == NameLookupType.NAME_VARIANT 459 || nameLookupType == NameLookupType.NAME_COLLATION_KEY; 460 } 461 } 462 463 public interface PackagesColumns { 464 public static final String _ID = BaseColumns._ID; 465 public static final String PACKAGE = "package"; 466 467 public static final String CONCRETE_ID = Tables.PACKAGES + "." + _ID; 468 } 469 470 public interface MimetypesColumns { 471 public static final String _ID = BaseColumns._ID; 472 public static final String MIMETYPE = "mimetype"; 473 474 public static final String CONCRETE_ID = Tables.MIMETYPES + "." + BaseColumns._ID; 475 public static final String CONCRETE_MIMETYPE = Tables.MIMETYPES + "." + MIMETYPE; 476 } 477 478 public interface AggregationExceptionColumns { 479 public static final String _ID = BaseColumns._ID; 480 } 481 482 public interface NicknameLookupColumns { 483 public static final String NAME = "name"; 484 public static final String CLUSTER = "cluster"; 485 } 486 487 public interface SettingsColumns { 488 public static final String CONCRETE_ACCOUNT_NAME = Tables.SETTINGS + "." 489 + Settings.ACCOUNT_NAME; 490 public static final String CONCRETE_ACCOUNT_TYPE = Tables.SETTINGS + "." 491 + Settings.ACCOUNT_TYPE; 492 public static final String CONCRETE_DATA_SET = Tables.SETTINGS + "." 493 + Settings.DATA_SET; 494 } 495 496 public interface PresenceColumns { 497 String RAW_CONTACT_ID = "presence_raw_contact_id"; 498 String CONTACT_ID = "presence_contact_id"; 499 } 500 501 public interface AggregatedPresenceColumns { 502 String CONTACT_ID = "presence_contact_id"; 503 504 String CONCRETE_CONTACT_ID = Tables.AGGREGATED_PRESENCE + "." + CONTACT_ID; 505 } 506 507 public interface StatusUpdatesColumns { 508 String DATA_ID = "status_update_data_id"; 509 510 String CONCRETE_DATA_ID = Tables.STATUS_UPDATES + "." + DATA_ID; 511 512 String CONCRETE_PRESENCE = Tables.STATUS_UPDATES + "." + StatusUpdates.PRESENCE; 513 String CONCRETE_STATUS = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS; 514 String CONCRETE_STATUS_TIMESTAMP = Tables.STATUS_UPDATES + "." 515 + StatusUpdates.STATUS_TIMESTAMP; 516 String CONCRETE_STATUS_RES_PACKAGE = Tables.STATUS_UPDATES + "." 517 + StatusUpdates.STATUS_RES_PACKAGE; 518 String CONCRETE_STATUS_LABEL = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_LABEL; 519 String CONCRETE_STATUS_ICON = Tables.STATUS_UPDATES + "." + StatusUpdates.STATUS_ICON; 520 } 521 522 public interface ContactsStatusUpdatesColumns { 523 String ALIAS = "contacts_" + Tables.STATUS_UPDATES; 524 525 String CONCRETE_DATA_ID = ALIAS + "." + StatusUpdatesColumns.DATA_ID; 526 527 String CONCRETE_PRESENCE = ALIAS + "." + StatusUpdates.PRESENCE; 528 String CONCRETE_STATUS = ALIAS + "." + StatusUpdates.STATUS; 529 String CONCRETE_STATUS_TIMESTAMP = ALIAS + "." + StatusUpdates.STATUS_TIMESTAMP; 530 String CONCRETE_STATUS_RES_PACKAGE = ALIAS + "." + StatusUpdates.STATUS_RES_PACKAGE; 531 String CONCRETE_STATUS_LABEL = ALIAS + "." + StatusUpdates.STATUS_LABEL; 532 String CONCRETE_STATUS_ICON = ALIAS + "." + StatusUpdates.STATUS_ICON; 533 } 534 535 public interface StreamItemsColumns { 536 final String CONCRETE_ID = Tables.STREAM_ITEMS + "." + BaseColumns._ID; 537 final String CONCRETE_RAW_CONTACT_ID = 538 Tables.STREAM_ITEMS + "." + StreamItems.RAW_CONTACT_ID; 539 final String CONCRETE_PACKAGE = Tables.STREAM_ITEMS + "." + StreamItems.RES_PACKAGE; 540 final String CONCRETE_ICON = Tables.STREAM_ITEMS + "." + StreamItems.RES_ICON; 541 final String CONCRETE_LABEL = Tables.STREAM_ITEMS + "." + StreamItems.RES_LABEL; 542 final String CONCRETE_TEXT = Tables.STREAM_ITEMS + "." + StreamItems.TEXT; 543 final String CONCRETE_TIMESTAMP = Tables.STREAM_ITEMS + "." + StreamItems.TIMESTAMP; 544 final String CONCRETE_COMMENTS = Tables.STREAM_ITEMS + "." + StreamItems.COMMENTS; 545 final String CONCRETE_SYNC1 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC1; 546 final String CONCRETE_SYNC2 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC2; 547 final String CONCRETE_SYNC3 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC3; 548 final String CONCRETE_SYNC4 = Tables.STREAM_ITEMS + "." + StreamItems.SYNC4; 549 } 550 551 public interface StreamItemPhotosColumns { 552 final String CONCRETE_ID = Tables.STREAM_ITEM_PHOTOS + "." + BaseColumns._ID; 553 final String CONCRETE_STREAM_ITEM_ID = Tables.STREAM_ITEM_PHOTOS + "." 554 + StreamItemPhotos.STREAM_ITEM_ID; 555 final String CONCRETE_SORT_INDEX = 556 Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SORT_INDEX; 557 final String CONCRETE_PHOTO_FILE_ID = Tables.STREAM_ITEM_PHOTOS + "." 558 + StreamItemPhotos.PHOTO_FILE_ID; 559 final String CONCRETE_SYNC1 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC1; 560 final String CONCRETE_SYNC2 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC2; 561 final String CONCRETE_SYNC3 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC3; 562 final String CONCRETE_SYNC4 = Tables.STREAM_ITEM_PHOTOS + "." + StreamItemPhotos.SYNC4; 563 } 564 565 public interface PhotoFilesColumns { 566 String CONCRETE_ID = Tables.PHOTO_FILES + "." + BaseColumns._ID; 567 String CONCRETE_HEIGHT = Tables.PHOTO_FILES + "." + PhotoFiles.HEIGHT; 568 String CONCRETE_WIDTH = Tables.PHOTO_FILES + "." + PhotoFiles.WIDTH; 569 String CONCRETE_FILESIZE = Tables.PHOTO_FILES + "." + PhotoFiles.FILESIZE; 570 } 571 572 public interface PropertiesColumns { 573 String PROPERTY_KEY = "property_key"; 574 String PROPERTY_VALUE = "property_value"; 575 } 576 577 public interface AccountsColumns { 578 String ACCOUNT_NAME = RawContacts.ACCOUNT_NAME; 579 String ACCOUNT_TYPE = RawContacts.ACCOUNT_TYPE; 580 String DATA_SET = RawContacts.DATA_SET; 581 } 582 583 public static final class DirectoryColumns { 584 public static final String TYPE_RESOURCE_NAME = "typeResourceName"; 585 } 586 587 public static final class SearchIndexColumns { 588 public static final String CONTACT_ID = "contact_id"; 589 public static final String CONTENT = "content"; 590 public static final String NAME = "name"; 591 public static final String TOKENS = "tokens"; 592 } 593 594 /** 595 * Private table for calculating per-contact-method ranking. 596 */ 597 public static final class DataUsageStatColumns { 598 /** type: INTEGER (long) */ 599 public static final String _ID = "stat_id"; 600 public static final String CONCRETE_ID = Tables.DATA_USAGE_STAT + "." + _ID; 601 602 /** type: INTEGER (long) */ 603 public static final String DATA_ID = "data_id"; 604 public static final String CONCRETE_DATA_ID = Tables.DATA_USAGE_STAT + "." + DATA_ID; 605 606 /** type: INTEGER (long) */ 607 public static final String LAST_TIME_USED = "last_time_used"; 608 public static final String CONCRETE_LAST_TIME_USED = 609 Tables.DATA_USAGE_STAT + "." + LAST_TIME_USED; 610 611 /** type: INTEGER */ 612 public static final String TIMES_USED = "times_used"; 613 public static final String CONCRETE_TIMES_USED = 614 Tables.DATA_USAGE_STAT + "." + TIMES_USED; 615 616 /** type: INTEGER */ 617 public static final String USAGE_TYPE_INT = "usage_type"; 618 public static final String CONCRETE_USAGE_TYPE = 619 Tables.DATA_USAGE_STAT + "." + USAGE_TYPE_INT; 620 621 /** 622 * Integer values for USAGE_TYPE. 623 * 624 * @see ContactsContract.DataUsageFeedback#USAGE_TYPE 625 */ 626 public static final int USAGE_TYPE_INT_CALL = 0; 627 public static final int USAGE_TYPE_INT_LONG_TEXT = 1; 628 public static final int USAGE_TYPE_INT_SHORT_TEXT = 2; 629 } 630 631 /** In-memory cache of previously found MIME-type mappings */ 632 private final HashMap<String, Long> mMimetypeCache = new HashMap<String, Long>(); 633 /** In-memory cache of previously found package name mappings */ 634 private final HashMap<String, Long> mPackageCache = new HashMap<String, Long>(); 635 636 private long mMimeTypeIdEmail; 637 private long mMimeTypeIdIm; 638 private long mMimeTypeIdNickname; 639 private long mMimeTypeIdOrganization; 640 private long mMimeTypeIdPhone; 641 private long mMimeTypeIdSip; 642 private long mMimeTypeIdStructuredName; 643 private long mMimeTypeIdStructuredPostal; 644 645 /** Compiled statements for querying and inserting mappings */ 646 private SQLiteStatement mContactIdQuery; 647 private SQLiteStatement mAggregationModeQuery; 648 private SQLiteStatement mDataMimetypeQuery; 649 private SQLiteStatement mActivitiesMimetypeQuery; 650 651 /** Precompiled sql statement for setting a data record to the primary. */ 652 private SQLiteStatement mSetPrimaryStatement; 653 /** Precompiled sql statement for setting a data record to the super primary. */ 654 private SQLiteStatement mSetSuperPrimaryStatement; 655 /** Precompiled sql statement for clearing super primary of a single record. */ 656 private SQLiteStatement mClearSuperPrimaryStatement; 657 /** Precompiled sql statement for updating a contact display name */ 658 private SQLiteStatement mRawContactDisplayNameUpdate; 659 660 private SQLiteStatement mNameLookupInsert; 661 private SQLiteStatement mNameLookupDelete; 662 private SQLiteStatement mStatusUpdateAutoTimestamp; 663 private SQLiteStatement mStatusUpdateInsert; 664 private SQLiteStatement mStatusUpdateReplace; 665 private SQLiteStatement mStatusAttributionUpdate; 666 private SQLiteStatement mStatusUpdateDelete; 667 private SQLiteStatement mResetNameVerifiedForOtherRawContacts; 668 private SQLiteStatement mContactInDefaultDirectoryQuery; 669 670 private final Context mContext; 671 private final boolean mDatabaseOptimizationEnabled; 672 private final SyncStateContentProviderHelper mSyncState; 673 private final CountryMonitor mCountryMonitor; 674 private StringBuilder mSb = new StringBuilder(); 675 676 private boolean mReopenDatabase = false; 677 678 private static ContactsDatabaseHelper sSingleton = null; 679 680 private boolean mUseStrictPhoneNumberComparison; 681 682 private String[] mSelectionArgs1 = new String[1]; 683 private NameSplitter.Name mName = new NameSplitter.Name(); 684 private CharArrayBuffer mCharArrayBuffer = new CharArrayBuffer(128); 685 private NameSplitter mNameSplitter; 686 687 public static synchronized ContactsDatabaseHelper getInstance(Context context) { 688 if (sSingleton == null) { 689 sSingleton = new ContactsDatabaseHelper(context, DATABASE_NAME, true); 690 } 691 return sSingleton; 692 } 693 694 /** 695 * Private constructor, callers except unit tests should obtain an instance through 696 * {@link #getInstance(android.content.Context)} instead. 697 */ 698 ContactsDatabaseHelper(Context context) { 699 this(context, null, false); 700 } 701 702 protected ContactsDatabaseHelper( 703 Context context, String databaseName, boolean optimizationEnabled) { 704 super(context, databaseName, null, DATABASE_VERSION); 705 mDatabaseOptimizationEnabled = optimizationEnabled; 706 Resources resources = context.getResources(); 707 708 mContext = context; 709 mSyncState = new SyncStateContentProviderHelper(); 710 mCountryMonitor = new CountryMonitor(context); 711 mUseStrictPhoneNumberComparison = 712 resources.getBoolean( 713 com.android.internal.R.bool.config_use_strict_phone_number_comparation); 714 } 715 716 private void refreshDatabaseCaches(SQLiteDatabase db) { 717 mStatusUpdateDelete = null; 718 mStatusUpdateReplace = null; 719 mStatusUpdateInsert = null; 720 mStatusUpdateAutoTimestamp = null; 721 mStatusAttributionUpdate = null; 722 mResetNameVerifiedForOtherRawContacts = null; 723 mRawContactDisplayNameUpdate = null; 724 mSetPrimaryStatement = null; 725 mClearSuperPrimaryStatement = null; 726 mSetSuperPrimaryStatement = null; 727 mNameLookupInsert = null; 728 mNameLookupDelete = null; 729 mDataMimetypeQuery = null; 730 mActivitiesMimetypeQuery = null; 731 mContactIdQuery = null; 732 mAggregationModeQuery = null; 733 mContactInDefaultDirectoryQuery = null; 734 735 populateMimeTypeCache(db); 736 } 737 738 private void populateMimeTypeCache(SQLiteDatabase db) { 739 mMimetypeCache.clear(); 740 mPackageCache.clear(); 741 742 // TODO: This could be optimized into one query instead of 7 743 // Also: We shouldn't have those fields in the first place. This should just be 744 // in the cache 745 mMimeTypeIdEmail = lookupMimeTypeId(Email.CONTENT_ITEM_TYPE, db); 746 mMimeTypeIdIm = lookupMimeTypeId(Im.CONTENT_ITEM_TYPE, db); 747 mMimeTypeIdNickname = lookupMimeTypeId(Nickname.CONTENT_ITEM_TYPE, db); 748 mMimeTypeIdOrganization = lookupMimeTypeId(Organization.CONTENT_ITEM_TYPE, db); 749 mMimeTypeIdPhone = lookupMimeTypeId(Phone.CONTENT_ITEM_TYPE, db); 750 mMimeTypeIdSip = lookupMimeTypeId(SipAddress.CONTENT_ITEM_TYPE, db); 751 mMimeTypeIdStructuredName = lookupMimeTypeId(StructuredName.CONTENT_ITEM_TYPE, db); 752 mMimeTypeIdStructuredPostal = lookupMimeTypeId(StructuredPostal.CONTENT_ITEM_TYPE, db); 753 } 754 755 @Override 756 public void onOpen(SQLiteDatabase db) { 757 refreshDatabaseCaches(db); 758 759 mSyncState.onDatabaseOpened(db); 760 761 db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";"); 762 db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_PRESENCE + "." + Tables.PRESENCE + " ("+ 763 StatusUpdates.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," + 764 StatusUpdates.PROTOCOL + " INTEGER NOT NULL," + 765 StatusUpdates.CUSTOM_PROTOCOL + " TEXT," + 766 StatusUpdates.IM_HANDLE + " TEXT," + 767 StatusUpdates.IM_ACCOUNT + " TEXT," + 768 PresenceColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," + 769 PresenceColumns.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," + 770 StatusUpdates.PRESENCE + " INTEGER," + 771 StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0," + 772 "UNIQUE(" + StatusUpdates.PROTOCOL + ", " + StatusUpdates.CUSTOM_PROTOCOL 773 + ", " + StatusUpdates.IM_HANDLE + ", " + StatusUpdates.IM_ACCOUNT + ")" + 774 ");"); 775 776 db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex" + " ON " 777 + Tables.PRESENCE + " (" + PresenceColumns.RAW_CONTACT_ID + ");"); 778 db.execSQL("CREATE INDEX IF NOT EXISTS " + DATABASE_PRESENCE + ".presenceIndex2" + " ON " 779 + Tables.PRESENCE + " (" + PresenceColumns.CONTACT_ID + ");"); 780 781 db.execSQL("CREATE TABLE IF NOT EXISTS " 782 + DATABASE_PRESENCE + "." + Tables.AGGREGATED_PRESENCE + " ("+ 783 AggregatedPresenceColumns.CONTACT_ID 784 + " INTEGER PRIMARY KEY REFERENCES contacts(_id)," + 785 StatusUpdates.PRESENCE + " INTEGER," + 786 StatusUpdates.CHAT_CAPABILITY + " INTEGER NOT NULL DEFAULT 0" + 787 ");"); 788 789 790 db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_deleted" 791 + " BEFORE DELETE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE 792 + " BEGIN " 793 + " DELETE FROM " + Tables.AGGREGATED_PRESENCE 794 + " WHERE " + AggregatedPresenceColumns.CONTACT_ID + " = " + 795 "(SELECT " + PresenceColumns.CONTACT_ID + 796 " FROM " + Tables.PRESENCE + 797 " WHERE " + PresenceColumns.RAW_CONTACT_ID 798 + "=OLD." + PresenceColumns.RAW_CONTACT_ID + 799 " AND NOT EXISTS" + 800 "(SELECT " + PresenceColumns.RAW_CONTACT_ID + 801 " FROM " + Tables.PRESENCE + 802 " WHERE " + PresenceColumns.CONTACT_ID 803 + "=OLD." + PresenceColumns.CONTACT_ID + 804 " AND " + PresenceColumns.RAW_CONTACT_ID 805 + "!=OLD." + PresenceColumns.RAW_CONTACT_ID + "));" 806 + " END"); 807 808 final String replaceAggregatePresenceSql = 809 "INSERT OR REPLACE INTO " + Tables.AGGREGATED_PRESENCE + "(" 810 + AggregatedPresenceColumns.CONTACT_ID + ", " 811 + StatusUpdates.PRESENCE + ", " 812 + StatusUpdates.CHAT_CAPABILITY + ")" 813 + " SELECT " 814 + PresenceColumns.CONTACT_ID + "," 815 + StatusUpdates.PRESENCE + "," 816 + StatusUpdates.CHAT_CAPABILITY 817 + " FROM " + Tables.PRESENCE 818 + " WHERE " 819 + " (ifnull(" + StatusUpdates.PRESENCE + ",0) * 10 " 820 + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))" 821 + " = (SELECT " 822 + "MAX (ifnull(" + StatusUpdates.PRESENCE + ",0) * 10 " 823 + "+ ifnull(" + StatusUpdates.CHAT_CAPABILITY + ", 0))" 824 + " FROM " + Tables.PRESENCE 825 + " WHERE " + PresenceColumns.CONTACT_ID 826 + "=NEW." + PresenceColumns.CONTACT_ID 827 + ")" 828 + " AND " + PresenceColumns.CONTACT_ID + "=NEW." + PresenceColumns.CONTACT_ID + ";"; 829 830 db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_inserted" 831 + " AFTER INSERT ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE 832 + " BEGIN " 833 + replaceAggregatePresenceSql 834 + " END"); 835 836 db.execSQL("CREATE TRIGGER " + DATABASE_PRESENCE + "." + Tables.PRESENCE + "_updated" 837 + " AFTER UPDATE ON " + DATABASE_PRESENCE + "." + Tables.PRESENCE 838 + " BEGIN " 839 + replaceAggregatePresenceSql 840 + " END"); 841 } 842 843 @Override 844 public void onCreate(SQLiteDatabase db) { 845 Log.i(TAG, "Bootstrapping database version: " + DATABASE_VERSION); 846 847 mSyncState.createDatabase(db); 848 849 // One row per group of contacts corresponding to the same person 850 db.execSQL("CREATE TABLE " + Tables.CONTACTS + " (" + 851 BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 852 Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," + 853 Contacts.PHOTO_ID + " INTEGER REFERENCES data(_id)," + 854 Contacts.PHOTO_FILE_ID + " INTEGER REFERENCES photo_files(_id)," + 855 Contacts.CUSTOM_RINGTONE + " TEXT," + 856 Contacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," + 857 Contacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," + 858 Contacts.LAST_TIME_CONTACTED + " INTEGER," + 859 Contacts.STARRED + " INTEGER NOT NULL DEFAULT 0," + 860 Contacts.HAS_PHONE_NUMBER + " INTEGER NOT NULL DEFAULT 0," + 861 Contacts.LOOKUP_KEY + " TEXT," + 862 ContactsColumns.LAST_STATUS_UPDATE_ID + " INTEGER REFERENCES data(_id)" + 863 ");"); 864 865 db.execSQL("CREATE INDEX contacts_has_phone_index ON " + Tables.CONTACTS + " (" + 866 Contacts.HAS_PHONE_NUMBER + 867 ");"); 868 869 db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" + 870 Contacts.NAME_RAW_CONTACT_ID + 871 ");"); 872 873 // Contacts table 874 db.execSQL("CREATE TABLE " + Tables.RAW_CONTACTS + " (" + 875 RawContacts._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 876 RawContacts.ACCOUNT_NAME + " STRING DEFAULT NULL, " + 877 RawContacts.ACCOUNT_TYPE + " STRING DEFAULT NULL, " + 878 RawContacts.DATA_SET + " STRING DEFAULT NULL, " + 879 RawContacts.SOURCE_ID + " TEXT," + 880 RawContacts.RAW_CONTACT_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," + 881 RawContacts.VERSION + " INTEGER NOT NULL DEFAULT 1," + 882 RawContacts.DIRTY + " INTEGER NOT NULL DEFAULT 0," + 883 RawContacts.DELETED + " INTEGER NOT NULL DEFAULT 0," + 884 RawContacts.CONTACT_ID + " INTEGER REFERENCES contacts(_id)," + 885 RawContacts.AGGREGATION_MODE + " INTEGER NOT NULL DEFAULT " + 886 RawContacts.AGGREGATION_MODE_DEFAULT + "," + 887 RawContactsColumns.AGGREGATION_NEEDED + " INTEGER NOT NULL DEFAULT 1," + 888 RawContacts.CUSTOM_RINGTONE + " TEXT," + 889 RawContacts.SEND_TO_VOICEMAIL + " INTEGER NOT NULL DEFAULT 0," + 890 RawContacts.TIMES_CONTACTED + " INTEGER NOT NULL DEFAULT 0," + 891 RawContacts.LAST_TIME_CONTACTED + " INTEGER," + 892 RawContacts.STARRED + " INTEGER NOT NULL DEFAULT 0," + 893 RawContacts.DISPLAY_NAME_PRIMARY + " TEXT," + 894 RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT," + 895 RawContacts.DISPLAY_NAME_SOURCE + " INTEGER NOT NULL DEFAULT " + 896 DisplayNameSources.UNDEFINED + "," + 897 RawContacts.PHONETIC_NAME + " TEXT," + 898 RawContacts.PHONETIC_NAME_STYLE + " TEXT," + 899 RawContacts.SORT_KEY_PRIMARY + " TEXT COLLATE " + 900 ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," + 901 RawContacts.SORT_KEY_ALTERNATIVE + " TEXT COLLATE " + 902 ContactsProvider2.PHONEBOOK_COLLATOR_NAME + "," + 903 RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0," + 904 RawContacts.SYNC1 + " TEXT, " + 905 RawContacts.SYNC2 + " TEXT, " + 906 RawContacts.SYNC3 + " TEXT, " + 907 RawContacts.SYNC4 + " TEXT " + 908 ");"); 909 910 db.execSQL("CREATE INDEX raw_contacts_contact_id_index ON " + Tables.RAW_CONTACTS + " (" + 911 RawContacts.CONTACT_ID + 912 ");"); 913 914 db.execSQL("CREATE INDEX raw_contacts_source_id_index ON " + Tables.RAW_CONTACTS + " (" + 915 RawContacts.SOURCE_ID + ", " + 916 RawContacts.ACCOUNT_TYPE + ", " + 917 RawContacts.ACCOUNT_NAME + 918 ");"); 919 920 db.execSQL("CREATE INDEX raw_contacts_source_id_data_set_index ON " + 921 Tables.RAW_CONTACTS + " (" + 922 RawContacts.SOURCE_ID + ", " + 923 RawContacts.ACCOUNT_TYPE + ", " + 924 RawContacts.ACCOUNT_NAME + ", " + 925 RawContacts.DATA_SET + 926 ");"); 927 928 db.execSQL("CREATE TABLE " + Tables.STREAM_ITEMS + " (" + 929 StreamItems._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 930 StreamItems.RAW_CONTACT_ID + " INTEGER NOT NULL, " + 931 StreamItems.RES_PACKAGE + " TEXT, " + 932 StreamItems.RES_ICON + " TEXT, " + 933 StreamItems.RES_LABEL + " TEXT, " + 934 StreamItems.TEXT + " TEXT, " + 935 StreamItems.TIMESTAMP + " INTEGER NOT NULL, " + 936 StreamItems.COMMENTS + " TEXT, " + 937 StreamItems.SYNC1 + " TEXT, " + 938 StreamItems.SYNC2 + " TEXT, " + 939 StreamItems.SYNC3 + " TEXT, " + 940 StreamItems.SYNC4 + " TEXT, " + 941 "FOREIGN KEY(" + StreamItems.RAW_CONTACT_ID + ") REFERENCES " + 942 Tables.RAW_CONTACTS + "(" + RawContacts._ID + "));"); 943 944 db.execSQL("CREATE TABLE " + Tables.STREAM_ITEM_PHOTOS + " (" + 945 StreamItemPhotos._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 946 StreamItemPhotos.STREAM_ITEM_ID + " INTEGER NOT NULL, " + 947 StreamItemPhotos.SORT_INDEX + " INTEGER, " + 948 StreamItemPhotos.PHOTO_FILE_ID + " INTEGER NOT NULL, " + 949 StreamItemPhotos.SYNC1 + " TEXT, " + 950 StreamItemPhotos.SYNC2 + " TEXT, " + 951 StreamItemPhotos.SYNC3 + " TEXT, " + 952 StreamItemPhotos.SYNC4 + " TEXT, " + 953 "FOREIGN KEY(" + StreamItemPhotos.STREAM_ITEM_ID + ") REFERENCES " + 954 Tables.STREAM_ITEMS + "(" + StreamItems._ID + "));"); 955 956 db.execSQL("CREATE TABLE " + Tables.PHOTO_FILES + " (" + 957 PhotoFiles._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 958 PhotoFiles.HEIGHT + " INTEGER NOT NULL, " + 959 PhotoFiles.WIDTH + " INTEGER NOT NULL, " + 960 PhotoFiles.FILESIZE + " INTEGER NOT NULL);"); 961 962 // TODO readd the index and investigate a controlled use of it 963// db.execSQL("CREATE INDEX raw_contacts_agg_index ON " + Tables.RAW_CONTACTS + " (" + 964// RawContactsColumns.AGGREGATION_NEEDED + 965// ");"); 966 967 // Package name mapping table 968 db.execSQL("CREATE TABLE " + Tables.PACKAGES + " (" + 969 PackagesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 970 PackagesColumns.PACKAGE + " TEXT NOT NULL" + 971 ");"); 972 973 // Mimetype mapping table 974 db.execSQL("CREATE TABLE " + Tables.MIMETYPES + " (" + 975 MimetypesColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 976 MimetypesColumns.MIMETYPE + " TEXT NOT NULL" + 977 ");"); 978 979 // Mimetype table requires an index on mime type 980 db.execSQL("CREATE UNIQUE INDEX mime_type ON " + Tables.MIMETYPES + " (" + 981 MimetypesColumns.MIMETYPE + 982 ");"); 983 984 // Public generic data table 985 db.execSQL("CREATE TABLE " + Tables.DATA + " (" + 986 Data._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 987 DataColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," + 988 DataColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," + 989 Data.RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 990 Data.IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," + 991 Data.IS_PRIMARY + " INTEGER NOT NULL DEFAULT 0," + 992 Data.IS_SUPER_PRIMARY + " INTEGER NOT NULL DEFAULT 0," + 993 Data.DATA_VERSION + " INTEGER NOT NULL DEFAULT 0," + 994 Data.DATA1 + " TEXT," + 995 Data.DATA2 + " TEXT," + 996 Data.DATA3 + " TEXT," + 997 Data.DATA4 + " TEXT," + 998 Data.DATA5 + " TEXT," + 999 Data.DATA6 + " TEXT," + 1000 Data.DATA7 + " TEXT," + 1001 Data.DATA8 + " TEXT," + 1002 Data.DATA9 + " TEXT," + 1003 Data.DATA10 + " TEXT," + 1004 Data.DATA11 + " TEXT," + 1005 Data.DATA12 + " TEXT," + 1006 Data.DATA13 + " TEXT," + 1007 Data.DATA14 + " TEXT," + 1008 Data.DATA15 + " TEXT," + 1009 Data.SYNC1 + " TEXT, " + 1010 Data.SYNC2 + " TEXT, " + 1011 Data.SYNC3 + " TEXT, " + 1012 Data.SYNC4 + " TEXT " + 1013 ");"); 1014 1015 db.execSQL("CREATE INDEX data_raw_contact_id ON " + Tables.DATA + " (" + 1016 Data.RAW_CONTACT_ID + 1017 ");"); 1018 1019 /** 1020 * For email lookup and similar queries. 1021 */ 1022 db.execSQL("CREATE INDEX data_mimetype_data1_index ON " + Tables.DATA + " (" + 1023 DataColumns.MIMETYPE_ID + "," + 1024 Data.DATA1 + 1025 ");"); 1026 1027 // Private phone numbers table used for lookup 1028 db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" + 1029 PhoneLookupColumns.DATA_ID 1030 + " INTEGER REFERENCES data(_id) NOT NULL," + 1031 PhoneLookupColumns.RAW_CONTACT_ID 1032 + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 1033 PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," + 1034 PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" + 1035 ");"); 1036 1037 db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" + 1038 PhoneLookupColumns.NORMALIZED_NUMBER + "," + 1039 PhoneLookupColumns.RAW_CONTACT_ID + "," + 1040 PhoneLookupColumns.DATA_ID + 1041 ");"); 1042 1043 db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" + 1044 PhoneLookupColumns.MIN_MATCH + "," + 1045 PhoneLookupColumns.RAW_CONTACT_ID + "," + 1046 PhoneLookupColumns.DATA_ID + 1047 ");"); 1048 1049 db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP + 1050 " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");"); 1051 1052 // Private name/nickname table used for lookup 1053 db.execSQL("CREATE TABLE " + Tables.NAME_LOOKUP + " (" + 1054 NameLookupColumns.DATA_ID 1055 + " INTEGER REFERENCES data(_id) NOT NULL," + 1056 NameLookupColumns.RAW_CONTACT_ID 1057 + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 1058 NameLookupColumns.NORMALIZED_NAME + " TEXT NOT NULL," + 1059 NameLookupColumns.NAME_TYPE + " INTEGER NOT NULL," + 1060 "PRIMARY KEY (" 1061 + NameLookupColumns.DATA_ID + ", " 1062 + NameLookupColumns.NORMALIZED_NAME + ", " 1063 + NameLookupColumns.NAME_TYPE + ")" + 1064 ");"); 1065 1066 db.execSQL("CREATE INDEX name_lookup_raw_contact_id_index ON " + Tables.NAME_LOOKUP + " (" + 1067 NameLookupColumns.RAW_CONTACT_ID + 1068 ");"); 1069 1070 db.execSQL("CREATE TABLE " + Tables.NICKNAME_LOOKUP + " (" + 1071 NicknameLookupColumns.NAME + " TEXT," + 1072 NicknameLookupColumns.CLUSTER + " TEXT" + 1073 ");"); 1074 1075 db.execSQL("CREATE UNIQUE INDEX nickname_lookup_index ON " + Tables.NICKNAME_LOOKUP + " (" + 1076 NicknameLookupColumns.NAME + ", " + 1077 NicknameLookupColumns.CLUSTER + 1078 ");"); 1079 1080 // Groups table 1081 db.execSQL("CREATE TABLE " + Tables.GROUPS + " (" + 1082 Groups._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1083 GroupsColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," + 1084 Groups.ACCOUNT_NAME + " STRING DEFAULT NULL, " + 1085 Groups.ACCOUNT_TYPE + " STRING DEFAULT NULL, " + 1086 Groups.DATA_SET + " STRING DEFAULT NULL, " + 1087 Groups.SOURCE_ID + " TEXT," + 1088 Groups.VERSION + " INTEGER NOT NULL DEFAULT 1," + 1089 Groups.DIRTY + " INTEGER NOT NULL DEFAULT 0," + 1090 Groups.TITLE + " TEXT," + 1091 Groups.TITLE_RES + " INTEGER," + 1092 Groups.NOTES + " TEXT," + 1093 Groups.SYSTEM_ID + " TEXT," + 1094 Groups.DELETED + " INTEGER NOT NULL DEFAULT 0," + 1095 Groups.GROUP_VISIBLE + " INTEGER NOT NULL DEFAULT 0," + 1096 Groups.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1," + 1097 Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0," + 1098 Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0," + 1099 Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0," + 1100 Groups.SYNC1 + " TEXT, " + 1101 Groups.SYNC2 + " TEXT, " + 1102 Groups.SYNC3 + " TEXT, " + 1103 Groups.SYNC4 + " TEXT " + 1104 ");"); 1105 1106 db.execSQL("CREATE INDEX groups_source_id_index ON " + Tables.GROUPS + " (" + 1107 Groups.SOURCE_ID + ", " + 1108 Groups.ACCOUNT_TYPE + ", " + 1109 Groups.ACCOUNT_NAME + 1110 ");"); 1111 1112 db.execSQL("CREATE INDEX groups_source_id_data_set_index ON " + Tables.GROUPS + " (" + 1113 Groups.SOURCE_ID + ", " + 1114 Groups.ACCOUNT_TYPE + ", " + 1115 Groups.ACCOUNT_NAME + ", " + 1116 Groups.DATA_SET + 1117 ");"); 1118 1119 db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.AGGREGATION_EXCEPTIONS + " (" + 1120 AggregationExceptionColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1121 AggregationExceptions.TYPE + " INTEGER NOT NULL, " + 1122 AggregationExceptions.RAW_CONTACT_ID1 1123 + " INTEGER REFERENCES raw_contacts(_id), " + 1124 AggregationExceptions.RAW_CONTACT_ID2 1125 + " INTEGER REFERENCES raw_contacts(_id)" + 1126 ");"); 1127 1128 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index1 ON " + 1129 Tables.AGGREGATION_EXCEPTIONS + " (" + 1130 AggregationExceptions.RAW_CONTACT_ID1 + ", " + 1131 AggregationExceptions.RAW_CONTACT_ID2 + 1132 ");"); 1133 1134 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS aggregation_exception_index2 ON " + 1135 Tables.AGGREGATION_EXCEPTIONS + " (" + 1136 AggregationExceptions.RAW_CONTACT_ID2 + ", " + 1137 AggregationExceptions.RAW_CONTACT_ID1 + 1138 ");"); 1139 1140 db.execSQL("CREATE TABLE IF NOT EXISTS " + Tables.SETTINGS + " (" + 1141 Settings.ACCOUNT_NAME + " STRING NOT NULL," + 1142 Settings.ACCOUNT_TYPE + " STRING NOT NULL," + 1143 Settings.DATA_SET + " STRING," + 1144 Settings.UNGROUPED_VISIBLE + " INTEGER NOT NULL DEFAULT 0," + 1145 Settings.SHOULD_SYNC + " INTEGER NOT NULL DEFAULT 1" + 1146 ");"); 1147 1148 db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" + 1149 Contacts._ID + " INTEGER PRIMARY KEY" + 1150 ");"); 1151 1152 db.execSQL("CREATE TABLE " + Tables.DEFAULT_DIRECTORY + " (" + 1153 Contacts._ID + " INTEGER PRIMARY KEY" + 1154 ");"); 1155 1156 // The table for recent calls is here so we can do table joins 1157 // on people, phones, and calls all in one place. 1158 db.execSQL("CREATE TABLE " + Tables.CALLS + " (" + 1159 Calls._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1160 Calls.NUMBER + " TEXT," + 1161 Calls.DATE + " INTEGER," + 1162 Calls.DURATION + " INTEGER," + 1163 Calls.TYPE + " INTEGER," + 1164 Calls.NEW + " INTEGER," + 1165 Calls.CACHED_NAME + " TEXT," + 1166 Calls.CACHED_NUMBER_TYPE + " INTEGER," + 1167 Calls.CACHED_NUMBER_LABEL + " TEXT," + 1168 Calls.COUNTRY_ISO + " TEXT," + 1169 Calls.VOICEMAIL_URI + " TEXT," + 1170 Calls.IS_READ + " INTEGER," + 1171 Calls.GEOCODED_LOCATION + " TEXT," + 1172 Calls.CACHED_LOOKUP_URI + " TEXT," + 1173 Calls.CACHED_MATCHED_NUMBER + " TEXT," + 1174 Calls.CACHED_NORMALIZED_NUMBER + " TEXT," + 1175 Calls.CACHED_PHOTO_ID + " INTEGER NOT NULL DEFAULT 0," + 1176 Voicemails._DATA + " TEXT," + 1177 Voicemails.HAS_CONTENT + " INTEGER," + 1178 Voicemails.MIME_TYPE + " TEXT," + 1179 Voicemails.SOURCE_DATA + " TEXT," + 1180 Voicemails.SOURCE_PACKAGE + " TEXT," + 1181 Voicemails.STATE + " INTEGER" + 1182 ");"); 1183 1184 // Voicemail source status table. 1185 db.execSQL("CREATE TABLE " + Tables.VOICEMAIL_STATUS + " (" + 1186 VoicemailContract.Status._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1187 VoicemailContract.Status.SOURCE_PACKAGE + " TEXT UNIQUE NOT NULL," + 1188 VoicemailContract.Status.SETTINGS_URI + " TEXT," + 1189 VoicemailContract.Status.VOICEMAIL_ACCESS_URI + " TEXT," + 1190 VoicemailContract.Status.CONFIGURATION_STATE + " INTEGER," + 1191 VoicemailContract.Status.DATA_CHANNEL_STATE + " INTEGER," + 1192 VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE + " INTEGER" + 1193 ");"); 1194 1195 // Activities table 1196 db.execSQL("CREATE TABLE " + Tables.ACTIVITIES + " (" + 1197 Activities._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1198 ActivitiesColumns.PACKAGE_ID + " INTEGER REFERENCES package(_id)," + 1199 ActivitiesColumns.MIMETYPE_ID + " INTEGER REFERENCES mimetype(_id) NOT NULL," + 1200 Activities.RAW_ID + " TEXT," + 1201 Activities.IN_REPLY_TO + " TEXT," + 1202 Activities.AUTHOR_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," + 1203 Activities.TARGET_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)," + 1204 Activities.PUBLISHED + " INTEGER NOT NULL," + 1205 Activities.THREAD_PUBLISHED + " INTEGER NOT NULL," + 1206 Activities.TITLE + " TEXT NOT NULL," + 1207 Activities.SUMMARY + " TEXT," + 1208 Activities.LINK + " TEXT, " + 1209 Activities.THUMBNAIL + " BLOB" + 1210 ");"); 1211 1212 db.execSQL("CREATE TABLE " + Tables.STATUS_UPDATES + " (" + 1213 StatusUpdatesColumns.DATA_ID + " INTEGER PRIMARY KEY REFERENCES data(_id)," + 1214 StatusUpdates.STATUS + " TEXT," + 1215 StatusUpdates.STATUS_TIMESTAMP + " INTEGER," + 1216 StatusUpdates.STATUS_RES_PACKAGE + " TEXT, " + 1217 StatusUpdates.STATUS_LABEL + " INTEGER, " + 1218 StatusUpdates.STATUS_ICON + " INTEGER" + 1219 ");"); 1220 1221 db.execSQL("CREATE TABLE " + Tables.PROPERTIES + " (" + 1222 PropertiesColumns.PROPERTY_KEY + " TEXT PRIMARY KEY, " + 1223 PropertiesColumns.PROPERTY_VALUE + " TEXT " + 1224 ");"); 1225 1226 db.execSQL("CREATE TABLE " + Tables.ACCOUNTS + " (" + 1227 AccountsColumns.ACCOUNT_NAME + " TEXT, " + 1228 AccountsColumns.ACCOUNT_TYPE + " TEXT, " + 1229 AccountsColumns.DATA_SET + " TEXT" + 1230 ");"); 1231 1232 // Allow contacts without any account to be created for now. Achieve that 1233 // by inserting a fake account with both type and name as NULL. 1234 db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL, NULL)"); 1235 1236 createDirectoriesTable(db); 1237 createSearchIndexTable(db); 1238 1239 db.execSQL("CREATE TABLE " + Tables.DATA_USAGE_STAT + "(" + 1240 DataUsageStatColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 1241 DataUsageStatColumns.DATA_ID + " INTEGER NOT NULL, " + 1242 DataUsageStatColumns.USAGE_TYPE_INT + " INTEGER NOT NULL DEFAULT 0, " + 1243 DataUsageStatColumns.TIMES_USED + " INTEGER NOT NULL DEFAULT 0, " + 1244 DataUsageStatColumns.LAST_TIME_USED + " INTERGER NOT NULL DEFAULT 0, " + 1245 "FOREIGN KEY(" + DataUsageStatColumns.DATA_ID + ") REFERENCES " 1246 + Tables.DATA + "(" + Data._ID + ")" + 1247 ");"); 1248 db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " + 1249 Tables.DATA_USAGE_STAT + " (" + 1250 DataUsageStatColumns.DATA_ID + ", " + 1251 DataUsageStatColumns.USAGE_TYPE_INT + 1252 ");"); 1253 1254 createContactsViews(db); 1255 createGroupsView(db); 1256 createContactsTriggers(db); 1257 createContactsIndexes(db); 1258 1259 loadNicknameLookupTable(db); 1260 1261 // Set sequence starts. 1262 initializeAutoIncrementSequences(db); 1263 1264 // Add the legacy API support views, etc 1265 LegacyApiSupport.createDatabase(db); 1266 1267 if (mDatabaseOptimizationEnabled) { 1268 // This will create a sqlite_stat1 table that is used for query optimization 1269 db.execSQL("ANALYZE;"); 1270 1271 updateSqliteStats(db); 1272 1273 // We need to close and reopen the database connection so that the stats are 1274 // taken into account. Make a note of it and do the actual reopening in the 1275 // getWritableDatabase method. 1276 mReopenDatabase = true; 1277 } 1278 1279 ContentResolver.requestSync(null /* all accounts */, 1280 ContactsContract.AUTHORITY, new Bundle()); 1281 } 1282 1283 protected void initializeAutoIncrementSequences(SQLiteDatabase db) { 1284 // Default implementation does nothing. 1285 } 1286 1287 private void createDirectoriesTable(SQLiteDatabase db) { 1288 db.execSQL("CREATE TABLE " + Tables.DIRECTORIES + "(" + 1289 Directory._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 1290 Directory.PACKAGE_NAME + " TEXT NOT NULL," + 1291 Directory.DIRECTORY_AUTHORITY + " TEXT NOT NULL," + 1292 Directory.TYPE_RESOURCE_ID + " INTEGER," + 1293 DirectoryColumns.TYPE_RESOURCE_NAME + " TEXT," + 1294 Directory.ACCOUNT_TYPE + " TEXT," + 1295 Directory.ACCOUNT_NAME + " TEXT," + 1296 Directory.DISPLAY_NAME + " TEXT, " + 1297 Directory.EXPORT_SUPPORT + " INTEGER NOT NULL" + 1298 " DEFAULT " + Directory.EXPORT_SUPPORT_NONE + "," + 1299 Directory.SHORTCUT_SUPPORT + " INTEGER NOT NULL" + 1300 " DEFAULT " + Directory.SHORTCUT_SUPPORT_NONE + "," + 1301 Directory.PHOTO_SUPPORT + " INTEGER NOT NULL" + 1302 " DEFAULT " + Directory.PHOTO_SUPPORT_NONE + 1303 ");"); 1304 1305 // Trigger a full scan of directories in the system 1306 setProperty(db, ContactDirectoryManager.PROPERTY_DIRECTORY_SCAN_COMPLETE, "0"); 1307 } 1308 1309 public void createSearchIndexTable(SQLiteDatabase db) { 1310 db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_INDEX); 1311 db.execSQL("CREATE VIRTUAL TABLE " + Tables.SEARCH_INDEX 1312 + " USING FTS4 (" 1313 + SearchIndexColumns.CONTACT_ID + " INTEGER REFERENCES contacts(_id) NOT NULL," 1314 + SearchIndexColumns.CONTENT + " TEXT, " 1315 + SearchIndexColumns.NAME + " TEXT, " 1316 + SearchIndexColumns.TOKENS + " TEXT" 1317 + ")"); 1318 } 1319 1320 private void createContactsTriggers(SQLiteDatabase db) { 1321 1322 /* 1323 * Automatically delete Data rows when a raw contact is deleted. 1324 */ 1325 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_deleted;"); 1326 db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_deleted " 1327 + " BEFORE DELETE ON " + Tables.RAW_CONTACTS 1328 + " BEGIN " 1329 + " DELETE FROM " + Tables.DATA 1330 + " WHERE " + Data.RAW_CONTACT_ID 1331 + "=OLD." + RawContacts._ID + ";" 1332 + " DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS 1333 + " WHERE " + AggregationExceptions.RAW_CONTACT_ID1 1334 + "=OLD." + RawContacts._ID 1335 + " OR " + AggregationExceptions.RAW_CONTACT_ID2 1336 + "=OLD." + RawContacts._ID + ";" 1337 + " DELETE FROM " + Tables.VISIBLE_CONTACTS 1338 + " WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID 1339 + " AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS 1340 + " WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID 1341 + " )=1;" 1342 + " DELETE FROM " + Tables.DEFAULT_DIRECTORY 1343 + " WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID 1344 + " AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS 1345 + " WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID 1346 + " )=1;" 1347 + " DELETE FROM " + Tables.CONTACTS 1348 + " WHERE " + Contacts._ID + "=OLD." + RawContacts.CONTACT_ID 1349 + " AND (SELECT COUNT(*) FROM " + Tables.RAW_CONTACTS 1350 + " WHERE " + RawContacts.CONTACT_ID + "=OLD." + RawContacts.CONTACT_ID 1351 + " )=1;" 1352 + " END"); 1353 1354 1355 db.execSQL("DROP TRIGGER IF EXISTS contacts_times_contacted;"); 1356 db.execSQL("DROP TRIGGER IF EXISTS raw_contacts_times_contacted;"); 1357 1358 /* 1359 * Triggers that update {@link RawContacts#VERSION} when the contact is 1360 * marked for deletion or any time a data row is inserted, updated or 1361 * deleted. 1362 */ 1363 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.RAW_CONTACTS + "_marked_deleted;"); 1364 db.execSQL("CREATE TRIGGER " + Tables.RAW_CONTACTS + "_marked_deleted " 1365 + " AFTER UPDATE ON " + Tables.RAW_CONTACTS 1366 + " BEGIN " 1367 + " UPDATE " + Tables.RAW_CONTACTS 1368 + " SET " 1369 + RawContacts.VERSION + "=OLD." + RawContacts.VERSION + "+1 " 1370 + " WHERE " + RawContacts._ID + "=OLD." + RawContacts._ID 1371 + " AND NEW." + RawContacts.DELETED + "!= OLD." + RawContacts.DELETED + ";" 1372 + " END"); 1373 1374 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_updated;"); 1375 db.execSQL("CREATE TRIGGER " + Tables.DATA + "_updated AFTER UPDATE ON " + Tables.DATA 1376 + " BEGIN " 1377 + " UPDATE " + Tables.DATA 1378 + " SET " + Data.DATA_VERSION + "=OLD." + Data.DATA_VERSION + "+1 " 1379 + " WHERE " + Data._ID + "=OLD." + Data._ID + ";" 1380 + " UPDATE " + Tables.RAW_CONTACTS 1381 + " SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 " 1382 + " WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";" 1383 + " END"); 1384 1385 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.DATA + "_deleted;"); 1386 db.execSQL("CREATE TRIGGER " + Tables.DATA + "_deleted BEFORE DELETE ON " + Tables.DATA 1387 + " BEGIN " 1388 + " UPDATE " + Tables.RAW_CONTACTS 1389 + " SET " + RawContacts.VERSION + "=" + RawContacts.VERSION + "+1 " 1390 + " WHERE " + RawContacts._ID + "=OLD." + Data.RAW_CONTACT_ID + ";" 1391 + " DELETE FROM " + Tables.PHONE_LOOKUP 1392 + " WHERE " + PhoneLookupColumns.DATA_ID + "=OLD." + Data._ID + ";" 1393 + " DELETE FROM " + Tables.STATUS_UPDATES 1394 + " WHERE " + StatusUpdatesColumns.DATA_ID + "=OLD." + Data._ID + ";" 1395 + " DELETE FROM " + Tables.NAME_LOOKUP 1396 + " WHERE " + NameLookupColumns.DATA_ID + "=OLD." + Data._ID + ";" 1397 + " END"); 1398 1399 1400 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_updated1;"); 1401 db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_updated1 " 1402 + " AFTER UPDATE ON " + Tables.GROUPS 1403 + " BEGIN " 1404 + " UPDATE " + Tables.GROUPS 1405 + " SET " 1406 + Groups.VERSION + "=OLD." + Groups.VERSION + "+1" 1407 + " WHERE " + Groups._ID + "=OLD." + Groups._ID + ";" 1408 + " END"); 1409 1410 // Update DEFAULT_FILTER table per AUTO_ADD column update. 1411 // See also upgradeToVersion411(). 1412 final String insertContactsWithoutAccount = ( 1413 " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + 1414 " SELECT " + RawContacts.CONTACT_ID + 1415 " FROM " + Tables.RAW_CONTACTS + 1416 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " + 1417 " AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL; "); 1418 final String insertContactsWithAccountNoDefaultGroup = ( 1419 " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + 1420 " SELECT " + RawContacts.CONTACT_ID + 1421 " FROM " + Tables.RAW_CONTACTS + 1422 " WHERE NOT EXISTS" + 1423 " (SELECT " + Groups._ID + 1424 " FROM " + Tables.GROUPS + 1425 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = " + 1426 GroupsColumns.CONCRETE_ACCOUNT_NAME + 1427 " AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = " + 1428 GroupsColumns.CONCRETE_ACCOUNT_TYPE + 1429 " AND " + Groups.AUTO_ADD + " != 0" + ");"); 1430 final String insertContactsWithAccountDefaultGroup = ( 1431 " INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + 1432 " SELECT " + RawContacts.CONTACT_ID + 1433 " FROM " + Tables.RAW_CONTACTS + 1434 " JOIN " + Tables.DATA + 1435 " ON (" + RawContactsColumns.CONCRETE_ID + "=" + 1436 Data.RAW_CONTACT_ID + ")" + 1437 " WHERE " + DataColumns.MIMETYPE_ID + "=" + 1438 "(SELECT " + MimetypesColumns._ID + " FROM " + Tables.MIMETYPES + 1439 " WHERE " + MimetypesColumns.MIMETYPE + 1440 "='" + GroupMembership.CONTENT_ITEM_TYPE + "')" + 1441 " AND EXISTS" + 1442 " (SELECT " + Groups._ID + 1443 " FROM " + Tables.GROUPS + 1444 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = " + 1445 GroupsColumns.CONCRETE_ACCOUNT_NAME + 1446 " AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = " + 1447 GroupsColumns.CONCRETE_ACCOUNT_TYPE + 1448 " AND " + Groups.AUTO_ADD + " != 0" + ");"); 1449 1450 db.execSQL("DROP TRIGGER IF EXISTS " + Tables.GROUPS + "_auto_add_updated1;"); 1451 db.execSQL("CREATE TRIGGER " + Tables.GROUPS + "_auto_add_updated1 " 1452 + " AFTER UPDATE OF " + Groups.AUTO_ADD + " ON " + Tables.GROUPS 1453 + " BEGIN " 1454 + " DELETE FROM " + Tables.DEFAULT_DIRECTORY + ";" 1455 + insertContactsWithoutAccount 1456 + insertContactsWithAccountNoDefaultGroup 1457 + insertContactsWithAccountDefaultGroup 1458 + " END"); 1459 } 1460 1461 private void createContactsIndexes(SQLiteDatabase db) { 1462 db.execSQL("DROP INDEX IF EXISTS name_lookup_index"); 1463 db.execSQL("CREATE INDEX name_lookup_index ON " + Tables.NAME_LOOKUP + " (" + 1464 NameLookupColumns.NORMALIZED_NAME + "," + 1465 NameLookupColumns.NAME_TYPE + ", " + 1466 NameLookupColumns.RAW_CONTACT_ID + ", " + 1467 NameLookupColumns.DATA_ID + 1468 ");"); 1469 1470 db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key1_index"); 1471 db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" + 1472 RawContacts.SORT_KEY_PRIMARY + 1473 ");"); 1474 1475 db.execSQL("DROP INDEX IF EXISTS raw_contact_sort_key2_index"); 1476 db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" + 1477 RawContacts.SORT_KEY_ALTERNATIVE + 1478 ");"); 1479 } 1480 1481 private void createContactsViews(SQLiteDatabase db) { 1482 db.execSQL("DROP VIEW IF EXISTS " + Views.CONTACTS + ";"); 1483 db.execSQL("DROP VIEW IF EXISTS " + Views.DATA + ";"); 1484 db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_CONTACTS + ";"); 1485 db.execSQL("DROP VIEW IF EXISTS " + Views.RAW_ENTITIES + ";"); 1486 db.execSQL("DROP VIEW IF EXISTS " + Views.ENTITIES + ";"); 1487 db.execSQL("DROP VIEW IF EXISTS " + Views.DATA_USAGE_STAT + ";"); 1488 db.execSQL("DROP VIEW IF EXISTS " + Views.STREAM_ITEMS + ";"); 1489 1490 String dataColumns = 1491 Data.IS_PRIMARY + ", " 1492 + Data.IS_SUPER_PRIMARY + ", " 1493 + Data.DATA_VERSION + ", " 1494 + DataColumns.CONCRETE_PACKAGE_ID + "," 1495 + PackagesColumns.PACKAGE + " AS " + Data.RES_PACKAGE + "," 1496 + DataColumns.CONCRETE_MIMETYPE_ID + "," 1497 + MimetypesColumns.MIMETYPE + " AS " + Data.MIMETYPE + ", " 1498 + Data.IS_READ_ONLY + ", " 1499 + Data.DATA1 + ", " 1500 + Data.DATA2 + ", " 1501 + Data.DATA3 + ", " 1502 + Data.DATA4 + ", " 1503 + Data.DATA5 + ", " 1504 + Data.DATA6 + ", " 1505 + Data.DATA7 + ", " 1506 + Data.DATA8 + ", " 1507 + Data.DATA9 + ", " 1508 + Data.DATA10 + ", " 1509 + Data.DATA11 + ", " 1510 + Data.DATA12 + ", " 1511 + Data.DATA13 + ", " 1512 + Data.DATA14 + ", " 1513 + Data.DATA15 + ", " 1514 + Data.SYNC1 + ", " 1515 + Data.SYNC2 + ", " 1516 + Data.SYNC3 + ", " 1517 + Data.SYNC4; 1518 1519 String syncColumns = 1520 RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AS " + RawContacts.ACCOUNT_NAME + "," 1521 + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AS " + RawContacts.ACCOUNT_TYPE + "," 1522 + RawContactsColumns.CONCRETE_DATA_SET + " AS " + RawContacts.DATA_SET + "," 1523 + "(CASE WHEN " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL THEN " 1524 + RawContactsColumns.CONCRETE_ACCOUNT_TYPE 1525 + " ELSE " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + "||'/'||" 1526 + RawContactsColumns.CONCRETE_DATA_SET + " END) AS " 1527 + RawContacts.ACCOUNT_TYPE_AND_DATA_SET + "," 1528 + RawContactsColumns.CONCRETE_SOURCE_ID + " AS " + RawContacts.SOURCE_ID + "," 1529 + RawContactsColumns.CONCRETE_NAME_VERIFIED + " AS " 1530 + RawContacts.NAME_VERIFIED + "," 1531 + RawContactsColumns.CONCRETE_VERSION + " AS " + RawContacts.VERSION + "," 1532 + RawContactsColumns.CONCRETE_DIRTY + " AS " + RawContacts.DIRTY + "," 1533 + RawContactsColumns.CONCRETE_SYNC1 + " AS " + RawContacts.SYNC1 + "," 1534 + RawContactsColumns.CONCRETE_SYNC2 + " AS " + RawContacts.SYNC2 + "," 1535 + RawContactsColumns.CONCRETE_SYNC3 + " AS " + RawContacts.SYNC3 + "," 1536 + RawContactsColumns.CONCRETE_SYNC4 + " AS " + RawContacts.SYNC4; 1537 1538 String baseContactColumns = 1539 Contacts.HAS_PHONE_NUMBER + ", " 1540 + Contacts.NAME_RAW_CONTACT_ID + ", " 1541 + Contacts.LOOKUP_KEY + ", " 1542 + Contacts.PHOTO_ID + ", " 1543 + Contacts.PHOTO_FILE_ID + ", " 1544 + "CAST(" + Clauses.CONTACT_VISIBLE + " AS INTEGER) AS " 1545 + Contacts.IN_VISIBLE_GROUP + ", " 1546 + ContactsColumns.LAST_STATUS_UPDATE_ID; 1547 1548 String contactOptionColumns = 1549 ContactsColumns.CONCRETE_CUSTOM_RINGTONE 1550 + " AS " + RawContacts.CUSTOM_RINGTONE + "," 1551 + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL 1552 + " AS " + RawContacts.SEND_TO_VOICEMAIL + "," 1553 + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED 1554 + " AS " + RawContacts.LAST_TIME_CONTACTED + "," 1555 + ContactsColumns.CONCRETE_TIMES_CONTACTED 1556 + " AS " + RawContacts.TIMES_CONTACTED + "," 1557 + ContactsColumns.CONCRETE_STARRED 1558 + " AS " + RawContacts.STARRED; 1559 1560 String contactNameColumns = 1561 "name_raw_contact." + RawContacts.DISPLAY_NAME_SOURCE 1562 + " AS " + Contacts.DISPLAY_NAME_SOURCE + ", " 1563 + "name_raw_contact." + RawContacts.DISPLAY_NAME_PRIMARY 1564 + " AS " + Contacts.DISPLAY_NAME_PRIMARY + ", " 1565 + "name_raw_contact." + RawContacts.DISPLAY_NAME_ALTERNATIVE 1566 + " AS " + Contacts.DISPLAY_NAME_ALTERNATIVE + ", " 1567 + "name_raw_contact." + RawContacts.PHONETIC_NAME 1568 + " AS " + Contacts.PHONETIC_NAME + ", " 1569 + "name_raw_contact." + RawContacts.PHONETIC_NAME_STYLE 1570 + " AS " + Contacts.PHONETIC_NAME_STYLE + ", " 1571 + "name_raw_contact." + RawContacts.SORT_KEY_PRIMARY 1572 + " AS " + Contacts.SORT_KEY_PRIMARY + ", " 1573 + "name_raw_contact." + RawContacts.SORT_KEY_ALTERNATIVE 1574 + " AS " + Contacts.SORT_KEY_ALTERNATIVE; 1575 1576 String dataSelect = "SELECT " 1577 + DataColumns.CONCRETE_ID + " AS " + Data._ID + "," 1578 + Data.RAW_CONTACT_ID + ", " 1579 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", " 1580 + syncColumns + ", " 1581 + dataColumns + ", " 1582 + contactOptionColumns + ", " 1583 + contactNameColumns + ", " 1584 + baseContactColumns + ", " 1585 + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 1586 Contacts.PHOTO_URI) + ", " 1587 + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 1588 Contacts.PHOTO_THUMBNAIL_URI) + ", " 1589 + dbForProfile() + " AS " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", " 1590 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID 1591 + " FROM " + Tables.DATA 1592 + " JOIN " + Tables.MIMETYPES + " ON (" 1593 + DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")" 1594 + " JOIN " + Tables.RAW_CONTACTS + " ON (" 1595 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")" 1596 + " JOIN " + Tables.CONTACTS + " ON (" 1597 + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")" 1598 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON(" 1599 + Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")" 1600 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON (" 1601 + DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")" 1602 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON (" 1603 + MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE 1604 + "' AND " + GroupsColumns.CONCRETE_ID + "=" 1605 + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")"; 1606 1607 db.execSQL("CREATE VIEW " + Views.DATA + " AS " + dataSelect); 1608 1609 String rawContactOptionColumns = 1610 RawContacts.CUSTOM_RINGTONE + "," 1611 + RawContacts.SEND_TO_VOICEMAIL + "," 1612 + RawContacts.LAST_TIME_CONTACTED + "," 1613 + RawContacts.TIMES_CONTACTED + "," 1614 + RawContacts.STARRED; 1615 1616 String rawContactsSelect = "SELECT " 1617 + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + "," 1618 + RawContacts.CONTACT_ID + ", " 1619 + RawContacts.AGGREGATION_MODE + ", " 1620 + RawContacts.RAW_CONTACT_IS_READ_ONLY + ", " 1621 + RawContacts.DELETED + ", " 1622 + RawContacts.DISPLAY_NAME_SOURCE + ", " 1623 + RawContacts.DISPLAY_NAME_PRIMARY + ", " 1624 + RawContacts.DISPLAY_NAME_ALTERNATIVE + ", " 1625 + RawContacts.PHONETIC_NAME + ", " 1626 + RawContacts.PHONETIC_NAME_STYLE + ", " 1627 + RawContacts.SORT_KEY_PRIMARY + ", " 1628 + RawContacts.SORT_KEY_ALTERNATIVE + ", " 1629 + dbForProfile() + " AS " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + ", " 1630 + rawContactOptionColumns + ", " 1631 + syncColumns 1632 + " FROM " + Tables.RAW_CONTACTS; 1633 1634 db.execSQL("CREATE VIEW " + Views.RAW_CONTACTS + " AS " + rawContactsSelect); 1635 1636 String contactsColumns = 1637 ContactsColumns.CONCRETE_CUSTOM_RINGTONE 1638 + " AS " + Contacts.CUSTOM_RINGTONE + ", " 1639 + contactNameColumns + ", " 1640 + baseContactColumns + ", " 1641 + ContactsColumns.CONCRETE_LAST_TIME_CONTACTED 1642 + " AS " + Contacts.LAST_TIME_CONTACTED + ", " 1643 + ContactsColumns.CONCRETE_SEND_TO_VOICEMAIL 1644 + " AS " + Contacts.SEND_TO_VOICEMAIL + ", " 1645 + ContactsColumns.CONCRETE_STARRED 1646 + " AS " + Contacts.STARRED + ", " 1647 + ContactsColumns.CONCRETE_TIMES_CONTACTED 1648 + " AS " + Contacts.TIMES_CONTACTED; 1649 1650 String contactsSelect = "SELECT " 1651 + ContactsColumns.CONCRETE_ID + " AS " + Contacts._ID + "," 1652 + contactsColumns + ", " 1653 + buildDisplayPhotoUriAlias(ContactsColumns.CONCRETE_ID, Contacts.PHOTO_URI) + ", " 1654 + buildThumbnailPhotoUriAlias(ContactsColumns.CONCRETE_ID, 1655 Contacts.PHOTO_THUMBNAIL_URI) + ", " 1656 + dbForProfile() + " AS " + Contacts.IS_USER_PROFILE 1657 + " FROM " + Tables.CONTACTS 1658 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON(" 1659 + Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")"; 1660 1661 db.execSQL("CREATE VIEW " + Views.CONTACTS + " AS " + contactsSelect); 1662 1663 String rawEntitiesSelect = "SELECT " 1664 + RawContacts.CONTACT_ID + ", " 1665 + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + "," 1666 + dataColumns + ", " 1667 + syncColumns + ", " 1668 + Data.SYNC1 + ", " 1669 + Data.SYNC2 + ", " 1670 + Data.SYNC3 + ", " 1671 + Data.SYNC4 + ", " 1672 + RawContactsColumns.CONCRETE_ID + " AS " + RawContacts._ID + ", " 1673 + DataColumns.CONCRETE_ID + " AS " + RawContacts.Entity.DATA_ID + "," 1674 + RawContactsColumns.CONCRETE_STARRED + " AS " + RawContacts.STARRED + "," 1675 + dbForProfile() + " AS " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "," 1676 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID 1677 + " FROM " + Tables.RAW_CONTACTS 1678 + " LEFT OUTER JOIN " + Tables.DATA + " ON (" 1679 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")" 1680 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON (" 1681 + DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")" 1682 + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON (" 1683 + DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")" 1684 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON (" 1685 + MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE 1686 + "' AND " + GroupsColumns.CONCRETE_ID + "=" 1687 + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")"; 1688 1689 db.execSQL("CREATE VIEW " + Views.RAW_ENTITIES + " AS " 1690 + rawEntitiesSelect); 1691 1692 String entitiesSelect = "SELECT " 1693 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + Contacts._ID + ", " 1694 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", " 1695 + RawContactsColumns.CONCRETE_DELETED + " AS " + RawContacts.DELETED + "," 1696 + dataColumns + ", " 1697 + syncColumns + ", " 1698 + contactsColumns + ", " 1699 + buildDisplayPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 1700 Contacts.PHOTO_URI) + ", " 1701 + buildThumbnailPhotoUriAlias(RawContactsColumns.CONCRETE_CONTACT_ID, 1702 Contacts.PHOTO_THUMBNAIL_URI) + ", " 1703 + dbForProfile() + " AS " + Contacts.IS_USER_PROFILE + ", " 1704 + Data.SYNC1 + ", " 1705 + Data.SYNC2 + ", " 1706 + Data.SYNC3 + ", " 1707 + Data.SYNC4 + ", " 1708 + RawContactsColumns.CONCRETE_ID + " AS " + Contacts.Entity.RAW_CONTACT_ID + ", " 1709 + DataColumns.CONCRETE_ID + " AS " + Contacts.Entity.DATA_ID + "," 1710 + Tables.GROUPS + "." + Groups.SOURCE_ID + " AS " + GroupMembership.GROUP_SOURCE_ID 1711 + " FROM " + Tables.RAW_CONTACTS 1712 + " JOIN " + Tables.CONTACTS + " ON (" 1713 + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")" 1714 + " JOIN " + Tables.RAW_CONTACTS + " AS name_raw_contact ON(" 1715 + Contacts.NAME_RAW_CONTACT_ID + "=name_raw_contact." + RawContacts._ID + ")" 1716 + " LEFT OUTER JOIN " + Tables.DATA + " ON (" 1717 + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")" 1718 + " LEFT OUTER JOIN " + Tables.PACKAGES + " ON (" 1719 + DataColumns.CONCRETE_PACKAGE_ID + "=" + PackagesColumns.CONCRETE_ID + ")" 1720 + " LEFT OUTER JOIN " + Tables.MIMETYPES + " ON (" 1721 + DataColumns.CONCRETE_MIMETYPE_ID + "=" + MimetypesColumns.CONCRETE_ID + ")" 1722 + " LEFT OUTER JOIN " + Tables.GROUPS + " ON (" 1723 + MimetypesColumns.CONCRETE_MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE 1724 + "' AND " + GroupsColumns.CONCRETE_ID + "=" 1725 + Tables.DATA + "." + GroupMembership.GROUP_ROW_ID + ")"; 1726 1727 db.execSQL("CREATE VIEW " + Views.ENTITIES + " AS " 1728 + entitiesSelect); 1729 1730 String dataUsageStatSelect = "SELECT " 1731 + DataUsageStatColumns.CONCRETE_ID + " AS " + DataUsageStatColumns._ID + ", " 1732 + DataUsageStatColumns.DATA_ID + ", " 1733 + RawContactsColumns.CONCRETE_CONTACT_ID + " AS " + RawContacts.CONTACT_ID + ", " 1734 + MimetypesColumns.CONCRETE_MIMETYPE + " AS " + Data.MIMETYPE + ", " 1735 + DataUsageStatColumns.USAGE_TYPE_INT + ", " 1736 + DataUsageStatColumns.TIMES_USED + ", " 1737 + DataUsageStatColumns.LAST_TIME_USED 1738 + " FROM " + Tables.DATA_USAGE_STAT 1739 + " JOIN " + Tables.DATA + " ON (" 1740 + DataColumns.CONCRETE_ID + "=" + DataUsageStatColumns.CONCRETE_DATA_ID + ")" 1741 + " JOIN " + Tables.RAW_CONTACTS + " ON (" 1742 + RawContactsColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_RAW_CONTACT_ID 1743 + " )" 1744 + " JOIN " + Tables.MIMETYPES + " ON (" 1745 + MimetypesColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_MIMETYPE_ID + ")"; 1746 1747 db.execSQL("CREATE VIEW " + Views.DATA_USAGE_STAT + " AS " + dataUsageStatSelect); 1748 1749 String streamItemSelect = "SELECT " + 1750 StreamItemsColumns.CONCRETE_ID + ", " + 1751 ContactsColumns.CONCRETE_ID + " AS " + StreamItems.CONTACT_ID + ", " + 1752 ContactsColumns.CONCRETE_LOOKUP_KEY + 1753 " AS " + StreamItems.CONTACT_LOOKUP_KEY + ", " + 1754 RawContactsColumns.CONCRETE_ACCOUNT_NAME + ", " + 1755 RawContactsColumns.CONCRETE_ACCOUNT_TYPE + ", " + 1756 RawContactsColumns.CONCRETE_DATA_SET + ", " + 1757 StreamItemsColumns.CONCRETE_RAW_CONTACT_ID + 1758 " as " + StreamItems.RAW_CONTACT_ID + ", " + 1759 RawContactsColumns.CONCRETE_SOURCE_ID + 1760 " as " + StreamItems.RAW_CONTACT_SOURCE_ID + ", " + 1761 StreamItemsColumns.CONCRETE_PACKAGE + ", " + 1762 StreamItemsColumns.CONCRETE_ICON + ", " + 1763 StreamItemsColumns.CONCRETE_LABEL + ", " + 1764 StreamItemsColumns.CONCRETE_TEXT + ", " + 1765 StreamItemsColumns.CONCRETE_TIMESTAMP + ", " + 1766 StreamItemsColumns.CONCRETE_COMMENTS + ", " + 1767 StreamItemsColumns.CONCRETE_SYNC1 + ", " + 1768 StreamItemsColumns.CONCRETE_SYNC2 + ", " + 1769 StreamItemsColumns.CONCRETE_SYNC3 + ", " + 1770 StreamItemsColumns.CONCRETE_SYNC4 + 1771 " FROM " + Tables.STREAM_ITEMS 1772 + " JOIN " + Tables.RAW_CONTACTS + " ON (" 1773 + StreamItemsColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID 1774 + ") JOIN " + Tables.CONTACTS + " ON (" 1775 + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"; 1776 1777 db.execSQL("CREATE VIEW " + Views.STREAM_ITEMS + " AS " + streamItemSelect); 1778 } 1779 1780 private static String buildDisplayPhotoUriAlias(String contactIdColumn, String alias) { 1781 return "(CASE WHEN " + Contacts.PHOTO_FILE_ID + " IS NULL THEN (CASE WHEN " 1782 + Contacts.PHOTO_ID + " IS NULL" 1783 + " OR " + Contacts.PHOTO_ID + "=0" 1784 + " THEN NULL" 1785 + " ELSE '" + Contacts.CONTENT_URI + "/'||" 1786 + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'" 1787 + " END) ELSE '" + DisplayPhoto.CONTENT_URI + "/'||" 1788 + Contacts.PHOTO_FILE_ID + " END)" 1789 + " AS " + alias; 1790 } 1791 1792 private static String buildThumbnailPhotoUriAlias(String contactIdColumn, String alias) { 1793 return "(CASE WHEN " 1794 + Contacts.PHOTO_ID + " IS NULL" 1795 + " OR " + Contacts.PHOTO_ID + "=0" 1796 + " THEN NULL" 1797 + " ELSE '" + Contacts.CONTENT_URI + "/'||" 1798 + contactIdColumn + "|| '/" + Photo.CONTENT_DIRECTORY + "'" 1799 + " END)" 1800 + " AS " + alias; 1801 } 1802 1803 /** 1804 * Returns the value to be returned when querying the column indicating that the contact 1805 * or raw contact belongs to the user's personal profile. Overridden in the profile 1806 * DB helper subclass. 1807 */ 1808 protected int dbForProfile() { 1809 return 0; 1810 } 1811 1812 private void createGroupsView(SQLiteDatabase db) { 1813 db.execSQL("DROP VIEW IF EXISTS " + Views.GROUPS + ";"); 1814 String groupsColumns = 1815 Groups.ACCOUNT_NAME + "," 1816 + Groups.ACCOUNT_TYPE + "," 1817 + Groups.DATA_SET + "," 1818 + "(CASE WHEN " + Groups.DATA_SET + " IS NULL THEN " + Groups.ACCOUNT_TYPE 1819 + " ELSE " + Groups.ACCOUNT_TYPE + "||" + Groups.DATA_SET + " END) AS " 1820 + Groups.ACCOUNT_TYPE_AND_DATA_SET + "," 1821 + Groups.SOURCE_ID + "," 1822 + Groups.VERSION + "," 1823 + Groups.DIRTY + "," 1824 + Groups.TITLE + "," 1825 + Groups.TITLE_RES + "," 1826 + Groups.NOTES + "," 1827 + Groups.SYSTEM_ID + "," 1828 + Groups.DELETED + "," 1829 + Groups.GROUP_VISIBLE + "," 1830 + Groups.SHOULD_SYNC + "," 1831 + Groups.AUTO_ADD + "," 1832 + Groups.FAVORITES + "," 1833 + Groups.GROUP_IS_READ_ONLY + "," 1834 + Groups.SYNC1 + "," 1835 + Groups.SYNC2 + "," 1836 + Groups.SYNC3 + "," 1837 + Groups.SYNC4 + "," 1838 + PackagesColumns.PACKAGE + " AS " + Groups.RES_PACKAGE; 1839 1840 String groupsSelect = "SELECT " 1841 + GroupsColumns.CONCRETE_ID + " AS " + Groups._ID + "," 1842 + groupsColumns 1843 + " FROM " + Tables.GROUPS_JOIN_PACKAGES; 1844 1845 db.execSQL("CREATE VIEW " + Views.GROUPS + " AS " + groupsSelect); 1846 } 1847 1848 @Override 1849 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 1850 if (oldVersion < 99) { 1851 Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion 1852 + ", data will be lost!"); 1853 1854 db.execSQL("DROP TABLE IF EXISTS " + Tables.CONTACTS + ";"); 1855 db.execSQL("DROP TABLE IF EXISTS " + Tables.RAW_CONTACTS + ";"); 1856 db.execSQL("DROP TABLE IF EXISTS " + Tables.PACKAGES + ";"); 1857 db.execSQL("DROP TABLE IF EXISTS " + Tables.MIMETYPES + ";"); 1858 db.execSQL("DROP TABLE IF EXISTS " + Tables.DATA + ";"); 1859 db.execSQL("DROP TABLE IF EXISTS " + Tables.PHONE_LOOKUP + ";"); 1860 db.execSQL("DROP TABLE IF EXISTS " + Tables.NAME_LOOKUP + ";"); 1861 db.execSQL("DROP TABLE IF EXISTS " + Tables.NICKNAME_LOOKUP + ";"); 1862 db.execSQL("DROP TABLE IF EXISTS " + Tables.GROUPS + ";"); 1863 db.execSQL("DROP TABLE IF EXISTS " + Tables.ACTIVITIES + ";"); 1864 db.execSQL("DROP TABLE IF EXISTS " + Tables.CALLS + ";"); 1865 db.execSQL("DROP TABLE IF EXISTS " + Tables.SETTINGS + ";"); 1866 db.execSQL("DROP TABLE IF EXISTS " + Tables.STATUS_UPDATES + ";"); 1867 1868 // TODO: we should not be dropping agg_exceptions and contact_options. In case that 1869 // table's schema changes, we should try to preserve the data, because it was entered 1870 // by the user and has never been synched to the server. 1871 db.execSQL("DROP TABLE IF EXISTS " + Tables.AGGREGATION_EXCEPTIONS + ";"); 1872 1873 onCreate(db); 1874 return; 1875 } 1876 1877 Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion); 1878 1879 boolean upgradeViewsAndTriggers = false; 1880 boolean upgradeNameLookup = false; 1881 boolean upgradeLegacyApiSupport = false; 1882 boolean upgradeSearchIndex = false; 1883 1884 if (oldVersion == 99) { 1885 upgradeViewsAndTriggers = true; 1886 oldVersion++; 1887 } 1888 1889 if (oldVersion == 100) { 1890 db.execSQL("CREATE INDEX IF NOT EXISTS mimetypes_mimetype_index ON " 1891 + Tables.MIMETYPES + " (" 1892 + MimetypesColumns.MIMETYPE + "," 1893 + MimetypesColumns._ID + ");"); 1894 updateIndexStats(db, Tables.MIMETYPES, 1895 "mimetypes_mimetype_index", "50 1 1"); 1896 1897 upgradeViewsAndTriggers = true; 1898 oldVersion++; 1899 } 1900 1901 if (oldVersion == 101) { 1902 upgradeViewsAndTriggers = true; 1903 oldVersion++; 1904 } 1905 1906 if (oldVersion == 102) { 1907 upgradeViewsAndTriggers = true; 1908 oldVersion++; 1909 } 1910 1911 if (oldVersion == 103) { 1912 upgradeViewsAndTriggers = true; 1913 oldVersion++; 1914 } 1915 1916 if (oldVersion == 104 || oldVersion == 201) { 1917 LegacyApiSupport.createSettingsTable(db); 1918 upgradeViewsAndTriggers = true; 1919 oldVersion++; 1920 } 1921 1922 if (oldVersion == 105) { 1923 upgradeToVersion202(db); 1924 upgradeNameLookup = true; 1925 oldVersion = 202; 1926 } 1927 1928 if (oldVersion == 202) { 1929 upgradeToVersion203(db); 1930 upgradeViewsAndTriggers = true; 1931 oldVersion++; 1932 } 1933 1934 if (oldVersion == 203) { 1935 upgradeViewsAndTriggers = true; 1936 oldVersion++; 1937 } 1938 1939 if (oldVersion == 204) { 1940 upgradeToVersion205(db); 1941 upgradeViewsAndTriggers = true; 1942 oldVersion++; 1943 } 1944 1945 if (oldVersion == 205) { 1946 upgrateToVersion206(db); 1947 upgradeViewsAndTriggers = true; 1948 oldVersion++; 1949 } 1950 1951 if (oldVersion == 206) { 1952 upgradeToVersion300(db); 1953 oldVersion = 300; 1954 } 1955 1956 if (oldVersion == 300) { 1957 upgradeViewsAndTriggers = true; 1958 oldVersion = 301; 1959 } 1960 1961 if (oldVersion == 301) { 1962 upgradeViewsAndTriggers = true; 1963 oldVersion = 302; 1964 } 1965 1966 if (oldVersion == 302) { 1967 upgradeEmailToVersion303(db); 1968 upgradeNicknameToVersion303(db); 1969 oldVersion = 303; 1970 } 1971 1972 if (oldVersion == 303) { 1973 upgradeToVersion304(db); 1974 oldVersion = 304; 1975 } 1976 1977 if (oldVersion == 304) { 1978 upgradeNameLookup = true; 1979 oldVersion = 305; 1980 } 1981 1982 if (oldVersion == 305) { 1983 upgradeToVersion306(db); 1984 oldVersion = 306; 1985 } 1986 1987 if (oldVersion == 306) { 1988 upgradeToVersion307(db); 1989 oldVersion = 307; 1990 } 1991 1992 if (oldVersion == 307) { 1993 upgradeToVersion308(db); 1994 oldVersion = 308; 1995 } 1996 1997 // Gingerbread upgrades 1998 if (oldVersion < 350) { 1999 upgradeViewsAndTriggers = true; 2000 oldVersion = 351; 2001 } 2002 2003 if (oldVersion == 351) { 2004 upgradeNameLookup = true; 2005 oldVersion = 352; 2006 } 2007 2008 if (oldVersion == 352) { 2009 upgradeToVersion353(db); 2010 oldVersion = 353; 2011 } 2012 2013 // Honeycomb upgrades 2014 if (oldVersion < 400) { 2015 upgradeViewsAndTriggers = true; 2016 upgradeToVersion400(db); 2017 oldVersion = 400; 2018 } 2019 2020 if (oldVersion == 400) { 2021 upgradeViewsAndTriggers = true; 2022 upgradeToVersion401(db); 2023 oldVersion = 401; 2024 } 2025 2026 if (oldVersion == 401) { 2027 upgradeToVersion402(db); 2028 oldVersion = 402; 2029 } 2030 2031 if (oldVersion == 402) { 2032 upgradeViewsAndTriggers = true; 2033 upgradeToVersion403(db); 2034 oldVersion = 403; 2035 } 2036 2037 if (oldVersion == 403) { 2038 upgradeViewsAndTriggers = true; 2039 oldVersion = 404; 2040 } 2041 2042 if (oldVersion == 404) { 2043 upgradeViewsAndTriggers = true; 2044 upgradeToVersion405(db); 2045 oldVersion = 405; 2046 } 2047 2048 if (oldVersion == 405) { 2049 upgradeViewsAndTriggers = true; 2050 upgradeToVersion406(db); 2051 oldVersion = 406; 2052 } 2053 2054 if (oldVersion == 406) { 2055 upgradeViewsAndTriggers = true; 2056 oldVersion = 407; 2057 } 2058 2059 if (oldVersion == 407) { 2060 // Obsolete 2061 oldVersion = 408; 2062 } 2063 2064 if (oldVersion == 408) { 2065 upgradeViewsAndTriggers = true; 2066 upgradeToVersion409(db); 2067 oldVersion = 409; 2068 } 2069 2070 if (oldVersion == 409) { 2071 upgradeViewsAndTriggers = true; 2072 oldVersion = 410; 2073 } 2074 2075 if (oldVersion == 410) { 2076 upgradeToVersion411(db); 2077 oldVersion = 411; 2078 } 2079 2080 if (oldVersion == 411) { 2081 // Same upgrade as 353, only on Honeycomb devices 2082 upgradeToVersion353(db); 2083 oldVersion = 412; 2084 } 2085 2086 if (oldVersion == 412) { 2087 upgradeToVersion413(db); 2088 oldVersion = 413; 2089 } 2090 2091 if (oldVersion == 413) { 2092 upgradeNameLookup = true; 2093 oldVersion = 414; 2094 } 2095 2096 if (oldVersion == 414) { 2097 upgradeToVersion415(db); 2098 upgradeViewsAndTriggers = true; 2099 oldVersion = 415; 2100 } 2101 2102 if (oldVersion == 415) { 2103 upgradeToVersion416(db); 2104 oldVersion = 416; 2105 } 2106 2107 if (oldVersion == 416) { 2108 upgradeLegacyApiSupport = true; 2109 oldVersion = 417; 2110 } 2111 2112 // Honeycomb-MR1 upgrades 2113 if (oldVersion < 500) { 2114 upgradeSearchIndex = true; 2115 } 2116 2117 if (oldVersion < 501) { 2118 upgradeSearchIndex = true; 2119 upgradeToVersion501(db); 2120 oldVersion = 501; 2121 } 2122 2123 if (oldVersion < 502) { 2124 upgradeSearchIndex = true; 2125 upgradeToVersion502(db); 2126 oldVersion = 502; 2127 } 2128 2129 if (oldVersion < 503) { 2130 upgradeSearchIndex = true; 2131 oldVersion = 503; 2132 } 2133 2134 if (oldVersion < 504) { 2135 upgradeToVersion504(db); 2136 oldVersion = 504; 2137 } 2138 2139 if (oldVersion < 600) { 2140 upgradeToVersion600(db); 2141 upgradeViewsAndTriggers = true; 2142 oldVersion = 600; 2143 } 2144 2145 if (oldVersion < 601) { 2146 upgradeToVersion601(db); 2147 oldVersion = 601; 2148 } 2149 2150 if (oldVersion < 602) { 2151 upgradeToVersion602(db); 2152 oldVersion = 602; 2153 } 2154 2155 if (oldVersion < 603) { 2156 upgradeViewsAndTriggers = true; 2157 oldVersion = 603; 2158 } 2159 2160 if (oldVersion < 604) { 2161 upgradeToVersion604(db); 2162 oldVersion = 604; 2163 } 2164 2165 if (oldVersion < 605) { 2166 upgradeViewsAndTriggers = true; 2167 upgradeToVersion605(db); 2168 oldVersion = 605; 2169 } 2170 2171 if (oldVersion < 606) { 2172 upgradeViewsAndTriggers = true; 2173 upgradeLegacyApiSupport = true; 2174 upgradeToVersion606(db); 2175 oldVersion = 606; 2176 } 2177 2178 if (oldVersion < 607) { 2179 upgradeViewsAndTriggers = true; 2180 upgradeToVersion607(db); 2181 oldVersion = 607; 2182 } 2183 2184 if (oldVersion < 608) { 2185 upgradeViewsAndTriggers = true; 2186 upgradeToVersion608(db); 2187 oldVersion = 608; 2188 } 2189 2190 if (oldVersion < 609) { 2191 upgradeToVersion609(db); 2192 oldVersion = 609; 2193 } 2194 2195 if (oldVersion < 610) { 2196 upgradeToVersion610(db); 2197 oldVersion = 610; 2198 } 2199 2200 if (oldVersion < 611) { 2201 upgradeViewsAndTriggers = true; 2202 upgradeToVersion611(db); 2203 oldVersion = 611; 2204 } 2205 2206 if (oldVersion < 612) { 2207 upgradeViewsAndTriggers = true; 2208 upgradeToVersion612(db); 2209 oldVersion = 612; 2210 } 2211 2212 if (oldVersion < 613) { 2213 upgradeToVersion613(db); 2214 oldVersion = 613; 2215 } 2216 2217 if (oldVersion < 614) { 2218 // this creates the view "view_stream_items" 2219 upgradeViewsAndTriggers = true; 2220 oldVersion = 614; 2221 } 2222 2223 if (oldVersion < 615) { 2224 upgradeToVersion615(db); 2225 oldVersion = 615; 2226 } 2227 2228 if (oldVersion < 616) { 2229 // this updates the "view_stream_items" view 2230 upgradeViewsAndTriggers = true; 2231 oldVersion = 616; 2232 } 2233 2234 if (oldVersion < 617) { 2235 // This version upgrade obsoleted the profile_raw_contact_id field of the Accounts 2236 // table, but we aren't removing the column because it is very little data (and not 2237 // referenced anymore). We do need to upgrade the views to handle the simplified 2238 // per-database "is profile" columns. 2239 upgradeViewsAndTriggers = true; 2240 oldVersion = 617; 2241 } 2242 2243 if (oldVersion < 618) { 2244 upgradeToVersion618(db); 2245 oldVersion = 618; 2246 } 2247 2248 if (oldVersion < 619) { 2249 upgradeViewsAndTriggers = true; 2250 oldVersion = 619; 2251 } 2252 2253 if (oldVersion < 620) { 2254 upgradeViewsAndTriggers = true; 2255 oldVersion = 620; 2256 } 2257 2258 if (upgradeViewsAndTriggers) { 2259 createContactsViews(db); 2260 createGroupsView(db); 2261 createContactsTriggers(db); 2262 createContactsIndexes(db); 2263 updateSqliteStats(db); 2264 upgradeLegacyApiSupport = true; 2265 mReopenDatabase = true; 2266 } 2267 2268 if (upgradeLegacyApiSupport) { 2269 LegacyApiSupport.createViews(db); 2270 } 2271 2272 if (upgradeNameLookup) { 2273 rebuildNameLookup(db); 2274 } 2275 2276 if (upgradeSearchIndex) { 2277 createSearchIndexTable(db); 2278 setProperty(db, SearchIndexManager.PROPERTY_SEARCH_INDEX_VERSION, "0"); 2279 } 2280 2281 if (oldVersion != newVersion) { 2282 throw new IllegalStateException( 2283 "error upgrading the database to version " + newVersion); 2284 } 2285 } 2286 2287 private void upgradeToVersion202(SQLiteDatabase db) { 2288 db.execSQL( 2289 "ALTER TABLE " + Tables.PHONE_LOOKUP + 2290 " ADD " + PhoneLookupColumns.MIN_MATCH + " TEXT;"); 2291 2292 db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" + 2293 PhoneLookupColumns.MIN_MATCH + "," + 2294 PhoneLookupColumns.RAW_CONTACT_ID + "," + 2295 PhoneLookupColumns.DATA_ID + 2296 ");"); 2297 2298 updateIndexStats(db, Tables.PHONE_LOOKUP, 2299 "phone_lookup_min_match_index", "10000 2 2 1"); 2300 2301 SQLiteStatement update = db.compileStatement( 2302 "UPDATE " + Tables.PHONE_LOOKUP + 2303 " SET " + PhoneLookupColumns.MIN_MATCH + "=?" + 2304 " WHERE " + PhoneLookupColumns.DATA_ID + "=?"); 2305 2306 // Populate the new column 2307 Cursor c = db.query(Tables.PHONE_LOOKUP + " JOIN " + Tables.DATA + 2308 " ON (" + PhoneLookupColumns.DATA_ID + "=" + DataColumns.CONCRETE_ID + ")", 2309 new String[]{Data._ID, Phone.NUMBER}, null, null, null, null, null); 2310 try { 2311 while (c.moveToNext()) { 2312 long dataId = c.getLong(0); 2313 String number = c.getString(1); 2314 if (!TextUtils.isEmpty(number)) { 2315 update.bindString(1, PhoneNumberUtils.toCallerIDMinMatch(number)); 2316 update.bindLong(2, dataId); 2317 update.execute(); 2318 } 2319 } 2320 } finally { 2321 c.close(); 2322 } 2323 } 2324 2325 private void upgradeToVersion203(SQLiteDatabase db) { 2326 // Garbage-collect first. A bug in Eclair was sometimes leaving 2327 // raw_contacts in the database that no longer had contacts associated 2328 // with them. To avoid failures during this database upgrade, drop 2329 // the orphaned raw_contacts. 2330 db.execSQL( 2331 "DELETE FROM raw_contacts" + 2332 " WHERE contact_id NOT NULL" + 2333 " AND contact_id NOT IN (SELECT _id FROM contacts)"); 2334 2335 db.execSQL( 2336 "ALTER TABLE " + Tables.CONTACTS + 2337 " ADD " + Contacts.NAME_RAW_CONTACT_ID + " INTEGER REFERENCES raw_contacts(_id)"); 2338 db.execSQL( 2339 "ALTER TABLE " + Tables.RAW_CONTACTS + 2340 " ADD contact_in_visible_group INTEGER NOT NULL DEFAULT 0"); 2341 2342 // For each Contact, find the RawContact that contributed the display name 2343 db.execSQL( 2344 "UPDATE " + Tables.CONTACTS + 2345 " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" + 2346 " SELECT " + RawContacts._ID + 2347 " FROM " + Tables.RAW_CONTACTS + 2348 " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + 2349 " AND " + RawContactsColumns.CONCRETE_DISPLAY_NAME + "=" + 2350 Tables.CONTACTS + "." + Contacts.DISPLAY_NAME + 2351 " ORDER BY " + RawContacts._ID + 2352 " LIMIT 1)" 2353 ); 2354 2355 db.execSQL("CREATE INDEX contacts_name_raw_contact_id_index ON " + Tables.CONTACTS + " (" + 2356 Contacts.NAME_RAW_CONTACT_ID + 2357 ");"); 2358 2359 // If for some unknown reason we missed some names, let's make sure there are 2360 // no contacts without a name, picking a raw contact "at random". 2361 db.execSQL( 2362 "UPDATE " + Tables.CONTACTS + 2363 " SET " + Contacts.NAME_RAW_CONTACT_ID + "=(" + 2364 " SELECT " + RawContacts._ID + 2365 " FROM " + Tables.RAW_CONTACTS + 2366 " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + 2367 " ORDER BY " + RawContacts._ID + 2368 " LIMIT 1)" + 2369 " WHERE " + Contacts.NAME_RAW_CONTACT_ID + " IS NULL" 2370 ); 2371 2372 // Wipe out DISPLAY_NAME on the Contacts table as it is no longer in use. 2373 db.execSQL( 2374 "UPDATE " + Tables.CONTACTS + 2375 " SET " + Contacts.DISPLAY_NAME + "=NULL" 2376 ); 2377 2378 // Copy the IN_VISIBLE_GROUP flag down to all raw contacts to allow 2379 // indexing on (display_name, in_visible_group) 2380 db.execSQL( 2381 "UPDATE " + Tables.RAW_CONTACTS + 2382 " SET contact_in_visible_group=(" + 2383 "SELECT " + Contacts.IN_VISIBLE_GROUP + 2384 " FROM " + Tables.CONTACTS + 2385 " WHERE " + Contacts._ID + "=" + RawContacts.CONTACT_ID + ")" + 2386 " WHERE " + RawContacts.CONTACT_ID + " NOT NULL" 2387 ); 2388 2389 db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" + 2390 "contact_in_visible_group" + "," + 2391 RawContactsColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC" + 2392 ");"); 2393 2394 db.execSQL("DROP INDEX contacts_visible_index"); 2395 db.execSQL("CREATE INDEX contacts_visible_index ON " + Tables.CONTACTS + " (" + 2396 Contacts.IN_VISIBLE_GROUP + 2397 ");"); 2398 } 2399 2400 private void upgradeToVersion205(SQLiteDatabase db) { 2401 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 2402 + " ADD " + RawContacts.DISPLAY_NAME_ALTERNATIVE + " TEXT;"); 2403 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 2404 + " ADD " + RawContacts.PHONETIC_NAME + " TEXT;"); 2405 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 2406 + " ADD " + RawContacts.PHONETIC_NAME_STYLE + " INTEGER;"); 2407 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 2408 + " ADD " + RawContacts.SORT_KEY_PRIMARY 2409 + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";"); 2410 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 2411 + " ADD " + RawContacts.SORT_KEY_ALTERNATIVE 2412 + " TEXT COLLATE " + ContactsProvider2.PHONEBOOK_COLLATOR_NAME + ";"); 2413 2414 final Locale locale = Locale.getDefault(); 2415 2416 NameSplitter splitter = createNameSplitter(); 2417 2418 SQLiteStatement rawContactUpdate = db.compileStatement( 2419 "UPDATE " + Tables.RAW_CONTACTS + 2420 " SET " + 2421 RawContacts.DISPLAY_NAME_PRIMARY + "=?," + 2422 RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," + 2423 RawContacts.PHONETIC_NAME + "=?," + 2424 RawContacts.PHONETIC_NAME_STYLE + "=?," + 2425 RawContacts.SORT_KEY_PRIMARY + "=?," + 2426 RawContacts.SORT_KEY_ALTERNATIVE + "=?" + 2427 " WHERE " + RawContacts._ID + "=?"); 2428 2429 upgradeStructuredNamesToVersion205(db, rawContactUpdate, splitter); 2430 upgradeOrganizationsToVersion205(db, rawContactUpdate, splitter); 2431 2432 db.execSQL("DROP INDEX raw_contact_sort_key1_index"); 2433 db.execSQL("CREATE INDEX raw_contact_sort_key1_index ON " + Tables.RAW_CONTACTS + " (" + 2434 "contact_in_visible_group" + "," + 2435 RawContacts.SORT_KEY_PRIMARY + 2436 ");"); 2437 2438 db.execSQL("CREATE INDEX raw_contact_sort_key2_index ON " + Tables.RAW_CONTACTS + " (" + 2439 "contact_in_visible_group" + "," + 2440 RawContacts.SORT_KEY_ALTERNATIVE + 2441 ");"); 2442 } 2443 2444 private interface StructName205Query { 2445 String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; 2446 2447 String COLUMNS[] = { 2448 DataColumns.CONCRETE_ID, 2449 Data.RAW_CONTACT_ID, 2450 RawContacts.DISPLAY_NAME_SOURCE, 2451 RawContacts.DISPLAY_NAME_PRIMARY, 2452 StructuredName.PREFIX, 2453 StructuredName.GIVEN_NAME, 2454 StructuredName.MIDDLE_NAME, 2455 StructuredName.FAMILY_NAME, 2456 StructuredName.SUFFIX, 2457 StructuredName.PHONETIC_FAMILY_NAME, 2458 StructuredName.PHONETIC_MIDDLE_NAME, 2459 StructuredName.PHONETIC_GIVEN_NAME, 2460 }; 2461 2462 int ID = 0; 2463 int RAW_CONTACT_ID = 1; 2464 int DISPLAY_NAME_SOURCE = 2; 2465 int DISPLAY_NAME = 3; 2466 int PREFIX = 4; 2467 int GIVEN_NAME = 5; 2468 int MIDDLE_NAME = 6; 2469 int FAMILY_NAME = 7; 2470 int SUFFIX = 8; 2471 int PHONETIC_FAMILY_NAME = 9; 2472 int PHONETIC_MIDDLE_NAME = 10; 2473 int PHONETIC_GIVEN_NAME = 11; 2474 } 2475 2476 private void upgradeStructuredNamesToVersion205(SQLiteDatabase db, 2477 SQLiteStatement rawContactUpdate, NameSplitter splitter) { 2478 2479 // Process structured names to detect the style of the full name and phonetic name 2480 2481 long mMimeType; 2482 try { 2483 mMimeType = DatabaseUtils.longForQuery(db, 2484 "SELECT " + MimetypesColumns._ID + 2485 " FROM " + Tables.MIMETYPES + 2486 " WHERE " + MimetypesColumns.MIMETYPE 2487 + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null); 2488 } catch (SQLiteDoneException e) { 2489 // No structured names in the database 2490 return; 2491 } 2492 2493 SQLiteStatement structuredNameUpdate = db.compileStatement( 2494 "UPDATE " + Tables.DATA + 2495 " SET " + 2496 StructuredName.FULL_NAME_STYLE + "=?," + 2497 StructuredName.DISPLAY_NAME + "=?," + 2498 StructuredName.PHONETIC_NAME_STYLE + "=?" + 2499 " WHERE " + Data._ID + "=?"); 2500 2501 NameSplitter.Name name = new NameSplitter.Name(); 2502 StringBuilder sb = new StringBuilder(); 2503 Cursor cursor = db.query(StructName205Query.TABLE, 2504 StructName205Query.COLUMNS, 2505 DataColumns.MIMETYPE_ID + "=" + mMimeType, null, null, null, null); 2506 try { 2507 while (cursor.moveToNext()) { 2508 long dataId = cursor.getLong(StructName205Query.ID); 2509 long rawContactId = cursor.getLong(StructName205Query.RAW_CONTACT_ID); 2510 int displayNameSource = cursor.getInt(StructName205Query.DISPLAY_NAME_SOURCE); 2511 String displayName = cursor.getString(StructName205Query.DISPLAY_NAME); 2512 2513 name.clear(); 2514 name.prefix = cursor.getString(StructName205Query.PREFIX); 2515 name.givenNames = cursor.getString(StructName205Query.GIVEN_NAME); 2516 name.middleName = cursor.getString(StructName205Query.MIDDLE_NAME); 2517 name.familyName = cursor.getString(StructName205Query.FAMILY_NAME); 2518 name.suffix = cursor.getString(StructName205Query.SUFFIX); 2519 name.phoneticFamilyName = cursor.getString(StructName205Query.PHONETIC_FAMILY_NAME); 2520 name.phoneticMiddleName = cursor.getString(StructName205Query.PHONETIC_MIDDLE_NAME); 2521 name.phoneticGivenName = cursor.getString(StructName205Query.PHONETIC_GIVEN_NAME); 2522 2523 upgradeNameToVersion205(dataId, rawContactId, displayNameSource, displayName, name, 2524 structuredNameUpdate, rawContactUpdate, splitter, sb); 2525 } 2526 } finally { 2527 cursor.close(); 2528 } 2529 } 2530 2531 private void upgradeNameToVersion205(long dataId, long rawContactId, int displayNameSource, 2532 String currentDisplayName, NameSplitter.Name name, 2533 SQLiteStatement structuredNameUpdate, SQLiteStatement rawContactUpdate, 2534 NameSplitter splitter, StringBuilder sb) { 2535 2536 splitter.guessNameStyle(name); 2537 int unadjustedFullNameStyle = name.fullNameStyle; 2538 name.fullNameStyle = splitter.getAdjustedFullNameStyle(name.fullNameStyle); 2539 String displayName = splitter.join(name, true, true); 2540 2541 // Don't update database with the adjusted fullNameStyle as it is locale 2542 // related 2543 structuredNameUpdate.bindLong(1, unadjustedFullNameStyle); 2544 DatabaseUtils.bindObjectToProgram(structuredNameUpdate, 2, displayName); 2545 structuredNameUpdate.bindLong(3, name.phoneticNameStyle); 2546 structuredNameUpdate.bindLong(4, dataId); 2547 structuredNameUpdate.execute(); 2548 2549 if (displayNameSource == DisplayNameSources.STRUCTURED_NAME) { 2550 String displayNameAlternative = splitter.join(name, false, false); 2551 String phoneticName = splitter.joinPhoneticName(name); 2552 String sortKey = null; 2553 String sortKeyAlternative = null; 2554 2555 if (phoneticName != null) { 2556 sortKey = sortKeyAlternative = phoneticName; 2557 } else if (name.fullNameStyle == FullNameStyle.CHINESE || 2558 name.fullNameStyle == FullNameStyle.CJK) { 2559 sortKey = sortKeyAlternative = ContactLocaleUtils.getIntance() 2560 .getSortKey(displayName, name.fullNameStyle); 2561 } 2562 2563 if (sortKey == null) { 2564 sortKey = displayName; 2565 sortKeyAlternative = displayNameAlternative; 2566 } 2567 2568 updateRawContact205(rawContactUpdate, rawContactId, displayName, 2569 displayNameAlternative, name.phoneticNameStyle, phoneticName, sortKey, 2570 sortKeyAlternative); 2571 } 2572 } 2573 2574 private interface Organization205Query { 2575 String TABLE = Tables.DATA_JOIN_RAW_CONTACTS; 2576 2577 String COLUMNS[] = { 2578 DataColumns.CONCRETE_ID, 2579 Data.RAW_CONTACT_ID, 2580 Organization.COMPANY, 2581 Organization.PHONETIC_NAME, 2582 }; 2583 2584 int ID = 0; 2585 int RAW_CONTACT_ID = 1; 2586 int COMPANY = 2; 2587 int PHONETIC_NAME = 3; 2588 } 2589 2590 private void upgradeOrganizationsToVersion205(SQLiteDatabase db, 2591 SQLiteStatement rawContactUpdate, NameSplitter splitter) { 2592 final long mimeType = lookupMimeTypeId(db, Organization.CONTENT_ITEM_TYPE); 2593 2594 SQLiteStatement organizationUpdate = db.compileStatement( 2595 "UPDATE " + Tables.DATA + 2596 " SET " + 2597 Organization.PHONETIC_NAME_STYLE + "=?" + 2598 " WHERE " + Data._ID + "=?"); 2599 2600 Cursor cursor = db.query(Organization205Query.TABLE, Organization205Query.COLUMNS, 2601 DataColumns.MIMETYPE_ID + "=" + mimeType + " AND " 2602 + RawContacts.DISPLAY_NAME_SOURCE + "=" + DisplayNameSources.ORGANIZATION, 2603 null, null, null, null); 2604 try { 2605 while (cursor.moveToNext()) { 2606 long dataId = cursor.getLong(Organization205Query.ID); 2607 long rawContactId = cursor.getLong(Organization205Query.RAW_CONTACT_ID); 2608 String company = cursor.getString(Organization205Query.COMPANY); 2609 String phoneticName = cursor.getString(Organization205Query.PHONETIC_NAME); 2610 2611 int phoneticNameStyle = splitter.guessPhoneticNameStyle(phoneticName); 2612 2613 organizationUpdate.bindLong(1, phoneticNameStyle); 2614 organizationUpdate.bindLong(2, dataId); 2615 organizationUpdate.execute(); 2616 2617 String sortKey = null; 2618 if (phoneticName == null && company != null) { 2619 int nameStyle = splitter.guessFullNameStyle(company); 2620 nameStyle = splitter.getAdjustedFullNameStyle(nameStyle); 2621 if (nameStyle == FullNameStyle.CHINESE || 2622 nameStyle == FullNameStyle.CJK ) { 2623 sortKey = ContactLocaleUtils.getIntance() 2624 .getSortKey(company, nameStyle); 2625 } 2626 } 2627 2628 if (sortKey == null) { 2629 sortKey = company; 2630 } 2631 2632 updateRawContact205(rawContactUpdate, rawContactId, company, 2633 company, phoneticNameStyle, phoneticName, sortKey, sortKey); 2634 } 2635 } finally { 2636 cursor.close(); 2637 } 2638 } 2639 2640 private void updateRawContact205(SQLiteStatement rawContactUpdate, long rawContactId, 2641 String displayName, String displayNameAlternative, int phoneticNameStyle, 2642 String phoneticName, String sortKeyPrimary, String sortKeyAlternative) { 2643 bindString(rawContactUpdate, 1, displayName); 2644 bindString(rawContactUpdate, 2, displayNameAlternative); 2645 bindString(rawContactUpdate, 3, phoneticName); 2646 rawContactUpdate.bindLong(4, phoneticNameStyle); 2647 bindString(rawContactUpdate, 5, sortKeyPrimary); 2648 bindString(rawContactUpdate, 6, sortKeyAlternative); 2649 rawContactUpdate.bindLong(7, rawContactId); 2650 rawContactUpdate.execute(); 2651 } 2652 2653 private void upgrateToVersion206(SQLiteDatabase db) { 2654 db.execSQL("ALTER TABLE " + Tables.RAW_CONTACTS 2655 + " ADD " + RawContacts.NAME_VERIFIED + " INTEGER NOT NULL DEFAULT 0;"); 2656 } 2657 2658 /** 2659 * Fix for the bug where name lookup records for organizations would get removed by 2660 * unrelated updates of the data rows. 2661 */ 2662 private void upgradeToVersion300(SQLiteDatabase db) { 2663 // No longer needed 2664 } 2665 2666 private static final class Upgrade303Query { 2667 public static final String TABLE = Tables.DATA; 2668 2669 public static final String SELECTION = 2670 DataColumns.MIMETYPE_ID + "=?" + 2671 " AND " + Data._ID + " NOT IN " + 2672 "(SELECT " + NameLookupColumns.DATA_ID + " FROM " + Tables.NAME_LOOKUP + ")" + 2673 " AND " + Data.DATA1 + " NOT NULL"; 2674 2675 public static final String COLUMNS[] = { 2676 Data._ID, 2677 Data.RAW_CONTACT_ID, 2678 Data.DATA1, 2679 }; 2680 2681 public static final int ID = 0; 2682 public static final int RAW_CONTACT_ID = 1; 2683 public static final int DATA1 = 2; 2684 } 2685 2686 /** 2687 * The {@link ContactsProvider2#update} method was deleting name lookup for new 2688 * emails during the sync. We need to restore the lost name lookup rows. 2689 */ 2690 private void upgradeEmailToVersion303(SQLiteDatabase db) { 2691 final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE); 2692 if (mimeTypeId == -1) { 2693 return; 2694 } 2695 2696 ContentValues values = new ContentValues(); 2697 2698 // Find all data rows with the mime type "email" that are missing name lookup 2699 Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS, 2700 Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 2701 null, null, null); 2702 try { 2703 while (cursor.moveToNext()) { 2704 long dataId = cursor.getLong(Upgrade303Query.ID); 2705 long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID); 2706 String value = cursor.getString(Upgrade303Query.DATA1); 2707 value = extractHandleFromEmailAddress(value); 2708 2709 if (value != null) { 2710 values.put(NameLookupColumns.DATA_ID, dataId); 2711 values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId); 2712 values.put(NameLookupColumns.NAME_TYPE, NameLookupType.EMAIL_BASED_NICKNAME); 2713 values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value)); 2714 db.insert(Tables.NAME_LOOKUP, null, values); 2715 } 2716 } 2717 } finally { 2718 cursor.close(); 2719 } 2720 } 2721 2722 /** 2723 * The {@link ContactsProvider2#update} method was deleting name lookup for new 2724 * nicknames during the sync. We need to restore the lost name lookup rows. 2725 */ 2726 private void upgradeNicknameToVersion303(SQLiteDatabase db) { 2727 final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE); 2728 if (mimeTypeId == -1) { 2729 return; 2730 } 2731 2732 ContentValues values = new ContentValues(); 2733 2734 // Find all data rows with the mime type "nickname" that are missing name lookup 2735 Cursor cursor = db.query(Upgrade303Query.TABLE, Upgrade303Query.COLUMNS, 2736 Upgrade303Query.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 2737 null, null, null); 2738 try { 2739 while (cursor.moveToNext()) { 2740 long dataId = cursor.getLong(Upgrade303Query.ID); 2741 long rawContactId = cursor.getLong(Upgrade303Query.RAW_CONTACT_ID); 2742 String value = cursor.getString(Upgrade303Query.DATA1); 2743 2744 values.put(NameLookupColumns.DATA_ID, dataId); 2745 values.put(NameLookupColumns.RAW_CONTACT_ID, rawContactId); 2746 values.put(NameLookupColumns.NAME_TYPE, NameLookupType.NICKNAME); 2747 values.put(NameLookupColumns.NORMALIZED_NAME, NameNormalizer.normalize(value)); 2748 db.insert(Tables.NAME_LOOKUP, null, values); 2749 } 2750 } finally { 2751 cursor.close(); 2752 } 2753 } 2754 2755 private void upgradeToVersion304(SQLiteDatabase db) { 2756 // Mimetype table requires an index on mime type 2757 db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS mime_type ON " + Tables.MIMETYPES + " (" + 2758 MimetypesColumns.MIMETYPE + 2759 ");"); 2760 } 2761 2762 private void upgradeToVersion306(SQLiteDatabase db) { 2763 // Fix invalid lookup that was used for Exchange contacts (it was not escaped) 2764 // It happened when a new contact was created AND synchronized 2765 final StringBuilder lookupKeyBuilder = new StringBuilder(); 2766 final SQLiteStatement updateStatement = db.compileStatement( 2767 "UPDATE contacts " + 2768 "SET lookup=? " + 2769 "WHERE _id=?"); 2770 final Cursor contactIdCursor = db.rawQuery( 2771 "SELECT DISTINCT contact_id " + 2772 "FROM raw_contacts " + 2773 "WHERE deleted=0 AND account_type='com.android.exchange'", 2774 null); 2775 try { 2776 while (contactIdCursor.moveToNext()) { 2777 final long contactId = contactIdCursor.getLong(0); 2778 lookupKeyBuilder.setLength(0); 2779 final Cursor c = db.rawQuery( 2780 "SELECT account_type, account_name, _id, sourceid, display_name " + 2781 "FROM raw_contacts " + 2782 "WHERE contact_id=? " + 2783 "ORDER BY _id", 2784 new String[] { String.valueOf(contactId) }); 2785 try { 2786 while (c.moveToNext()) { 2787 ContactLookupKey.appendToLookupKey(lookupKeyBuilder, 2788 c.getString(0), 2789 c.getString(1), 2790 c.getLong(2), 2791 c.getString(3), 2792 c.getString(4)); 2793 } 2794 } finally { 2795 c.close(); 2796 } 2797 2798 if (lookupKeyBuilder.length() == 0) { 2799 updateStatement.bindNull(1); 2800 } else { 2801 updateStatement.bindString(1, Uri.encode(lookupKeyBuilder.toString())); 2802 } 2803 updateStatement.bindLong(2, contactId); 2804 2805 updateStatement.execute(); 2806 } 2807 } finally { 2808 updateStatement.close(); 2809 contactIdCursor.close(); 2810 } 2811 } 2812 2813 private void upgradeToVersion307(SQLiteDatabase db) { 2814 db.execSQL("CREATE TABLE properties (" + 2815 "property_key TEXT PRIMARY_KEY, " + 2816 "property_value TEXT" + 2817 ");"); 2818 } 2819 2820 private void upgradeToVersion308(SQLiteDatabase db) { 2821 db.execSQL("CREATE TABLE accounts (" + 2822 "account_name TEXT, " + 2823 "account_type TEXT " + 2824 ");"); 2825 2826 db.execSQL("INSERT INTO accounts " + 2827 "SELECT DISTINCT account_name, account_type FROM raw_contacts"); 2828 } 2829 2830 private void upgradeToVersion400(SQLiteDatabase db) { 2831 db.execSQL("ALTER TABLE " + Tables.GROUPS 2832 + " ADD " + Groups.FAVORITES + " INTEGER NOT NULL DEFAULT 0;"); 2833 db.execSQL("ALTER TABLE " + Tables.GROUPS 2834 + " ADD " + Groups.AUTO_ADD + " INTEGER NOT NULL DEFAULT 0;"); 2835 } 2836 2837 private void upgradeToVersion353(SQLiteDatabase db) { 2838 db.execSQL("DELETE FROM contacts " + 2839 "WHERE NOT EXISTS (SELECT 1 FROM raw_contacts WHERE contact_id=contacts._id)"); 2840 } 2841 2842 private void rebuildNameLookup(SQLiteDatabase db) { 2843 db.execSQL("DROP INDEX IF EXISTS name_lookup_index"); 2844 insertNameLookup(db); 2845 createContactsIndexes(db); 2846 } 2847 2848 /** 2849 * Regenerates all locale-sensitive data: nickname_lookup, name_lookup and sort keys. 2850 */ 2851 public void setLocale(ContactsProvider2 provider, Locale locale) { 2852 Log.i(TAG, "Switching to locale " + locale); 2853 2854 long start = SystemClock.uptimeMillis(); 2855 SQLiteDatabase db = getWritableDatabase(); 2856 db.setLocale(locale); 2857 db.beginTransaction(); 2858 try { 2859 db.execSQL("DROP INDEX raw_contact_sort_key1_index"); 2860 db.execSQL("DROP INDEX raw_contact_sort_key2_index"); 2861 db.execSQL("DROP INDEX IF EXISTS name_lookup_index"); 2862 2863 loadNicknameLookupTable(db); 2864 insertNameLookup(db); 2865 rebuildSortKeys(db, provider); 2866 createContactsIndexes(db); 2867 db.setTransactionSuccessful(); 2868 } finally { 2869 db.endTransaction(); 2870 } 2871 2872 Log.i(TAG, "Locale change completed in " + (SystemClock.uptimeMillis() - start) + "ms"); 2873 } 2874 2875 /** 2876 * Regenerates sort keys for all contacts. 2877 */ 2878 private void rebuildSortKeys(SQLiteDatabase db, ContactsProvider2 provider) { 2879 Cursor cursor = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID}, 2880 null, null, null, null, null); 2881 try { 2882 while (cursor.moveToNext()) { 2883 long rawContactId = cursor.getLong(0); 2884 updateRawContactDisplayName(db, rawContactId); 2885 } 2886 } finally { 2887 cursor.close(); 2888 } 2889 } 2890 2891 private void insertNameLookup(SQLiteDatabase db) { 2892 db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP); 2893 2894 SQLiteStatement nameLookupInsert = db.compileStatement( 2895 "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "(" 2896 + NameLookupColumns.RAW_CONTACT_ID + "," 2897 + NameLookupColumns.DATA_ID + "," 2898 + NameLookupColumns.NAME_TYPE + "," 2899 + NameLookupColumns.NORMALIZED_NAME + 2900 ") VALUES (?,?,?,?)"); 2901 2902 try { 2903 insertStructuredNameLookup(db, nameLookupInsert); 2904 insertEmailLookup(db, nameLookupInsert); 2905 insertNicknameLookup(db, nameLookupInsert); 2906 } finally { 2907 nameLookupInsert.close(); 2908 } 2909 } 2910 2911 private static final class StructuredNameQuery { 2912 public static final String TABLE = Tables.DATA; 2913 2914 public static final String SELECTION = 2915 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; 2916 2917 public static final String COLUMNS[] = { 2918 StructuredName._ID, 2919 StructuredName.RAW_CONTACT_ID, 2920 StructuredName.DISPLAY_NAME, 2921 }; 2922 2923 public static final int ID = 0; 2924 public static final int RAW_CONTACT_ID = 1; 2925 public static final int DISPLAY_NAME = 2; 2926 } 2927 2928 private class StructuredNameLookupBuilder extends NameLookupBuilder { 2929 2930 private final SQLiteStatement mNameLookupInsert; 2931 private final CommonNicknameCache mCommonNicknameCache; 2932 2933 public StructuredNameLookupBuilder(NameSplitter splitter, 2934 CommonNicknameCache commonNicknameCache, SQLiteStatement nameLookupInsert) { 2935 super(splitter); 2936 this.mCommonNicknameCache = commonNicknameCache; 2937 this.mNameLookupInsert = nameLookupInsert; 2938 } 2939 2940 @Override 2941 protected void insertNameLookup(long rawContactId, long dataId, int lookupType, 2942 String name) { 2943 if (!TextUtils.isEmpty(name)) { 2944 ContactsDatabaseHelper.this.insertNormalizedNameLookup(mNameLookupInsert, 2945 rawContactId, dataId, lookupType, name); 2946 } 2947 } 2948 2949 @Override 2950 protected String[] getCommonNicknameClusters(String normalizedName) { 2951 return mCommonNicknameCache.getCommonNicknameClusters(normalizedName); 2952 } 2953 } 2954 2955 /** 2956 * Inserts name lookup rows for all structured names in the database. 2957 */ 2958 private void insertStructuredNameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) { 2959 NameSplitter nameSplitter = createNameSplitter(); 2960 NameLookupBuilder nameLookupBuilder = new StructuredNameLookupBuilder(nameSplitter, 2961 new CommonNicknameCache(db), nameLookupInsert); 2962 final long mimeTypeId = lookupMimeTypeId(db, StructuredName.CONTENT_ITEM_TYPE); 2963 Cursor cursor = db.query(StructuredNameQuery.TABLE, StructuredNameQuery.COLUMNS, 2964 StructuredNameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 2965 null, null, null); 2966 try { 2967 while (cursor.moveToNext()) { 2968 long dataId = cursor.getLong(StructuredNameQuery.ID); 2969 long rawContactId = cursor.getLong(StructuredNameQuery.RAW_CONTACT_ID); 2970 String name = cursor.getString(StructuredNameQuery.DISPLAY_NAME); 2971 int fullNameStyle = nameSplitter.guessFullNameStyle(name); 2972 fullNameStyle = nameSplitter.getAdjustedFullNameStyle(fullNameStyle); 2973 nameLookupBuilder.insertNameLookup(rawContactId, dataId, name, fullNameStyle); 2974 } 2975 } finally { 2976 cursor.close(); 2977 } 2978 } 2979 2980 private static final class OrganizationQuery { 2981 public static final String TABLE = Tables.DATA; 2982 2983 public static final String SELECTION = 2984 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; 2985 2986 public static final String COLUMNS[] = { 2987 Organization._ID, 2988 Organization.RAW_CONTACT_ID, 2989 Organization.COMPANY, 2990 Organization.TITLE, 2991 }; 2992 2993 public static final int ID = 0; 2994 public static final int RAW_CONTACT_ID = 1; 2995 public static final int COMPANY = 2; 2996 public static final int TITLE = 3; 2997 } 2998 2999 private static final class EmailQuery { 3000 public static final String TABLE = Tables.DATA; 3001 3002 public static final String SELECTION = 3003 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; 3004 3005 public static final String COLUMNS[] = { 3006 Email._ID, 3007 Email.RAW_CONTACT_ID, 3008 Email.ADDRESS, 3009 }; 3010 3011 public static final int ID = 0; 3012 public static final int RAW_CONTACT_ID = 1; 3013 public static final int ADDRESS = 2; 3014 } 3015 3016 /** 3017 * Inserts name lookup rows for all email addresses in the database. 3018 */ 3019 private void insertEmailLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) { 3020 final long mimeTypeId = lookupMimeTypeId(db, Email.CONTENT_ITEM_TYPE); 3021 Cursor cursor = db.query(EmailQuery.TABLE, EmailQuery.COLUMNS, 3022 EmailQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 3023 null, null, null); 3024 try { 3025 while (cursor.moveToNext()) { 3026 long dataId = cursor.getLong(EmailQuery.ID); 3027 long rawContactId = cursor.getLong(EmailQuery.RAW_CONTACT_ID); 3028 String address = cursor.getString(EmailQuery.ADDRESS); 3029 address = extractHandleFromEmailAddress(address); 3030 insertNameLookup(nameLookupInsert, rawContactId, dataId, 3031 NameLookupType.EMAIL_BASED_NICKNAME, address); 3032 } 3033 } finally { 3034 cursor.close(); 3035 } 3036 } 3037 3038 private static final class NicknameQuery { 3039 public static final String TABLE = Tables.DATA; 3040 3041 public static final String SELECTION = 3042 DataColumns.MIMETYPE_ID + "=? AND " + Data.DATA1 + " NOT NULL"; 3043 3044 public static final String COLUMNS[] = { 3045 Nickname._ID, 3046 Nickname.RAW_CONTACT_ID, 3047 Nickname.NAME, 3048 }; 3049 3050 public static final int ID = 0; 3051 public static final int RAW_CONTACT_ID = 1; 3052 public static final int NAME = 2; 3053 } 3054 3055 /** 3056 * Inserts name lookup rows for all nicknames in the database. 3057 */ 3058 private void insertNicknameLookup(SQLiteDatabase db, SQLiteStatement nameLookupInsert) { 3059 final long mimeTypeId = lookupMimeTypeId(db, Nickname.CONTENT_ITEM_TYPE); 3060 Cursor cursor = db.query(NicknameQuery.TABLE, NicknameQuery.COLUMNS, 3061 NicknameQuery.SELECTION, new String[] {String.valueOf(mimeTypeId)}, 3062 null, null, null); 3063 try { 3064 while (cursor.moveToNext()) { 3065 long dataId = cursor.getLong(NicknameQuery.ID); 3066 long rawContactId = cursor.getLong(NicknameQuery.RAW_CONTACT_ID); 3067 String nickname = cursor.getString(NicknameQuery.NAME); 3068 insertNameLookup(nameLookupInsert, rawContactId, dataId, 3069 NameLookupType.NICKNAME, nickname); 3070 } 3071 } finally { 3072 cursor.close(); 3073 } 3074 } 3075 3076 /** 3077 * Inserts a record in the {@link Tables#NAME_LOOKUP} table. 3078 */ 3079 public void insertNameLookup(SQLiteStatement stmt, long rawContactId, long dataId, 3080 int lookupType, String name) { 3081 if (TextUtils.isEmpty(name)) { 3082 return; 3083 } 3084 3085 String normalized = NameNormalizer.normalize(name); 3086 if (TextUtils.isEmpty(normalized)) { 3087 return; 3088 } 3089 3090 insertNormalizedNameLookup(stmt, rawContactId, dataId, lookupType, normalized); 3091 } 3092 3093 private void insertNormalizedNameLookup(SQLiteStatement stmt, long rawContactId, long dataId, 3094 int lookupType, String normalizedName) { 3095 stmt.bindLong(1, rawContactId); 3096 stmt.bindLong(2, dataId); 3097 stmt.bindLong(3, lookupType); 3098 stmt.bindString(4, normalizedName); 3099 stmt.executeInsert(); 3100 } 3101 3102 /** 3103 * Changing the VISIBLE bit from a field on both RawContacts and Contacts to a separate table. 3104 */ 3105 private void upgradeToVersion401(SQLiteDatabase db) { 3106 db.execSQL("CREATE TABLE " + Tables.VISIBLE_CONTACTS + " (" + 3107 Contacts._ID + " INTEGER PRIMARY KEY" + 3108 ");"); 3109 db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS + 3110 " SELECT " + Contacts._ID + 3111 " FROM " + Tables.CONTACTS + 3112 " WHERE " + Contacts.IN_VISIBLE_GROUP + "!=0"); 3113 db.execSQL("DROP INDEX contacts_visible_index"); 3114 } 3115 3116 /** 3117 * Introducing a new table: directories. 3118 */ 3119 private void upgradeToVersion402(SQLiteDatabase db) { 3120 createDirectoriesTable(db); 3121 } 3122 3123 private void upgradeToVersion403(SQLiteDatabase db) { 3124 db.execSQL("DROP TABLE IF EXISTS directories;"); 3125 createDirectoriesTable(db); 3126 3127 db.execSQL("ALTER TABLE raw_contacts" 3128 + " ADD raw_contact_is_read_only INTEGER NOT NULL DEFAULT 0;"); 3129 3130 db.execSQL("ALTER TABLE data" 3131 + " ADD is_read_only INTEGER NOT NULL DEFAULT 0;"); 3132 } 3133 3134 private void upgradeToVersion405(SQLiteDatabase db) { 3135 db.execSQL("DROP TABLE IF EXISTS phone_lookup;"); 3136 // Private phone numbers table used for lookup 3137 db.execSQL("CREATE TABLE " + Tables.PHONE_LOOKUP + " (" + 3138 PhoneLookupColumns.DATA_ID 3139 + " INTEGER REFERENCES data(_id) NOT NULL," + 3140 PhoneLookupColumns.RAW_CONTACT_ID 3141 + " INTEGER REFERENCES raw_contacts(_id) NOT NULL," + 3142 PhoneLookupColumns.NORMALIZED_NUMBER + " TEXT NOT NULL," + 3143 PhoneLookupColumns.MIN_MATCH + " TEXT NOT NULL" + 3144 ");"); 3145 3146 db.execSQL("CREATE INDEX phone_lookup_index ON " + Tables.PHONE_LOOKUP + " (" + 3147 PhoneLookupColumns.NORMALIZED_NUMBER + "," + 3148 PhoneLookupColumns.RAW_CONTACT_ID + "," + 3149 PhoneLookupColumns.DATA_ID + 3150 ");"); 3151 3152 db.execSQL("CREATE INDEX phone_lookup_min_match_index ON " + Tables.PHONE_LOOKUP + " (" + 3153 PhoneLookupColumns.MIN_MATCH + "," + 3154 PhoneLookupColumns.RAW_CONTACT_ID + "," + 3155 PhoneLookupColumns.DATA_ID + 3156 ");"); 3157 3158 final long mimeTypeId = lookupMimeTypeId(db, Phone.CONTENT_ITEM_TYPE); 3159 if (mimeTypeId == -1) { 3160 return; 3161 } 3162 3163 Cursor cursor = db.rawQuery( 3164 "SELECT _id, " + Phone.RAW_CONTACT_ID + ", " + Phone.NUMBER + 3165 " FROM " + Tables.DATA + 3166 " WHERE " + DataColumns.MIMETYPE_ID + "=" + mimeTypeId 3167 + " AND " + Phone.NUMBER + " NOT NULL", null); 3168 3169 ContentValues phoneValues = new ContentValues(); 3170 try { 3171 while (cursor.moveToNext()) { 3172 long dataID = cursor.getLong(0); 3173 long rawContactID = cursor.getLong(1); 3174 String number = cursor.getString(2); 3175 String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); 3176 if (!TextUtils.isEmpty(normalizedNumber)) { 3177 phoneValues.clear(); 3178 phoneValues.put(PhoneLookupColumns.RAW_CONTACT_ID, rawContactID); 3179 phoneValues.put(PhoneLookupColumns.DATA_ID, dataID); 3180 phoneValues.put(PhoneLookupColumns.NORMALIZED_NUMBER, normalizedNumber); 3181 phoneValues.put(PhoneLookupColumns.MIN_MATCH, 3182 PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber)); 3183 db.insert(Tables.PHONE_LOOKUP, null, phoneValues); 3184 } 3185 } 3186 } finally { 3187 cursor.close(); 3188 } 3189 } 3190 3191 private void upgradeToVersion406(SQLiteDatabase db) { 3192 db.execSQL("ALTER TABLE calls ADD countryiso TEXT;"); 3193 } 3194 3195 private void upgradeToVersion409(SQLiteDatabase db) { 3196 db.execSQL("DROP TABLE IF EXISTS directories;"); 3197 createDirectoriesTable(db); 3198 } 3199 3200 /** 3201 * Adding DEFAULT_DIRECTORY table. 3202 * DEFAULT_DIRECTORY should contain every contact which should be shown to users in default. 3203 * - if a contact doesn't belong to any account (local contact), it should be in 3204 * default_directory 3205 * - if a contact belongs to an account that doesn't have a "default" group, it should be in 3206 * default_directory 3207 * - if a contact belongs to an account that has a "default" group (like Google directory, 3208 * which has "My contacts" group as default), it should be in default_directory. 3209 * 3210 * This logic assumes that accounts with the "default" group should have at least one 3211 * group with AUTO_ADD (implying it is the default group) flag in the groups table. 3212 */ 3213 private void upgradeToVersion411(SQLiteDatabase db) { 3214 db.execSQL("DROP TABLE IF EXISTS " + Tables.DEFAULT_DIRECTORY); 3215 db.execSQL("CREATE TABLE default_directory (_id INTEGER PRIMARY KEY);"); 3216 3217 // Process contacts without an account 3218 db.execSQL("INSERT OR IGNORE INTO default_directory " + 3219 " SELECT contact_id " + 3220 " FROM raw_contacts " + 3221 " WHERE raw_contacts.account_name IS NULL " + 3222 " AND raw_contacts.account_type IS NULL "); 3223 3224 // Process accounts that don't have a default group (e.g. Exchange). 3225 db.execSQL("INSERT OR IGNORE INTO default_directory " + 3226 " SELECT contact_id " + 3227 " FROM raw_contacts " + 3228 " WHERE NOT EXISTS" + 3229 " (SELECT _id " + 3230 " FROM groups " + 3231 " WHERE raw_contacts.account_name = groups.account_name" + 3232 " AND raw_contacts.account_type = groups.account_type" + 3233 " AND groups.auto_add != 0)"); 3234 3235 final long mimetype = lookupMimeTypeId(db, GroupMembership.CONTENT_ITEM_TYPE); 3236 3237 // Process accounts that do have a default group (e.g. Google) 3238 db.execSQL("INSERT OR IGNORE INTO default_directory " + 3239 " SELECT contact_id " + 3240 " FROM raw_contacts " + 3241 " JOIN data " + 3242 " ON (raw_contacts._id=raw_contact_id)" + 3243 " WHERE mimetype_id=" + mimetype + 3244 " AND EXISTS" + 3245 " (SELECT _id" + 3246 " FROM groups" + 3247 " WHERE raw_contacts.account_name = groups.account_name" + 3248 " AND raw_contacts.account_type = groups.account_type" + 3249 " AND groups.auto_add != 0)"); 3250 } 3251 3252 private void upgradeToVersion413(SQLiteDatabase db) { 3253 db.execSQL("DROP TABLE IF EXISTS directories;"); 3254 createDirectoriesTable(db); 3255 } 3256 3257 private void upgradeToVersion415(SQLiteDatabase db) { 3258 db.execSQL( 3259 "ALTER TABLE " + Tables.GROUPS + 3260 " ADD " + Groups.GROUP_IS_READ_ONLY + " INTEGER NOT NULL DEFAULT 0"); 3261 db.execSQL( 3262 "UPDATE " + Tables.GROUPS + 3263 " SET " + Groups.GROUP_IS_READ_ONLY + "=1" + 3264 " WHERE " + Groups.SYSTEM_ID + " NOT NULL"); 3265 } 3266 3267 private void upgradeToVersion416(SQLiteDatabase db) { 3268 db.execSQL("CREATE INDEX phone_lookup_data_id_min_match_index ON " + Tables.PHONE_LOOKUP + 3269 " (" + PhoneLookupColumns.DATA_ID + ", " + PhoneLookupColumns.MIN_MATCH + ");"); 3270 } 3271 3272 private void upgradeToVersion501(SQLiteDatabase db) { 3273 // Remove organization rows from the name lookup, we now use search index for that 3274 db.execSQL("DELETE FROM name_lookup WHERE name_type=5"); 3275 } 3276 3277 private void upgradeToVersion502(SQLiteDatabase db) { 3278 // Remove Chinese and Korean name lookup - this data is now in the search index 3279 db.execSQL("DELETE FROM name_lookup WHERE name_type IN (6, 7)"); 3280 } 3281 3282 private void upgradeToVersion504(SQLiteDatabase db) { 3283 populateMimeTypeCache(db); 3284 3285 // Find all names with prefixes and recreate display name 3286 Cursor cursor = db.rawQuery( 3287 "SELECT " + StructuredName.RAW_CONTACT_ID + 3288 " FROM " + Tables.DATA + 3289 " WHERE " + DataColumns.MIMETYPE_ID + "=?" 3290 + " AND " + StructuredName.PREFIX + " NOT NULL", 3291 new String[]{ String.valueOf(mMimeTypeIdStructuredName) }); 3292 3293 try { 3294 while(cursor.moveToNext()) { 3295 long rawContactId = cursor.getLong(0); 3296 updateRawContactDisplayName(db, rawContactId); 3297 } 3298 3299 } finally { 3300 cursor.close(); 3301 } 3302 } 3303 3304 private void upgradeToVersion600(SQLiteDatabase db) { 3305 // This change used to add the profile raw contact ID to the Accounts table. That 3306 // column is no longer needed (as of version 614) since the profile records are stored in 3307 // a separate copy of the database for security reasons. So this change is now a no-op. 3308 } 3309 3310 private void upgradeToVersion601(SQLiteDatabase db) { 3311 db.execSQL("CREATE TABLE data_usage_stat(" + 3312 "stat_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3313 "data_id INTEGER NOT NULL, " + 3314 "usage_type INTEGER NOT NULL DEFAULT 0, " + 3315 "times_used INTEGER NOT NULL DEFAULT 0, " + 3316 "last_time_used INTERGER NOT NULL DEFAULT 0, " + 3317 "FOREIGN KEY(data_id) REFERENCES data(_id));"); 3318 db.execSQL("CREATE UNIQUE INDEX data_usage_stat_index ON " + 3319 "data_usage_stat (data_id, usage_type)"); 3320 } 3321 3322 private void upgradeToVersion602(SQLiteDatabase db) { 3323 db.execSQL("ALTER TABLE calls ADD voicemail_uri TEXT;"); 3324 db.execSQL("ALTER TABLE calls ADD _data TEXT;"); 3325 db.execSQL("ALTER TABLE calls ADD has_content INTEGER;"); 3326 db.execSQL("ALTER TABLE calls ADD mime_type TEXT;"); 3327 db.execSQL("ALTER TABLE calls ADD source_data TEXT;"); 3328 db.execSQL("ALTER TABLE calls ADD source_package TEXT;"); 3329 db.execSQL("ALTER TABLE calls ADD state INTEGER;"); 3330 } 3331 3332 private void upgradeToVersion604(SQLiteDatabase db) { 3333 db.execSQL("CREATE TABLE voicemail_status (" + 3334 "_id INTEGER PRIMARY KEY AUTOINCREMENT," + 3335 "source_package TEXT UNIQUE NOT NULL," + 3336 "settings_uri TEXT," + 3337 "voicemail_access_uri TEXT," + 3338 "configuration_state INTEGER," + 3339 "data_channel_state INTEGER," + 3340 "notification_channel_state INTEGER" + 3341 ");"); 3342 } 3343 3344 private void upgradeToVersion605(SQLiteDatabase db) { 3345 // This version used to create the stream item and stream item photos tables, but a newer 3346 // version of those tables is created in version 609 below. So omitting the creation in 3347 // this upgrade step to avoid a create->drop->create. 3348 } 3349 3350 private void upgradeToVersion606(SQLiteDatabase db) { 3351 db.execSQL("DROP VIEW IF EXISTS view_contacts_restricted;"); 3352 db.execSQL("DROP VIEW IF EXISTS view_data_restricted;"); 3353 db.execSQL("DROP VIEW IF EXISTS view_raw_contacts_restricted;"); 3354 db.execSQL("DROP VIEW IF EXISTS view_raw_entities_restricted;"); 3355 db.execSQL("DROP VIEW IF EXISTS view_entities_restricted;"); 3356 db.execSQL("DROP VIEW IF EXISTS view_data_usage_stat_restricted;"); 3357 db.execSQL("DROP INDEX IF EXISTS contacts_restricted_index"); 3358 3359 // We should remove the restricted columns here as well, but unfortunately SQLite doesn't 3360 // provide ALTER TABLE DROP COLUMN. As they have DEFAULT 0, we can keep but ignore them 3361 } 3362 3363 private void upgradeToVersion607(SQLiteDatabase db) { 3364 // We added "action" and "action_uri" to groups here, but realized this was not a smart 3365 // move. This upgrade step has been removed (all dogfood phones that executed this step 3366 // will have those columns, but that shouldn't hurt. Unfortunately, SQLite makes it hard 3367 // to remove columns) 3368 } 3369 3370 private void upgradeToVersion608(SQLiteDatabase db) { 3371 db.execSQL("ALTER TABLE contacts ADD photo_file_id INTEGER REFERENCES photo_files(_id);"); 3372 3373 db.execSQL("CREATE TABLE photo_files(" + 3374 "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3375 "height INTEGER NOT NULL, " + 3376 "width INTEGER NOT NULL, " + 3377 "filesize INTEGER NOT NULL);"); 3378 } 3379 3380 private void upgradeToVersion609(SQLiteDatabase db) { 3381 // This version used to create the stream item and stream item photos tables, but a newer 3382 // version of those tables is created in version 613 below. So omitting the creation in 3383 // this upgrade step to avoid a create->drop->create. 3384 } 3385 3386 private void upgradeToVersion610(SQLiteDatabase db) { 3387 db.execSQL("ALTER TABLE calls ADD is_read INTEGER;"); 3388 } 3389 3390 private void upgradeToVersion611(SQLiteDatabase db) { 3391 db.execSQL("ALTER TABLE raw_contacts ADD data_set TEXT DEFAULT NULL;"); 3392 db.execSQL("ALTER TABLE groups ADD data_set TEXT DEFAULT NULL;"); 3393 db.execSQL("ALTER TABLE accounts ADD data_set TEXT DEFAULT NULL;"); 3394 3395 db.execSQL("CREATE INDEX raw_contacts_source_id_data_set_index ON raw_contacts " + 3396 "(sourceid, account_type, account_name, data_set);"); 3397 3398 db.execSQL("CREATE INDEX groups_source_id_data_set_index ON groups " + 3399 "(sourceid, account_type, account_name, data_set);"); 3400 } 3401 3402 private void upgradeToVersion612(SQLiteDatabase db) { 3403 db.execSQL("ALTER TABLE calls ADD geocoded_location TEXT DEFAULT NULL;"); 3404 // Old calls will not have a geocoded location; new calls will get it when inserted. 3405 } 3406 3407 private void upgradeToVersion613(SQLiteDatabase db) { 3408 // The stream item and stream item photos APIs were not in-use by anyone in the time 3409 // between their initial creation (in v609) and this update. So we're just dropping 3410 // and re-creating them to get appropriate columns. The delta is as follows: 3411 // - In stream_items, package_id was replaced by res_package. 3412 // - In stream_item_photos, picture was replaced by photo_file_id. 3413 // - Instead of resource ids for icon and label, we use resource name strings now 3414 // - Added sync columns 3415 // - Removed action and action_uri 3416 // - Text and comments are now nullable 3417 3418 db.execSQL("DROP TABLE IF EXISTS stream_items"); 3419 db.execSQL("DROP TABLE IF EXISTS stream_item_photos"); 3420 3421 db.execSQL("CREATE TABLE stream_items(" + 3422 "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3423 "raw_contact_id INTEGER NOT NULL, " + 3424 "res_package TEXT, " + 3425 "icon TEXT, " + 3426 "label TEXT, " + 3427 "text TEXT, " + 3428 "timestamp INTEGER NOT NULL, " + 3429 "comments TEXT, " + 3430 "stream_item_sync1 TEXT, " + 3431 "stream_item_sync2 TEXT, " + 3432 "stream_item_sync3 TEXT, " + 3433 "stream_item_sync4 TEXT, " + 3434 "FOREIGN KEY(raw_contact_id) REFERENCES raw_contacts(_id));"); 3435 3436 db.execSQL("CREATE TABLE stream_item_photos(" + 3437 "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 3438 "stream_item_id INTEGER NOT NULL, " + 3439 "sort_index INTEGER, " + 3440 "photo_file_id INTEGER NOT NULL, " + 3441 "stream_item_photo_sync1 TEXT, " + 3442 "stream_item_photo_sync2 TEXT, " + 3443 "stream_item_photo_sync3 TEXT, " + 3444 "stream_item_photo_sync4 TEXT, " + 3445 "FOREIGN KEY(stream_item_id) REFERENCES stream_items(_id));"); 3446 } 3447 3448 private void upgradeToVersion615(SQLiteDatabase db) { 3449 // Old calls will not have up to date values for these columns, they will be filled in 3450 // as needed. 3451 db.execSQL("ALTER TABLE calls ADD lookup_uri TEXT DEFAULT NULL;"); 3452 db.execSQL("ALTER TABLE calls ADD matched_number TEXT DEFAULT NULL;"); 3453 db.execSQL("ALTER TABLE calls ADD normalized_number TEXT DEFAULT NULL;"); 3454 db.execSQL("ALTER TABLE calls ADD photo_id INTEGER NOT NULL DEFAULT 0;"); 3455 } 3456 3457 private void upgradeToVersion618(SQLiteDatabase db) { 3458 // The Settings table needs a data_set column which technically should be part of the 3459 // primary key but can't be because it may be null. Since SQLite doesn't support nuking 3460 // the primary key, we'll drop the old table, re-create it, and copy the settings back in. 3461 db.execSQL("CREATE TEMPORARY TABLE settings_backup(" + 3462 "account_name STRING NOT NULL," + 3463 "account_type STRING NOT NULL," + 3464 "ungrouped_visible INTEGER NOT NULL DEFAULT 0," + 3465 "should_sync INTEGER NOT NULL DEFAULT 1" + 3466 ");"); 3467 db.execSQL("INSERT INTO settings_backup " + 3468 "SELECT account_name, account_type, ungrouped_visible, should_sync" + 3469 " FROM settings"); 3470 db.execSQL("DROP TABLE settings"); 3471 db.execSQL("CREATE TABLE settings (" + 3472 "account_name STRING NOT NULL," + 3473 "account_type STRING NOT NULL," + 3474 "data_set STRING," + 3475 "ungrouped_visible INTEGER NOT NULL DEFAULT 0," + 3476 "should_sync INTEGER NOT NULL DEFAULT 1" + 3477 ");"); 3478 db.execSQL("INSERT INTO settings " + 3479 "SELECT account_name, account_type, NULL, ungrouped_visible, should_sync " + 3480 "FROM settings_backup"); 3481 db.execSQL("DROP TABLE settings_backup"); 3482 } 3483 3484 public String extractHandleFromEmailAddress(String email) { 3485 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email); 3486 if (tokens.length == 0) { 3487 return null; 3488 } 3489 3490 String address = tokens[0].getAddress(); 3491 int at = address.indexOf('@'); 3492 if (at != -1) { 3493 return address.substring(0, at); 3494 } 3495 return null; 3496 } 3497 3498 public String extractAddressFromEmailAddress(String email) { 3499 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(email); 3500 if (tokens.length == 0) { 3501 return null; 3502 } 3503 3504 return tokens[0].getAddress().trim(); 3505 } 3506 3507 private static long lookupMimeTypeId(SQLiteDatabase db, String mimeType) { 3508 try { 3509 return DatabaseUtils.longForQuery(db, 3510 "SELECT " + MimetypesColumns._ID + 3511 " FROM " + Tables.MIMETYPES + 3512 " WHERE " + MimetypesColumns.MIMETYPE 3513 + "='" + mimeType + "'", null); 3514 } catch (SQLiteDoneException e) { 3515 // No rows of this type in the database 3516 return -1; 3517 } 3518 } 3519 3520 private void bindString(SQLiteStatement stmt, int index, String value) { 3521 if (value == null) { 3522 stmt.bindNull(index); 3523 } else { 3524 stmt.bindString(index, value); 3525 } 3526 } 3527 3528 private void bindLong(SQLiteStatement stmt, int index, Number value) { 3529 if (value == null) { 3530 stmt.bindNull(index); 3531 } else { 3532 stmt.bindLong(index, value.longValue()); 3533 } 3534 } 3535 3536 /** 3537 * Adds index stats into the SQLite database to force it to always use the lookup indexes. 3538 */ 3539 private void updateSqliteStats(SQLiteDatabase db) { 3540 3541 // Specific stats strings are based on an actual large database after running ANALYZE 3542 try { 3543 updateIndexStats(db, Tables.CONTACTS, 3544 "contacts_has_phone_index", "10000 500"); 3545 3546 updateIndexStats(db, Tables.RAW_CONTACTS, 3547 "raw_contacts_source_id_index", "10000 1 1 1"); 3548 updateIndexStats(db, Tables.RAW_CONTACTS, 3549 "raw_contacts_contact_id_index", "10000 2"); 3550 3551 updateIndexStats(db, Tables.NAME_LOOKUP, 3552 "name_lookup_raw_contact_id_index", "10000 3"); 3553 updateIndexStats(db, Tables.NAME_LOOKUP, 3554 "name_lookup_index", "10000 3 2 2 1"); 3555 updateIndexStats(db, Tables.NAME_LOOKUP, 3556 "sqlite_autoindex_name_lookup_1", "10000 3 2 1"); 3557 3558 updateIndexStats(db, Tables.PHONE_LOOKUP, 3559 "phone_lookup_index", "10000 2 2 1"); 3560 updateIndexStats(db, Tables.PHONE_LOOKUP, 3561 "phone_lookup_min_match_index", "10000 2 2 1"); 3562 3563 updateIndexStats(db, Tables.DATA, 3564 "data_mimetype_data1_index", "60000 5000 2"); 3565 updateIndexStats(db, Tables.DATA, 3566 "data_raw_contact_id", "60000 10"); 3567 3568 updateIndexStats(db, Tables.GROUPS, 3569 "groups_source_id_index", "50 1 1 1"); 3570 3571 updateIndexStats(db, Tables.NICKNAME_LOOKUP, 3572 "sqlite_autoindex_name_lookup_1", "500 2 1"); 3573 3574 } catch (SQLException e) { 3575 Log.e(TAG, "Could not update index stats", e); 3576 } 3577 } 3578 3579 /** 3580 * Stores statistics for a given index. 3581 * 3582 * @param stats has the following structure: the first index is the expected size of 3583 * the table. The following integer(s) are the expected number of records selected with the 3584 * index. There should be one integer per indexed column. 3585 */ 3586 private void updateIndexStats(SQLiteDatabase db, String table, String index, 3587 String stats) { 3588 db.execSQL("DELETE FROM sqlite_stat1 WHERE tbl='" + table + "' AND idx='" + index + "';"); 3589 db.execSQL("INSERT INTO sqlite_stat1 (tbl,idx,stat)" 3590 + " VALUES ('" + table + "','" + index + "','" + stats + "');"); 3591 } 3592 3593 @Override 3594 public synchronized SQLiteDatabase getWritableDatabase() { 3595 SQLiteDatabase db = super.getWritableDatabase(); 3596 if (mReopenDatabase) { 3597 mReopenDatabase = false; 3598 close(); 3599 db = super.getWritableDatabase(); 3600 } 3601 return db; 3602 } 3603 3604 /** 3605 * Wipes all data except mime type and package lookup tables. 3606 */ 3607 public void wipeData() { 3608 SQLiteDatabase db = getWritableDatabase(); 3609 3610 db.execSQL("DELETE FROM " + Tables.ACCOUNTS + ";"); 3611 db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " VALUES(NULL, NULL, NULL)"); 3612 3613 db.execSQL("DELETE FROM " + Tables.CONTACTS + ";"); 3614 db.execSQL("DELETE FROM " + Tables.RAW_CONTACTS + ";"); 3615 db.execSQL("DELETE FROM " + Tables.STREAM_ITEMS + ";"); 3616 db.execSQL("DELETE FROM " + Tables.STREAM_ITEM_PHOTOS + ";"); 3617 db.execSQL("DELETE FROM " + Tables.PHOTO_FILES + ";"); 3618 db.execSQL("DELETE FROM " + Tables.DATA + ";"); 3619 db.execSQL("DELETE FROM " + Tables.PHONE_LOOKUP + ";"); 3620 db.execSQL("DELETE FROM " + Tables.NAME_LOOKUP + ";"); 3621 db.execSQL("DELETE FROM " + Tables.GROUPS + ";"); 3622 db.execSQL("DELETE FROM " + Tables.AGGREGATION_EXCEPTIONS + ";"); 3623 db.execSQL("DELETE FROM " + Tables.SETTINGS + ";"); 3624 db.execSQL("DELETE FROM " + Tables.ACTIVITIES + ";"); 3625 db.execSQL("DELETE FROM " + Tables.CALLS + ";"); 3626 db.execSQL("DELETE FROM " + Tables.DIRECTORIES + ";"); 3627 db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + ";"); 3628 3629 // Note: we are not removing reference data from Tables.NICKNAME_LOOKUP 3630 } 3631 3632 public NameSplitter createNameSplitter() { 3633 mNameSplitter = new NameSplitter( 3634 mContext.getString(com.android.internal.R.string.common_name_prefixes), 3635 mContext.getString(com.android.internal.R.string.common_last_name_prefixes), 3636 mContext.getString(com.android.internal.R.string.common_name_suffixes), 3637 mContext.getString(com.android.internal.R.string.common_name_conjunctions), 3638 Locale.getDefault()); 3639 return mNameSplitter; 3640 } 3641 3642 /** 3643 * Return the {@link ApplicationInfo#uid} for the given package name. 3644 */ 3645 public static int getUidForPackageName(PackageManager pm, String packageName) { 3646 try { 3647 ApplicationInfo clientInfo = pm.getApplicationInfo(packageName, 0 /* no flags */); 3648 return clientInfo.uid; 3649 } catch (NameNotFoundException e) { 3650 throw new RuntimeException(e); 3651 } 3652 } 3653 3654 /** 3655 * Perform an internal string-to-integer lookup using the compiled 3656 * {@link SQLiteStatement} provided. If a mapping isn't found in database, it will be 3657 * created. All new, uncached answers are added to the cache automatically. 3658 * 3659 * @param query Compiled statement used to query for the mapping. 3660 * @param insert Compiled statement used to insert a new mapping when no 3661 * existing one is found in cache or from query. 3662 * @param value Value to find mapping for. 3663 * @param cache In-memory cache of previous answers. 3664 * @return An unique integer mapping for the given value. 3665 */ 3666 private long lookupAndCacheId(SQLiteStatement query, SQLiteStatement insert, 3667 String value, HashMap<String, Long> cache) { 3668 long id = -1; 3669 try { 3670 // Try searching database for mapping 3671 DatabaseUtils.bindObjectToProgram(query, 1, value); 3672 id = query.simpleQueryForLong(); 3673 } catch (SQLiteDoneException e) { 3674 // Nothing found, so try inserting new mapping 3675 DatabaseUtils.bindObjectToProgram(insert, 1, value); 3676 id = insert.executeInsert(); 3677 } 3678 if (id != -1) { 3679 // Cache and return the new answer 3680 cache.put(value, id); 3681 return id; 3682 } else { 3683 // Otherwise throw if no mapping found or created 3684 throw new IllegalStateException("Couldn't find or create internal " 3685 + "lookup table entry for value " + value); 3686 } 3687 } 3688 3689 /** 3690 * Convert a package name into an integer, using {@link Tables#PACKAGES} for 3691 * lookups and possible allocation of new IDs as needed. 3692 */ 3693 public long getPackageId(String packageName) { 3694 // Try an in-memory cache lookup 3695 if (mPackageCache.containsKey(packageName)) return mPackageCache.get(packageName); 3696 3697 final SQLiteStatement packageQuery = getWritableDatabase().compileStatement( 3698 "SELECT " + PackagesColumns._ID + 3699 " FROM " + Tables.PACKAGES + 3700 " WHERE " + PackagesColumns.PACKAGE + "=?"); 3701 3702 final SQLiteStatement packageInsert = getWritableDatabase().compileStatement( 3703 "INSERT INTO " + Tables.PACKAGES + "(" 3704 + PackagesColumns.PACKAGE + 3705 ") VALUES (?)"); 3706 try { 3707 return lookupAndCacheId(packageQuery, packageInsert, packageName, mPackageCache); 3708 } finally { 3709 packageQuery.close(); 3710 packageInsert.close(); 3711 } 3712 } 3713 3714 /** 3715 * Convert a mimetype into an integer, using {@link Tables#MIMETYPES} for 3716 * lookups and possible allocation of new IDs as needed. 3717 */ 3718 public long getMimeTypeId(String mimetype) { 3719 // Try an in-memory cache lookup 3720 if (mMimetypeCache.containsKey(mimetype)) return mMimetypeCache.get(mimetype); 3721 3722 return lookupMimeTypeId(mimetype, getWritableDatabase()); 3723 } 3724 3725 private long lookupMimeTypeId(String mimetype, SQLiteDatabase db) { 3726 final SQLiteStatement mimetypeQuery = db.compileStatement( 3727 "SELECT " + MimetypesColumns._ID + 3728 " FROM " + Tables.MIMETYPES + 3729 " WHERE " + MimetypesColumns.MIMETYPE + "=?"); 3730 3731 final SQLiteStatement mimetypeInsert = db.compileStatement( 3732 "INSERT INTO " + Tables.MIMETYPES + "(" 3733 + MimetypesColumns.MIMETYPE + 3734 ") VALUES (?)"); 3735 3736 try { 3737 return lookupAndCacheId(mimetypeQuery, mimetypeInsert, mimetype, mMimetypeCache); 3738 } finally { 3739 mimetypeQuery.close(); 3740 mimetypeInsert.close(); 3741 } 3742 } 3743 3744 public long getMimeTypeIdForStructuredName() { 3745 return mMimeTypeIdStructuredName; 3746 } 3747 3748 public long getMimeTypeIdForStructuredPostal() { 3749 return mMimeTypeIdStructuredPostal; 3750 } 3751 3752 public long getMimeTypeIdForOrganization() { 3753 return mMimeTypeIdOrganization; 3754 } 3755 3756 public long getMimeTypeIdForIm() { 3757 return mMimeTypeIdIm; 3758 } 3759 3760 public long getMimeTypeIdForEmail() { 3761 return mMimeTypeIdEmail; 3762 } 3763 3764 public long getMimeTypeIdForPhone() { 3765 return mMimeTypeIdPhone; 3766 } 3767 3768 public long getMimeTypeIdForSip() { 3769 return mMimeTypeIdSip; 3770 } 3771 3772 public int getDisplayNameSourceForMimeTypeId(int mimeTypeId) { 3773 if (mimeTypeId == mMimeTypeIdStructuredName) { 3774 return DisplayNameSources.STRUCTURED_NAME; 3775 } else if (mimeTypeId == mMimeTypeIdEmail) { 3776 return DisplayNameSources.EMAIL; 3777 } else if (mimeTypeId == mMimeTypeIdPhone) { 3778 return DisplayNameSources.PHONE; 3779 } else if (mimeTypeId == mMimeTypeIdOrganization) { 3780 return DisplayNameSources.ORGANIZATION; 3781 } else if (mimeTypeId == mMimeTypeIdNickname) { 3782 return DisplayNameSources.NICKNAME; 3783 } else { 3784 return DisplayNameSources.UNDEFINED; 3785 } 3786 } 3787 3788 /** 3789 * Find the mimetype for the given {@link Data#_ID}. 3790 */ 3791 public String getDataMimeType(long dataId) { 3792 if (mDataMimetypeQuery == null) { 3793 mDataMimetypeQuery = getWritableDatabase().compileStatement( 3794 "SELECT " + MimetypesColumns.MIMETYPE + 3795 " FROM " + Tables.DATA_JOIN_MIMETYPES + 3796 " WHERE " + Tables.DATA + "." + Data._ID + "=?"); 3797 } 3798 try { 3799 // Try database query to find mimetype 3800 DatabaseUtils.bindObjectToProgram(mDataMimetypeQuery, 1, dataId); 3801 String mimetype = mDataMimetypeQuery.simpleQueryForString(); 3802 return mimetype; 3803 } catch (SQLiteDoneException e) { 3804 // No valid mapping found, so return null 3805 return null; 3806 } 3807 } 3808 3809 /** 3810 * Find the mime-type for the given {@link Activities#_ID}. 3811 */ 3812 public String getActivityMimeType(long activityId) { 3813 if (mActivitiesMimetypeQuery == null) { 3814 mActivitiesMimetypeQuery = getWritableDatabase().compileStatement( 3815 "SELECT " + MimetypesColumns.MIMETYPE + 3816 " FROM " + Tables.ACTIVITIES_JOIN_MIMETYPES + 3817 " WHERE " + Tables.ACTIVITIES + "." + Activities._ID + "=?"); 3818 } 3819 try { 3820 // Try database query to find mimetype 3821 DatabaseUtils.bindObjectToProgram(mActivitiesMimetypeQuery, 1, activityId); 3822 String mimetype = mActivitiesMimetypeQuery.simpleQueryForString(); 3823 return mimetype; 3824 } catch (SQLiteDoneException e) { 3825 // No valid mapping found, so return null 3826 return null; 3827 } 3828 } 3829 3830 /** 3831 * Update {@link Contacts#IN_VISIBLE_GROUP} for all contacts. 3832 */ 3833 public void updateAllVisible() { 3834 updateCustomContactVisibility(getWritableDatabase(), ""); 3835 } 3836 3837 /** 3838 * Updates contact visibility and return true iff the visibility was actually changed. 3839 */ 3840 public boolean updateContactVisibleOnlyIfChanged(TransactionContext txContext, long contactId) { 3841 return updateContactVisible(txContext, contactId, true); 3842 } 3843 3844 /** 3845 * Update {@link Contacts#IN_VISIBLE_GROUP} and 3846 * {@link Tables#DEFAULT_DIRECTORY} for a specific contact. 3847 */ 3848 public void updateContactVisible(TransactionContext txContext, long contactId) { 3849 updateContactVisible(txContext, contactId, false); 3850 } 3851 3852 public boolean updateContactVisible( 3853 TransactionContext txContext, long contactId, boolean onlyIfChanged) { 3854 SQLiteDatabase db = getWritableDatabase(); 3855 updateCustomContactVisibility(db, " AND " + Contacts._ID + "=" + contactId); 3856 3857 String contactIdAsString = String.valueOf(contactId); 3858 long mimetype = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); 3859 3860 // The contact will be included in the default directory if contains 3861 // a raw contact that is in any group or in an account that 3862 // does not have any AUTO_ADD groups. 3863 boolean newVisibility = DatabaseUtils.longForQuery(db, 3864 "SELECT EXISTS (" + 3865 "SELECT " + RawContacts.CONTACT_ID + 3866 " FROM " + Tables.RAW_CONTACTS + 3867 " JOIN " + Tables.DATA + 3868 " ON (" + RawContactsColumns.CONCRETE_ID + "=" 3869 + Data.RAW_CONTACT_ID + ")" + 3870 " WHERE " + RawContacts.CONTACT_ID + "=?" + 3871 " AND " + DataColumns.MIMETYPE_ID + "=?" + 3872 ") OR EXISTS (" + 3873 "SELECT " + RawContacts._ID + 3874 " FROM " + Tables.RAW_CONTACTS + 3875 " WHERE " + RawContacts.CONTACT_ID + "=?" + 3876 " AND NOT EXISTS" + 3877 " (SELECT " + Groups._ID + 3878 " FROM " + Tables.GROUPS + 3879 " WHERE " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " = " 3880 + GroupsColumns.CONCRETE_ACCOUNT_NAME + 3881 " AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " = " 3882 + GroupsColumns.CONCRETE_ACCOUNT_TYPE + 3883 " AND (" + RawContactsColumns.CONCRETE_DATA_SET + " = " 3884 + GroupsColumns.CONCRETE_DATA_SET 3885 + " OR " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL AND " 3886 + GroupsColumns.CONCRETE_DATA_SET + " IS NULL)" + 3887 " AND " + Groups.AUTO_ADD + " != 0" + 3888 ")" + 3889 ") OR EXISTS (" + 3890 "SELECT " + RawContacts._ID + 3891 " FROM " + Tables.RAW_CONTACTS + 3892 " WHERE " + RawContacts.CONTACT_ID + "=?" + 3893 " AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL " + 3894 " AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL" + 3895 " AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL" + 3896 ")", 3897 new String[] { 3898 contactIdAsString, 3899 String.valueOf(mimetype), 3900 contactIdAsString, 3901 contactIdAsString 3902 }) != 0; 3903 3904 if (onlyIfChanged) { 3905 boolean oldVisibility = isContactInDefaultDirectory(db, contactId); 3906 if (oldVisibility == newVisibility) { 3907 return false; 3908 } 3909 } 3910 3911 if (newVisibility) { 3912 db.execSQL("INSERT OR IGNORE INTO " + Tables.DEFAULT_DIRECTORY + " VALUES(?)", 3913 new String[] { contactIdAsString }); 3914 txContext.invalidateSearchIndexForContact(contactId); 3915 } else { 3916 db.execSQL("DELETE FROM " + Tables.DEFAULT_DIRECTORY + 3917 " WHERE " + Contacts._ID + "=?", 3918 new String[] { contactIdAsString }); 3919 db.execSQL("DELETE FROM " + Tables.SEARCH_INDEX + 3920 " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", 3921 new String[] { contactIdAsString }); 3922 } 3923 return true; 3924 } 3925 3926 public boolean isContactInDefaultDirectory(SQLiteDatabase db, long contactId) { 3927 if (mContactInDefaultDirectoryQuery == null) { 3928 mContactInDefaultDirectoryQuery = db.compileStatement( 3929 "SELECT EXISTS (" + 3930 "SELECT 1 FROM " + Tables.DEFAULT_DIRECTORY + 3931 " WHERE " + Contacts._ID + "=?)"); 3932 } 3933 mContactInDefaultDirectoryQuery.bindLong(1, contactId); 3934 return mContactInDefaultDirectoryQuery.simpleQueryForLong() != 0; 3935 } 3936 3937 private void updateCustomContactVisibility(SQLiteDatabase db, String selection) { 3938 final long groupMembershipMimetypeId = getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); 3939 String[] selectionArgs = new String[]{String.valueOf(groupMembershipMimetypeId)}; 3940 3941 // First delete what needs to be deleted, then insert what needs to be added. 3942 // Since flash writes are very expensive, this approach is much better than 3943 // delete-all-insert-all. 3944 db.execSQL("DELETE FROM " + Tables.VISIBLE_CONTACTS + 3945 " WHERE " + "_id NOT IN" + 3946 "(SELECT " + Contacts._ID + 3947 " FROM " + Tables.CONTACTS + 3948 " WHERE (" + Clauses.CONTACT_IS_VISIBLE + ")=1) " + selection, 3949 selectionArgs); 3950 3951 db.execSQL("INSERT INTO " + Tables.VISIBLE_CONTACTS + 3952 " SELECT " + Contacts._ID + 3953 " FROM " + Tables.CONTACTS + 3954 " WHERE " + Contacts._ID + 3955 " NOT IN " + Tables.VISIBLE_CONTACTS + 3956 " AND (" + Clauses.CONTACT_IS_VISIBLE + ")=1 " + selection, 3957 selectionArgs); 3958 } 3959 3960 /** 3961 * Returns contact ID for the given contact or zero if it is NULL. 3962 */ 3963 public long getContactId(long rawContactId) { 3964 if (mContactIdQuery == null) { 3965 mContactIdQuery = getWritableDatabase().compileStatement( 3966 "SELECT " + RawContacts.CONTACT_ID + 3967 " FROM " + Tables.RAW_CONTACTS + 3968 " WHERE " + RawContacts._ID + "=?"); 3969 } 3970 try { 3971 DatabaseUtils.bindObjectToProgram(mContactIdQuery, 1, rawContactId); 3972 return mContactIdQuery.simpleQueryForLong(); 3973 } catch (SQLiteDoneException e) { 3974 // No valid mapping found, so return 0 3975 return 0; 3976 } 3977 } 3978 3979 public int getAggregationMode(long rawContactId) { 3980 if (mAggregationModeQuery == null) { 3981 mAggregationModeQuery = getWritableDatabase().compileStatement( 3982 "SELECT " + RawContacts.AGGREGATION_MODE + 3983 " FROM " + Tables.RAW_CONTACTS + 3984 " WHERE " + RawContacts._ID + "=?"); 3985 } 3986 try { 3987 DatabaseUtils.bindObjectToProgram(mAggregationModeQuery, 1, rawContactId); 3988 return (int)mAggregationModeQuery.simpleQueryForLong(); 3989 } catch (SQLiteDoneException e) { 3990 // No valid row found, so return "disabled" 3991 return RawContacts.AGGREGATION_MODE_DISABLED; 3992 } 3993 } 3994 3995 public void buildPhoneLookupAndContactQuery( 3996 SQLiteQueryBuilder qb, String normalizedNumber, String numberE164) { 3997 String minMatch = PhoneNumberUtils.toCallerIDMinMatch(normalizedNumber); 3998 StringBuilder sb = new StringBuilder(); 3999 appendPhoneLookupTables(sb, minMatch, true); 4000 qb.setTables(sb.toString()); 4001 4002 sb = new StringBuilder(); 4003 appendPhoneLookupSelection(sb, normalizedNumber, numberE164); 4004 qb.appendWhere(sb.toString()); 4005 } 4006 4007 public String buildPhoneLookupAsNestedQuery(String number) { 4008 StringBuilder sb = new StringBuilder(); 4009 final String minMatch = PhoneNumberUtils.toCallerIDMinMatch(number); 4010 sb.append("(SELECT DISTINCT raw_contact_id" + " FROM "); 4011 appendPhoneLookupTables(sb, minMatch, false); 4012 sb.append(" WHERE "); 4013 appendPhoneLookupSelection(sb, number, null); 4014 sb.append(")"); 4015 return sb.toString(); 4016 } 4017 4018 private void appendPhoneLookupTables(StringBuilder sb, final String minMatch, 4019 boolean joinContacts) { 4020 sb.append(Tables.RAW_CONTACTS); 4021 if (joinContacts) { 4022 sb.append(" JOIN " + Views.CONTACTS + " contacts_view" 4023 + " ON (contacts_view._id = raw_contacts.contact_id)"); 4024 } 4025 sb.append(", (SELECT data_id, normalized_number, length(normalized_number) as len " 4026 + " FROM phone_lookup " + " WHERE (" + Tables.PHONE_LOOKUP + "." 4027 + PhoneLookupColumns.MIN_MATCH + " = '"); 4028 sb.append(minMatch); 4029 sb.append("')) AS lookup, " + Tables.DATA); 4030 } 4031 4032 private void appendPhoneLookupSelection(StringBuilder sb, String number, String numberE164) { 4033 sb.append("lookup.data_id=data._id AND data.raw_contact_id=raw_contacts._id"); 4034 boolean hasNumberE164 = !TextUtils.isEmpty(numberE164); 4035 boolean hasNumber = !TextUtils.isEmpty(number); 4036 if (hasNumberE164 || hasNumber) { 4037 sb.append(" AND ( "); 4038 if (hasNumberE164) { 4039 sb.append(" lookup.normalized_number = "); 4040 DatabaseUtils.appendEscapedSQLString(sb, numberE164); 4041 } 4042 if (hasNumberE164 && hasNumber) { 4043 sb.append(" OR "); 4044 } 4045 if (hasNumber) { 4046 int numberLen = number.length(); 4047 sb.append(" lookup.len <= "); 4048 sb.append(numberLen); 4049 sb.append(" AND substr("); 4050 DatabaseUtils.appendEscapedSQLString(sb, number); 4051 sb.append(','); 4052 sb.append(numberLen); 4053 sb.append(" - lookup.len + 1) = lookup.normalized_number"); 4054 // Some countries (e.g. Brazil) can have incoming calls which contain only the local 4055 // number (no country calling code and no area code). This case is handled below. 4056 // Details see b/5197612. 4057 if (!hasNumberE164) { 4058 sb.append(" OR ("); 4059 sb.append(" lookup.len > "); 4060 sb.append(numberLen); 4061 sb.append(" AND substr(lookup.normalized_number,"); 4062 sb.append("lookup.len + 1 - "); 4063 sb.append(numberLen); 4064 sb.append(") = "); 4065 DatabaseUtils.appendEscapedSQLString(sb, number); 4066 sb.append(")"); 4067 } 4068 } 4069 sb.append(')'); 4070 } 4071 } 4072 4073 public String getUseStrictPhoneNumberComparisonParameter() { 4074 return mUseStrictPhoneNumberComparison ? "1" : "0"; 4075 } 4076 4077 /** 4078 * Loads common nickname mappings into the database. 4079 */ 4080 private void loadNicknameLookupTable(SQLiteDatabase db) { 4081 db.execSQL("DELETE FROM " + Tables.NICKNAME_LOOKUP); 4082 4083 String[] strings = mContext.getResources().getStringArray( 4084 com.android.internal.R.array.common_nicknames); 4085 if (strings == null || strings.length == 0) { 4086 return; 4087 } 4088 4089 SQLiteStatement nicknameLookupInsert = db.compileStatement("INSERT INTO " 4090 + Tables.NICKNAME_LOOKUP + "(" + NicknameLookupColumns.NAME + "," 4091 + NicknameLookupColumns.CLUSTER + ") VALUES (?,?)"); 4092 4093 try { 4094 for (int clusterId = 0; clusterId < strings.length; clusterId++) { 4095 String[] names = strings[clusterId].split(","); 4096 for (int j = 0; j < names.length; j++) { 4097 String name = NameNormalizer.normalize(names[j]); 4098 try { 4099 DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 1, name); 4100 DatabaseUtils.bindObjectToProgram(nicknameLookupInsert, 2, 4101 String.valueOf(clusterId)); 4102 nicknameLookupInsert.executeInsert(); 4103 } catch (SQLiteException e) { 4104 4105 // Print the exception and keep going - this is not a fatal error 4106 Log.e(TAG, "Cannot insert nickname: " + names[j], e); 4107 } 4108 } 4109 } 4110 } finally { 4111 nicknameLookupInsert.close(); 4112 } 4113 } 4114 4115 public static void copyStringValue(ContentValues toValues, String toKey, 4116 ContentValues fromValues, String fromKey) { 4117 if (fromValues.containsKey(fromKey)) { 4118 toValues.put(toKey, fromValues.getAsString(fromKey)); 4119 } 4120 } 4121 4122 public static void copyLongValue(ContentValues toValues, String toKey, 4123 ContentValues fromValues, String fromKey) { 4124 if (fromValues.containsKey(fromKey)) { 4125 long longValue; 4126 Object value = fromValues.get(fromKey); 4127 if (value instanceof Boolean) { 4128 if ((Boolean)value) { 4129 longValue = 1; 4130 } else { 4131 longValue = 0; 4132 } 4133 } else if (value instanceof String) { 4134 longValue = Long.parseLong((String)value); 4135 } else { 4136 longValue = ((Number)value).longValue(); 4137 } 4138 toValues.put(toKey, longValue); 4139 } 4140 } 4141 4142 public SyncStateContentProviderHelper getSyncState() { 4143 return mSyncState; 4144 } 4145 4146 /** 4147 * Delete the aggregate contact if it has no constituent raw contacts other 4148 * than the supplied one. 4149 */ 4150 public void removeContactIfSingleton(long rawContactId) { 4151 SQLiteDatabase db = getWritableDatabase(); 4152 4153 // Obtain contact ID from the supplied raw contact ID 4154 String contactIdFromRawContactId = "(SELECT " + RawContacts.CONTACT_ID + " FROM " 4155 + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=" + rawContactId + ")"; 4156 4157 // Find other raw contacts in the same aggregate contact 4158 String otherRawContacts = "(SELECT contacts1." + RawContacts._ID + " FROM " 4159 + Tables.RAW_CONTACTS + " contacts1 JOIN " + Tables.RAW_CONTACTS + " contacts2 ON (" 4160 + "contacts1." + RawContacts.CONTACT_ID + "=contacts2." + RawContacts.CONTACT_ID 4161 + ") WHERE contacts1." + RawContacts._ID + "!=" + rawContactId + "" 4162 + " AND contacts2." + RawContacts._ID + "=" + rawContactId + ")"; 4163 4164 db.execSQL("DELETE FROM " + Tables.CONTACTS 4165 + " WHERE " + Contacts._ID + "=" + contactIdFromRawContactId 4166 + " AND NOT EXISTS " + otherRawContacts + ";"); 4167 } 4168 4169 /** 4170 * Returns the value from the {@link Tables#PROPERTIES} table. 4171 */ 4172 public String getProperty(String key, String defaultValue) { 4173 Cursor cursor = getReadableDatabase().query(Tables.PROPERTIES, 4174 new String[]{PropertiesColumns.PROPERTY_VALUE}, 4175 PropertiesColumns.PROPERTY_KEY + "=?", 4176 new String[]{key}, null, null, null); 4177 String value = null; 4178 try { 4179 if (cursor.moveToFirst()) { 4180 value = cursor.getString(0); 4181 } 4182 } finally { 4183 cursor.close(); 4184 } 4185 4186 return value != null ? value : defaultValue; 4187 } 4188 4189 /** 4190 * Stores a key-value pair in the {@link Tables#PROPERTIES} table. 4191 */ 4192 public void setProperty(String key, String value) { 4193 setProperty(getWritableDatabase(), key, value); 4194 } 4195 4196 private void setProperty(SQLiteDatabase db, String key, String value) { 4197 ContentValues values = new ContentValues(); 4198 values.put(PropertiesColumns.PROPERTY_KEY, key); 4199 values.put(PropertiesColumns.PROPERTY_VALUE, value); 4200 db.replace(Tables.PROPERTIES, null, values); 4201 } 4202 4203 /** 4204 * Test if any of the columns appear in the given projection. 4205 */ 4206 public boolean isInProjection(String[] projection, String... columns) { 4207 if (projection == null) { 4208 return true; 4209 } 4210 4211 // Optimized for a single-column test 4212 if (columns.length == 1) { 4213 String column = columns[0]; 4214 for (String test : projection) { 4215 if (column.equals(test)) { 4216 return true; 4217 } 4218 } 4219 } else { 4220 for (String test : projection) { 4221 for (String column : columns) { 4222 if (column.equals(test)) { 4223 return true; 4224 } 4225 } 4226 } 4227 } 4228 return false; 4229 } 4230 4231 /** 4232 * Returns a detailed exception message for the supplied URI. It includes the calling 4233 * user and calling package(s). 4234 */ 4235 public String exceptionMessage(Uri uri) { 4236 return exceptionMessage(null, uri); 4237 } 4238 4239 /** 4240 * Returns a detailed exception message for the supplied URI. It includes the calling 4241 * user and calling package(s). 4242 */ 4243 public String exceptionMessage(String message, Uri uri) { 4244 StringBuilder sb = new StringBuilder(); 4245 if (message != null) { 4246 sb.append(message).append("; "); 4247 } 4248 sb.append("URI: ").append(uri); 4249 final PackageManager pm = mContext.getPackageManager(); 4250 int callingUid = Binder.getCallingUid(); 4251 sb.append(", calling user: "); 4252 String userName = pm.getNameForUid(callingUid); 4253 if (userName != null) { 4254 sb.append(userName); 4255 } else { 4256 sb.append(callingUid); 4257 } 4258 4259 final String[] callerPackages = pm.getPackagesForUid(callingUid); 4260 if (callerPackages != null && callerPackages.length > 0) { 4261 if (callerPackages.length == 1) { 4262 sb.append(", calling package:"); 4263 sb.append(callerPackages[0]); 4264 } else { 4265 sb.append(", calling package is one of: ["); 4266 for (int i = 0; i < callerPackages.length; i++) { 4267 if (i != 0) { 4268 sb.append(", "); 4269 } 4270 sb.append(callerPackages[i]); 4271 } 4272 sb.append("]"); 4273 } 4274 } 4275 4276 return sb.toString(); 4277 } 4278 4279 protected String getCountryIso() { 4280 CountryDetector detector = 4281 (CountryDetector) mContext.getSystemService(Context.COUNTRY_DETECTOR); 4282 return detector.detectCountry().getCountryIso(); 4283 } 4284 4285 public void deleteStatusUpdate(long dataId) { 4286 if (mStatusUpdateDelete == null) { 4287 mStatusUpdateDelete = getWritableDatabase().compileStatement( 4288 "DELETE FROM " + Tables.STATUS_UPDATES + 4289 " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"); 4290 } 4291 mStatusUpdateDelete.bindLong(1, dataId); 4292 mStatusUpdateDelete.execute(); 4293 } 4294 4295 public void replaceStatusUpdate(Long dataId, long timestamp, String status, String resPackage, 4296 Integer iconResource, Integer labelResource) { 4297 if (mStatusUpdateReplace == null) { 4298 mStatusUpdateReplace = getWritableDatabase().compileStatement( 4299 "INSERT OR REPLACE INTO " + Tables.STATUS_UPDATES + "(" 4300 + StatusUpdatesColumns.DATA_ID + ", " 4301 + StatusUpdates.STATUS_TIMESTAMP + "," 4302 + StatusUpdates.STATUS + "," 4303 + StatusUpdates.STATUS_RES_PACKAGE + "," 4304 + StatusUpdates.STATUS_ICON + "," 4305 + StatusUpdates.STATUS_LABEL + ")" + 4306 " VALUES (?,?,?,?,?,?)"); 4307 } 4308 mStatusUpdateReplace.bindLong(1, dataId); 4309 mStatusUpdateReplace.bindLong(2, timestamp); 4310 bindString(mStatusUpdateReplace, 3, status); 4311 bindString(mStatusUpdateReplace, 4, resPackage); 4312 bindLong(mStatusUpdateReplace, 5, iconResource); 4313 bindLong(mStatusUpdateReplace, 6, labelResource); 4314 mStatusUpdateReplace.execute(); 4315 } 4316 4317 public void insertStatusUpdate(Long dataId, String status, String resPackage, 4318 Integer iconResource, Integer labelResource) { 4319 if (mStatusUpdateInsert == null) { 4320 mStatusUpdateInsert = getWritableDatabase().compileStatement( 4321 "INSERT INTO " + Tables.STATUS_UPDATES + "(" 4322 + StatusUpdatesColumns.DATA_ID + ", " 4323 + StatusUpdates.STATUS + "," 4324 + StatusUpdates.STATUS_RES_PACKAGE + "," 4325 + StatusUpdates.STATUS_ICON + "," 4326 + StatusUpdates.STATUS_LABEL + ")" + 4327 " VALUES (?,?,?,?,?)"); 4328 } 4329 try { 4330 mStatusUpdateInsert.bindLong(1, dataId); 4331 bindString(mStatusUpdateInsert, 2, status); 4332 bindString(mStatusUpdateInsert, 3, resPackage); 4333 bindLong(mStatusUpdateInsert, 4, iconResource); 4334 bindLong(mStatusUpdateInsert, 5, labelResource); 4335 mStatusUpdateInsert.executeInsert(); 4336 } catch (SQLiteConstraintException e) { 4337 // The row already exists - update it 4338 if (mStatusUpdateAutoTimestamp == null) { 4339 mStatusUpdateAutoTimestamp = getWritableDatabase().compileStatement( 4340 "UPDATE " + Tables.STATUS_UPDATES + 4341 " SET " + StatusUpdates.STATUS_TIMESTAMP + "=?," 4342 + StatusUpdates.STATUS + "=?" + 4343 " WHERE " + StatusUpdatesColumns.DATA_ID + "=?" 4344 + " AND " + StatusUpdates.STATUS + "!=?"); 4345 } 4346 4347 long timestamp = System.currentTimeMillis(); 4348 mStatusUpdateAutoTimestamp.bindLong(1, timestamp); 4349 bindString(mStatusUpdateAutoTimestamp, 2, status); 4350 mStatusUpdateAutoTimestamp.bindLong(3, dataId); 4351 bindString(mStatusUpdateAutoTimestamp, 4, status); 4352 mStatusUpdateAutoTimestamp.execute(); 4353 4354 if (mStatusAttributionUpdate == null) { 4355 mStatusAttributionUpdate = getWritableDatabase().compileStatement( 4356 "UPDATE " + Tables.STATUS_UPDATES + 4357 " SET " + StatusUpdates.STATUS_RES_PACKAGE + "=?," 4358 + StatusUpdates.STATUS_ICON + "=?," 4359 + StatusUpdates.STATUS_LABEL + "=?" + 4360 " WHERE " + StatusUpdatesColumns.DATA_ID + "=?"); 4361 } 4362 bindString(mStatusAttributionUpdate, 1, resPackage); 4363 bindLong(mStatusAttributionUpdate, 2, iconResource); 4364 bindLong(mStatusAttributionUpdate, 3, labelResource); 4365 mStatusAttributionUpdate.bindLong(4, dataId); 4366 mStatusAttributionUpdate.execute(); 4367 } 4368 } 4369 4370 /** 4371 * Resets the {@link RawContacts#NAME_VERIFIED} flag to 0 on all other raw 4372 * contacts in the same aggregate 4373 */ 4374 public void resetNameVerifiedForOtherRawContacts(long rawContactId) { 4375 if (mResetNameVerifiedForOtherRawContacts == null) { 4376 mResetNameVerifiedForOtherRawContacts = getWritableDatabase().compileStatement( 4377 "UPDATE " + Tables.RAW_CONTACTS + 4378 " SET " + RawContacts.NAME_VERIFIED + "=0" + 4379 " WHERE " + RawContacts.CONTACT_ID + "=(" + 4380 "SELECT " + RawContacts.CONTACT_ID + 4381 " FROM " + Tables.RAW_CONTACTS + 4382 " WHERE " + RawContacts._ID + "=?)" + 4383 " AND " + RawContacts._ID + "!=?"); 4384 } 4385 mResetNameVerifiedForOtherRawContacts.bindLong(1, rawContactId); 4386 mResetNameVerifiedForOtherRawContacts.bindLong(2, rawContactId); 4387 mResetNameVerifiedForOtherRawContacts.execute(); 4388 } 4389 4390 private interface RawContactNameQuery { 4391 public static final String RAW_SQL = 4392 "SELECT " 4393 + DataColumns.MIMETYPE_ID + "," 4394 + Data.IS_PRIMARY + "," 4395 + Data.DATA1 + "," 4396 + Data.DATA2 + "," 4397 + Data.DATA3 + "," 4398 + Data.DATA4 + "," 4399 + Data.DATA5 + "," 4400 + Data.DATA6 + "," 4401 + Data.DATA7 + "," 4402 + Data.DATA8 + "," 4403 + Data.DATA9 + "," 4404 + Data.DATA10 + "," 4405 + Data.DATA11 + 4406 " FROM " + Tables.DATA + 4407 " WHERE " + Data.RAW_CONTACT_ID + "=?" + 4408 " AND (" + Data.DATA1 + " NOT NULL OR " + 4409 Organization.TITLE + " NOT NULL)"; 4410 4411 public static final int MIMETYPE = 0; 4412 public static final int IS_PRIMARY = 1; 4413 public static final int DATA1 = 2; 4414 public static final int GIVEN_NAME = 3; // data2 4415 public static final int FAMILY_NAME = 4; // data3 4416 public static final int PREFIX = 5; // data4 4417 public static final int TITLE = 5; // data4 4418 public static final int MIDDLE_NAME = 6; // data5 4419 public static final int SUFFIX = 7; // data6 4420 public static final int PHONETIC_GIVEN_NAME = 8; // data7 4421 public static final int PHONETIC_MIDDLE_NAME = 9; // data8 4422 public static final int ORGANIZATION_PHONETIC_NAME = 9; // data8 4423 public static final int PHONETIC_FAMILY_NAME = 10; // data9 4424 public static final int FULL_NAME_STYLE = 11; // data10 4425 public static final int ORGANIZATION_PHONETIC_NAME_STYLE = 11; // data10 4426 public static final int PHONETIC_NAME_STYLE = 12; // data11 4427 } 4428 4429 /** 4430 * Updates a raw contact display name based on data rows, e.g. structured name, 4431 * organization, email etc. 4432 */ 4433 public void updateRawContactDisplayName(SQLiteDatabase db, long rawContactId) { 4434 if (mNameSplitter == null) { 4435 createNameSplitter(); 4436 } 4437 4438 int bestDisplayNameSource = DisplayNameSources.UNDEFINED; 4439 NameSplitter.Name bestName = null; 4440 String bestDisplayName = null; 4441 String bestPhoneticName = null; 4442 int bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED; 4443 4444 mSelectionArgs1[0] = String.valueOf(rawContactId); 4445 Cursor c = db.rawQuery(RawContactNameQuery.RAW_SQL, mSelectionArgs1); 4446 try { 4447 while (c.moveToNext()) { 4448 int mimeType = c.getInt(RawContactNameQuery.MIMETYPE); 4449 int source = getDisplayNameSourceForMimeTypeId(mimeType); 4450 if (source < bestDisplayNameSource || source == DisplayNameSources.UNDEFINED) { 4451 continue; 4452 } 4453 4454 if (source == bestDisplayNameSource 4455 && c.getInt(RawContactNameQuery.IS_PRIMARY) == 0) { 4456 continue; 4457 } 4458 4459 if (mimeType == getMimeTypeIdForStructuredName()) { 4460 NameSplitter.Name name; 4461 if (bestName != null) { 4462 name = new NameSplitter.Name(); 4463 } else { 4464 name = mName; 4465 name.clear(); 4466 } 4467 name.prefix = c.getString(RawContactNameQuery.PREFIX); 4468 name.givenNames = c.getString(RawContactNameQuery.GIVEN_NAME); 4469 name.middleName = c.getString(RawContactNameQuery.MIDDLE_NAME); 4470 name.familyName = c.getString(RawContactNameQuery.FAMILY_NAME); 4471 name.suffix = c.getString(RawContactNameQuery.SUFFIX); 4472 name.fullNameStyle = c.isNull(RawContactNameQuery.FULL_NAME_STYLE) 4473 ? FullNameStyle.UNDEFINED 4474 : c.getInt(RawContactNameQuery.FULL_NAME_STYLE); 4475 name.phoneticFamilyName = c.getString(RawContactNameQuery.PHONETIC_FAMILY_NAME); 4476 name.phoneticMiddleName = c.getString(RawContactNameQuery.PHONETIC_MIDDLE_NAME); 4477 name.phoneticGivenName = c.getString(RawContactNameQuery.PHONETIC_GIVEN_NAME); 4478 name.phoneticNameStyle = c.isNull(RawContactNameQuery.PHONETIC_NAME_STYLE) 4479 ? PhoneticNameStyle.UNDEFINED 4480 : c.getInt(RawContactNameQuery.PHONETIC_NAME_STYLE); 4481 if (!name.isEmpty()) { 4482 bestDisplayNameSource = source; 4483 bestName = name; 4484 } 4485 } else if (mimeType == getMimeTypeIdForOrganization()) { 4486 mCharArrayBuffer.sizeCopied = 0; 4487 c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer); 4488 if (mCharArrayBuffer.sizeCopied != 0) { 4489 bestDisplayNameSource = source; 4490 bestDisplayName = new String(mCharArrayBuffer.data, 0, 4491 mCharArrayBuffer.sizeCopied); 4492 bestPhoneticName = c.getString( 4493 RawContactNameQuery.ORGANIZATION_PHONETIC_NAME); 4494 bestPhoneticNameStyle = 4495 c.isNull(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE) 4496 ? PhoneticNameStyle.UNDEFINED 4497 : c.getInt(RawContactNameQuery.ORGANIZATION_PHONETIC_NAME_STYLE); 4498 } else { 4499 c.copyStringToBuffer(RawContactNameQuery.TITLE, mCharArrayBuffer); 4500 if (mCharArrayBuffer.sizeCopied != 0) { 4501 bestDisplayNameSource = source; 4502 bestDisplayName = new String(mCharArrayBuffer.data, 0, 4503 mCharArrayBuffer.sizeCopied); 4504 bestPhoneticName = null; 4505 bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED; 4506 } 4507 } 4508 } else { 4509 // Display name is at DATA1 in all other types. 4510 // This is ensured in the constructor. 4511 4512 mCharArrayBuffer.sizeCopied = 0; 4513 c.copyStringToBuffer(RawContactNameQuery.DATA1, mCharArrayBuffer); 4514 if (mCharArrayBuffer.sizeCopied != 0) { 4515 bestDisplayNameSource = source; 4516 bestDisplayName = new String(mCharArrayBuffer.data, 0, 4517 mCharArrayBuffer.sizeCopied); 4518 bestPhoneticName = null; 4519 bestPhoneticNameStyle = PhoneticNameStyle.UNDEFINED; 4520 } 4521 } 4522 } 4523 4524 } finally { 4525 c.close(); 4526 } 4527 4528 String displayNamePrimary; 4529 String displayNameAlternative; 4530 String sortNamePrimary; 4531 String sortNameAlternative; 4532 String sortKeyPrimary = null; 4533 String sortKeyAlternative = null; 4534 int displayNameStyle = FullNameStyle.UNDEFINED; 4535 4536 if (bestDisplayNameSource == DisplayNameSources.STRUCTURED_NAME) { 4537 displayNameStyle = bestName.fullNameStyle; 4538 if (displayNameStyle == FullNameStyle.CJK 4539 || displayNameStyle == FullNameStyle.UNDEFINED) { 4540 displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle); 4541 bestName.fullNameStyle = displayNameStyle; 4542 } 4543 4544 displayNamePrimary = mNameSplitter.join(bestName, true, true); 4545 displayNameAlternative = mNameSplitter.join(bestName, false, true); 4546 4547 if (TextUtils.isEmpty(bestName.prefix)) { 4548 sortNamePrimary = displayNamePrimary; 4549 sortNameAlternative = displayNameAlternative; 4550 } else { 4551 sortNamePrimary = mNameSplitter.join(bestName, true, false); 4552 sortNameAlternative = mNameSplitter.join(bestName, false, false); 4553 } 4554 4555 bestPhoneticName = mNameSplitter.joinPhoneticName(bestName); 4556 bestPhoneticNameStyle = bestName.phoneticNameStyle; 4557 } else { 4558 displayNamePrimary = displayNameAlternative = bestDisplayName; 4559 sortNamePrimary = sortNameAlternative = bestDisplayName; 4560 } 4561 4562 if (bestPhoneticName != null) { 4563 sortKeyPrimary = sortKeyAlternative = bestPhoneticName; 4564 if (bestPhoneticNameStyle == PhoneticNameStyle.UNDEFINED) { 4565 bestPhoneticNameStyle = mNameSplitter.guessPhoneticNameStyle(bestPhoneticName); 4566 } 4567 } else { 4568 if (displayNameStyle == FullNameStyle.UNDEFINED) { 4569 displayNameStyle = mNameSplitter.guessFullNameStyle(bestDisplayName); 4570 if (displayNameStyle == FullNameStyle.UNDEFINED 4571 || displayNameStyle == FullNameStyle.CJK) { 4572 displayNameStyle = mNameSplitter.getAdjustedNameStyleBasedOnPhoneticNameStyle( 4573 displayNameStyle, bestPhoneticNameStyle); 4574 } 4575 displayNameStyle = mNameSplitter.getAdjustedFullNameStyle(displayNameStyle); 4576 } 4577 if (displayNameStyle == FullNameStyle.CHINESE || 4578 displayNameStyle == FullNameStyle.CJK) { 4579 sortKeyPrimary = sortKeyAlternative = 4580 ContactLocaleUtils.getIntance().getSortKey( 4581 sortNamePrimary, displayNameStyle); 4582 } 4583 } 4584 4585 if (sortKeyPrimary == null) { 4586 sortKeyPrimary = sortNamePrimary; 4587 sortKeyAlternative = sortNameAlternative; 4588 } 4589 4590 if (mRawContactDisplayNameUpdate == null) { 4591 mRawContactDisplayNameUpdate = db.compileStatement( 4592 "UPDATE " + Tables.RAW_CONTACTS + 4593 " SET " + 4594 RawContacts.DISPLAY_NAME_SOURCE + "=?," + 4595 RawContacts.DISPLAY_NAME_PRIMARY + "=?," + 4596 RawContacts.DISPLAY_NAME_ALTERNATIVE + "=?," + 4597 RawContacts.PHONETIC_NAME + "=?," + 4598 RawContacts.PHONETIC_NAME_STYLE + "=?," + 4599 RawContacts.SORT_KEY_PRIMARY + "=?," + 4600 RawContacts.SORT_KEY_ALTERNATIVE + "=?" + 4601 " WHERE " + RawContacts._ID + "=?"); 4602 } 4603 4604 mRawContactDisplayNameUpdate.bindLong(1, bestDisplayNameSource); 4605 bindString(mRawContactDisplayNameUpdate, 2, displayNamePrimary); 4606 bindString(mRawContactDisplayNameUpdate, 3, displayNameAlternative); 4607 bindString(mRawContactDisplayNameUpdate, 4, bestPhoneticName); 4608 mRawContactDisplayNameUpdate.bindLong(5, bestPhoneticNameStyle); 4609 bindString(mRawContactDisplayNameUpdate, 6, sortKeyPrimary); 4610 bindString(mRawContactDisplayNameUpdate, 7, sortKeyAlternative); 4611 mRawContactDisplayNameUpdate.bindLong(8, rawContactId); 4612 mRawContactDisplayNameUpdate.execute(); 4613 } 4614 4615 /* 4616 * Sets the given dataId record in the "data" table to primary, and resets all data records of 4617 * the same mimetype and under the same contact to not be primary. 4618 * 4619 * @param dataId the id of the data record to be set to primary. Pass -1 to clear the primary 4620 * flag of all data items of this raw contacts 4621 */ 4622 public void setIsPrimary(long rawContactId, long dataId, long mimeTypeId) { 4623 if (mSetPrimaryStatement == null) { 4624 mSetPrimaryStatement = getWritableDatabase().compileStatement( 4625 "UPDATE " + Tables.DATA + 4626 " SET " + Data.IS_PRIMARY + "=(_id=?)" + 4627 " WHERE " + DataColumns.MIMETYPE_ID + "=?" + 4628 " AND " + Data.RAW_CONTACT_ID + "=?"); 4629 } 4630 mSetPrimaryStatement.bindLong(1, dataId); 4631 mSetPrimaryStatement.bindLong(2, mimeTypeId); 4632 mSetPrimaryStatement.bindLong(3, rawContactId); 4633 mSetPrimaryStatement.execute(); 4634 } 4635 4636 /* 4637 * Clears the super primary of all data items of the given raw contact. does not touch 4638 * other raw contacts of the same joined aggregate 4639 */ 4640 public void clearSuperPrimary(long rawContactId, long mimeTypeId) { 4641 if (mClearSuperPrimaryStatement == null) { 4642 mClearSuperPrimaryStatement = getWritableDatabase().compileStatement( 4643 "UPDATE " + Tables.DATA + 4644 " SET " + Data.IS_SUPER_PRIMARY + "=0" + 4645 " WHERE " + DataColumns.MIMETYPE_ID + "=?" + 4646 " AND " + Data.RAW_CONTACT_ID + "=?"); 4647 } 4648 mClearSuperPrimaryStatement.bindLong(1, mimeTypeId); 4649 mClearSuperPrimaryStatement.bindLong(2, rawContactId); 4650 mClearSuperPrimaryStatement.execute(); 4651 } 4652 4653 /* 4654 * Sets the given dataId record in the "data" table to "super primary", and resets all data 4655 * records of the same mimetype and under the same aggregate to not be "super primary". 4656 * 4657 * @param dataId the id of the data record to be set to primary. 4658 */ 4659 public void setIsSuperPrimary(long rawContactId, long dataId, long mimeTypeId) { 4660 if (mSetSuperPrimaryStatement == null) { 4661 mSetSuperPrimaryStatement = getWritableDatabase().compileStatement( 4662 "UPDATE " + Tables.DATA + 4663 " SET " + Data.IS_SUPER_PRIMARY + "=(" + Data._ID + "=?)" + 4664 " WHERE " + DataColumns.MIMETYPE_ID + "=?" + 4665 " AND " + Data.RAW_CONTACT_ID + " IN (" + 4666 "SELECT " + RawContacts._ID + 4667 " FROM " + Tables.RAW_CONTACTS + 4668 " WHERE " + RawContacts.CONTACT_ID + " =(" + 4669 "SELECT " + RawContacts.CONTACT_ID + 4670 " FROM " + Tables.RAW_CONTACTS + 4671 " WHERE " + RawContacts._ID + "=?))"); 4672 } 4673 mSetSuperPrimaryStatement.bindLong(1, dataId); 4674 mSetSuperPrimaryStatement.bindLong(2, mimeTypeId); 4675 mSetSuperPrimaryStatement.bindLong(3, rawContactId); 4676 mSetSuperPrimaryStatement.execute(); 4677 } 4678 4679 /** 4680 * Inserts a record in the {@link Tables#NAME_LOOKUP} table. 4681 */ 4682 public void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) { 4683 if (TextUtils.isEmpty(name)) { 4684 return; 4685 } 4686 4687 if (mNameLookupInsert == null) { 4688 mNameLookupInsert = getWritableDatabase().compileStatement( 4689 "INSERT OR IGNORE INTO " + Tables.NAME_LOOKUP + "(" 4690 + NameLookupColumns.RAW_CONTACT_ID + "," 4691 + NameLookupColumns.DATA_ID + "," 4692 + NameLookupColumns.NAME_TYPE + "," 4693 + NameLookupColumns.NORMALIZED_NAME 4694 + ") VALUES (?,?,?,?)"); 4695 } 4696 mNameLookupInsert.bindLong(1, rawContactId); 4697 mNameLookupInsert.bindLong(2, dataId); 4698 mNameLookupInsert.bindLong(3, lookupType); 4699 bindString(mNameLookupInsert, 4, name); 4700 mNameLookupInsert.executeInsert(); 4701 } 4702 4703 /** 4704 * Deletes all {@link Tables#NAME_LOOKUP} table rows associated with the specified data element. 4705 */ 4706 public void deleteNameLookup(long dataId) { 4707 if (mNameLookupDelete == null) { 4708 mNameLookupDelete = getWritableDatabase().compileStatement( 4709 "DELETE FROM " + Tables.NAME_LOOKUP + 4710 " WHERE " + NameLookupColumns.DATA_ID + "=?"); 4711 } 4712 mNameLookupDelete.bindLong(1, dataId); 4713 mNameLookupDelete.execute(); 4714 } 4715 4716 public String insertNameLookupForEmail(long rawContactId, long dataId, String email) { 4717 if (TextUtils.isEmpty(email)) { 4718 return null; 4719 } 4720 4721 String address = extractHandleFromEmailAddress(email); 4722 if (address == null) { 4723 return null; 4724 } 4725 4726 insertNameLookup(rawContactId, dataId, 4727 NameLookupType.EMAIL_BASED_NICKNAME, NameNormalizer.normalize(address)); 4728 return address; 4729 } 4730 4731 /** 4732 * Normalizes the nickname and inserts it in the name lookup table. 4733 */ 4734 public void insertNameLookupForNickname(long rawContactId, long dataId, String nickname) { 4735 if (TextUtils.isEmpty(nickname)) { 4736 return; 4737 } 4738 4739 insertNameLookup(rawContactId, dataId, 4740 NameLookupType.NICKNAME, NameNormalizer.normalize(nickname)); 4741 } 4742 4743 public void insertNameLookupForPhoneticName(long rawContactId, long dataId, String familyName, 4744 String middleName, String givenName) { 4745 mSb.setLength(0); 4746 if (familyName != null) { 4747 mSb.append(familyName.trim()); 4748 } 4749 if (middleName != null) { 4750 mSb.append(middleName.trim()); 4751 } 4752 if (givenName != null) { 4753 mSb.append(givenName.trim()); 4754 } 4755 4756 if (mSb.length() > 0) { 4757 insertNameLookup(rawContactId, dataId, NameLookupType.NAME_COLLATION_KEY, 4758 NameNormalizer.normalize(mSb.toString())); 4759 } 4760 } 4761 4762 /** 4763 * Performs a query and returns true if any Data item of the raw contact with the given 4764 * id and mimetype is marked as super-primary 4765 */ 4766 public boolean rawContactHasSuperPrimary(long rawContactId, long mimeTypeId) { 4767 final Cursor existsCursor = getReadableDatabase().rawQuery( 4768 "SELECT EXISTS(SELECT 1 FROM " + Tables.DATA + 4769 " WHERE " + Data.RAW_CONTACT_ID + "=?" + 4770 " AND " + DataColumns.MIMETYPE_ID + "=?" + 4771 " AND " + Data.IS_SUPER_PRIMARY + "<>0)", 4772 new String[] { String.valueOf(rawContactId), String.valueOf(mimeTypeId) }); 4773 try { 4774 if (!existsCursor.moveToFirst()) throw new IllegalStateException(); 4775 return existsCursor.getInt(0) != 0; 4776 } finally { 4777 existsCursor.close(); 4778 } 4779 } 4780 4781 public String getCurrentCountryIso() { 4782 return mCountryMonitor.getCountryIso(); 4783 } 4784 4785 /* package */ String querySearchIndexContentForTest(long contactId) { 4786 return DatabaseUtils.stringForQuery(getReadableDatabase(), 4787 "SELECT " + SearchIndexColumns.CONTENT + 4788 " FROM " + Tables.SEARCH_INDEX + 4789 " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", 4790 new String[] { String.valueOf(contactId) }); 4791 } 4792 4793 /* package */ String querySearchIndexTokensForTest(long contactId) { 4794 return DatabaseUtils.stringForQuery(getReadableDatabase(), 4795 "SELECT " + SearchIndexColumns.TOKENS + 4796 " FROM " + Tables.SEARCH_INDEX + 4797 " WHERE " + SearchIndexColumns.CONTACT_ID + "=CAST(? AS int)", 4798 new String[] { String.valueOf(contactId) }); 4799 } 4800} 4801