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