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