summaryrefslogtreecommitdiff
path: root/java/com/android/dialer/speeddial/database/SpeedDialEntryDatabaseHelper.java
blob: 7c823bd63ccce04cbaca3b61b663a02a62a4e9b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.dialer.speeddial.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import com.android.dialer.common.Assert;
import com.android.dialer.common.database.Selection;
import com.android.dialer.speeddial.database.SpeedDialEntry.Channel;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;

/**
 * {@link SpeedDialEntryDao} implemented as an SQLite database.
 *
 * @see SpeedDialEntryDao
 */
public final class SpeedDialEntryDatabaseHelper extends SQLiteOpenHelper
    implements SpeedDialEntryDao {

  private static final int DATABASE_VERSION = 1;
  private static final String DATABASE_NAME = "CPSpeedDialEntry";

  // Column names
  private static final String TABLE_NAME = "speed_dial_entries";
  private static final String ID = "id";
  private static final String CONTACT_ID = "contact_id";
  private static final String LOOKUP_KEY = "lookup_key";
  private static final String PHONE_NUMBER = "phone_number";
  private static final String PHONE_LABEL = "phone_label";
  private static final String PHONE_TECHNOLOGY = "phone_technology";

  // Column positions
  private static final int POSITION_ID = 0;
  private static final int POSITION_CONTACT_ID = 1;
  private static final int POSITION_LOOKUP_KEY = 2;
  private static final int POSITION_PHONE_NUMBER = 3;
  private static final int POSITION_PHONE_LABEL = 4;
  private static final int POSITION_PHONE_TECHNOLOGY = 5;

  // Create Table Query
  private static final String CREATE_TABLE_SQL =
      "create table if not exists "
          + TABLE_NAME
          + " ("
          + (ID + " integer primary key, ")
          + (CONTACT_ID + " integer, ")
          + (LOOKUP_KEY + " text, ")
          + (PHONE_NUMBER + " text, ")
          + (PHONE_LABEL + " text, ")
          + (PHONE_TECHNOLOGY + " integer ")
          + ");";

  private static final String DELETE_TABLE_SQL = "drop table if exists " + TABLE_NAME;

  public SpeedDialEntryDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_SQL);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO(calderwoodra): handle upgrades more elegantly
    db.execSQL(DELETE_TABLE_SQL);
    this.onCreate(db);
  }

  @Override
  public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO(calderwoodra): handle upgrades more elegantly
    this.onUpgrade(db, oldVersion, newVersion);
  }

  @Override
  public ImmutableList<SpeedDialEntry> getAllEntries() {
    List<SpeedDialEntry> entries = new ArrayList<>();

    String query = "SELECT * FROM " + TABLE_NAME;
    try (SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null)) {
      cursor.moveToPosition(-1);
      while (cursor.moveToNext()) {
        String number = cursor.getString(POSITION_PHONE_NUMBER);
        Channel channel = null;
        if (!TextUtils.isEmpty(number)) {
          channel =
              Channel.builder()
                  .setNumber(number)
                  .setLabel(cursor.getString(POSITION_PHONE_LABEL))
                  .setTechnology(cursor.getInt(POSITION_PHONE_TECHNOLOGY))
                  .build();
        }

        SpeedDialEntry entry =
            SpeedDialEntry.builder()
                .setDefaultChannel(channel)
                .setContactId(cursor.getLong(POSITION_CONTACT_ID))
                .setLookupKey(cursor.getString(POSITION_LOOKUP_KEY))
                .setId(cursor.getLong(POSITION_ID))
                .build();
        entries.add(entry);
      }
    }
    return ImmutableList.copyOf(entries);
  }

  @Override
  public void insert(ImmutableList<SpeedDialEntry> entries) {
    if (entries.isEmpty()) {
      return;
    }

    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
      insert(db, entries);
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
      db.close();
    }
  }

  private void insert(SQLiteDatabase writeableDatabase, ImmutableList<SpeedDialEntry> entries) {
    for (SpeedDialEntry entry : entries) {
      Assert.checkArgument(entry.id() == null);
      if (writeableDatabase.insert(TABLE_NAME, null, buildContentValuesWithoutId(entry)) == -1L) {
        throw Assert.createUnsupportedOperationFailException(
            "Attempted to insert a row that already exists.");
      }
    }
  }

  @Override
  public long insert(SpeedDialEntry entry) {
    long updateRowId;
    try (SQLiteDatabase db = getWritableDatabase()) {
      updateRowId = db.insert(TABLE_NAME, null, buildContentValuesWithoutId(entry));
    }
    if (updateRowId == -1) {
      throw Assert.createUnsupportedOperationFailException(
          "Attempted to insert a row that already exists.");
    }
    return updateRowId;
  }

  @Override
  public void update(ImmutableList<SpeedDialEntry> entries) {
    if (entries.isEmpty()) {
      return;
    }

    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
      update(db, entries);
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
      db.close();
    }
  }

  private void update(SQLiteDatabase writeableDatabase, ImmutableList<SpeedDialEntry> entries) {
    for (SpeedDialEntry entry : entries) {
      int count =
          writeableDatabase.update(
              TABLE_NAME,
              buildContentValuesWithId(entry),
              ID + " = ?",
              new String[] {Long.toString(entry.id())});
      if (count != 1) {
        throw Assert.createUnsupportedOperationFailException(
            "Attempted to update an undetermined number of rows: " + count);
      }
    }
  }

  private ContentValues buildContentValuesWithId(SpeedDialEntry entry) {
    return buildContentValues(entry, true);
  }

  private ContentValues buildContentValuesWithoutId(SpeedDialEntry entry) {
    return buildContentValues(entry, false);
  }

  private ContentValues buildContentValues(SpeedDialEntry entry, boolean includeId) {
    ContentValues values = new ContentValues();
    if (includeId) {
      values.put(ID, entry.id());
    }
    values.put(CONTACT_ID, entry.contactId());
    values.put(LOOKUP_KEY, entry.lookupKey());
    if (entry.defaultChannel() != null) {
      values.put(PHONE_NUMBER, entry.defaultChannel().number());
      values.put(PHONE_LABEL, entry.defaultChannel().label());
      values.put(PHONE_TECHNOLOGY, entry.defaultChannel().technology());
    }
    return values;
  }

  @Override
  public void delete(ImmutableList<Long> ids) {
    if (ids.isEmpty()) {
      return;
    }

    try (SQLiteDatabase db = getWritableDatabase()) {
      delete(db, ids);
    }
  }

  private void delete(SQLiteDatabase writeableDatabase, ImmutableList<Long> ids) {
    List<String> idStrings = new ArrayList<>();
    for (Long id : ids) {
      idStrings.add(Long.toString(id));
    }

    Selection selection = Selection.builder().and(Selection.column(ID).in(idStrings)).build();
    int count =
        writeableDatabase.delete(
            TABLE_NAME, selection.getSelection(), selection.getSelectionArgs());
    if (count != ids.size()) {
      throw Assert.createUnsupportedOperationFailException(
          "Attempted to delete an undetermined number of rows: " + count);
    }
  }

  @Override
  public void insertUpdateAndDelete(
      ImmutableList<SpeedDialEntry> entriesToInsert,
      ImmutableList<SpeedDialEntry> entriesToUpdate,
      ImmutableList<Long> entriesToDelete) {
    if (entriesToInsert.isEmpty() && entriesToUpdate.isEmpty() && entriesToDelete.isEmpty()) {
      return;
    }
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
      insert(db, entriesToInsert);
      update(db, entriesToUpdate);
      delete(db, entriesToDelete);
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
      db.close();
    }
  }

  @Override
  public void deleteAll() {
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
      // Passing null into where clause will delete all rows
      db.delete(TABLE_NAME, /* whereClause=*/ null, null);
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
      db.close();
    }
  }
}