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