-
Notifications
You must be signed in to change notification settings - Fork 76
/
DatabaseManager.java
270 lines (224 loc) · 8.35 KB
/
DatabaseManager.java
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
/*
* Copyright 2017 Gabor Varadi
*
* 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.zhuinden.simplestackexamplemvvm.core.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.zhuinden.simplestackexamplemvvm.core.scheduler.BackgroundScheduler;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public final class DatabaseManager
extends SQLiteOpenHelper {
public interface Table {
String getId(Object element);
String getIdFieldName();
String getTableName();
Fields[] getFields();
String[] getAllQueryFields();
List<List<Fields>> getIndexedFields();
void onCreate(SQLiteDatabase database);
void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion);
}
public static final class Fields {
private String fieldName;
private String fieldType;
private String fieldAdditional;
public Fields(String fieldName, String fieldType, String fieldAdditional) {
this.fieldName = fieldName;
this.fieldType = fieldType;
this.fieldAdditional = fieldAdditional;
}
public String getFieldName() {
return fieldName;
}
public String getFieldType() {
return fieldType;
}
public String getFieldAdditional() {
return fieldAdditional;
}
@Override
public String toString() {
return fieldName;
}
}
public interface QueryDefinition {
Cursor query(SQLiteDatabase database, Table table);
}
private static final String DATABASE_NAME = "tasks.db";
private static final int DATABASE_VERSION = 1;
private final List<Table> tables;
private final BackgroundScheduler backgroundScheduler;
private SQLiteDatabase database;
@Inject
public DatabaseManager(Context appContext, List<Table> tables, BackgroundScheduler backgroundScheduler) {
super(appContext, DATABASE_NAME, null, DATABASE_VERSION);
this.tables = tables;
this.backgroundScheduler = backgroundScheduler;
this.database = getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase database) {
for(Table table : tables) {
table.onCreate(database);
}
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
for(Table table : tables) {
table.onUpgrade(database, oldVersion, newVersion);
}
}
public SQLiteDatabase getDatabase() {
return this.database;
}
public interface Transaction {
void execute(SQLiteDatabase sqLiteDatabase);
}
public interface Mapper<T> {
T from(Cursor cursor);
ContentValues from(ContentValues contentValues, T t);
}
public void executeTransaction(Transaction transaction) {
try {
database.beginTransaction();
transaction.execute(database);
database.setTransactionSuccessful();
} finally {
if(database.inTransaction()) {
database.endTransaction();
}
}
}
private <T> List<T> collectObjectFromCursor(Mapper<T> mapper, Cursor cursor) {
List<T> list = new LinkedList<>();
if(cursor.moveToFirst()) {
do {
T object = mapper.from(cursor);
list.add(object);
} while(cursor.moveToNext());
}
return Collections.unmodifiableList(new ArrayList<>(list));
}
public <T> List<T> findAll(Table table, Mapper<T> mapper) {
return findAll(table,
mapper,
QueryBuilder.of(table).buildDefinition()
);
}
public <T> List<T> findAll(Table table, Mapper<T> mapper, QueryDefinition queryDefinition) {
Cursor cursor = queryDefinition.query(database, table);
List<T> list = collectObjectFromCursor(mapper, cursor);
cursor.close();
return list;
}
public <T> T findOne(Table table, Mapper<T> mapper, QueryDefinition queryDefinition) {
List<T> list = findAll(table, mapper, queryDefinition);
return list.isEmpty() ? null : list.get(0);
}
public <T> void insert(Table table, Mapper<T> mapper, T element) {
insert(table, mapper, Collections.singletonList(element));
// calls to other insert
}
public <T> void insert(Table table, Mapper<T> mapper, List<T> elements) {
executeTransaction(sqLiteDatabase -> {
ContentValues contentValues = new ContentValues();
for(T t : elements) {
contentValues = mapper.from(contentValues, t);
sqLiteDatabase.insertWithOnConflict(table.getTableName(),
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE);
}
});
refresh(table);
}
public <T> void delete(Table table, T element) {
delete(table, Collections.singletonList(element));;
// calls to other delete
}
public <T> void delete(Table table, List<T> elements) {
executeTransaction(sqLiteDatabase -> {
for(T t : elements) {
sqLiteDatabase.delete(table.getTableName(),
table.getIdFieldName() + " = ?",
new String[]{table.getId(t)});
}
});
refresh(table);
}
public void deleteAll(Table table) {
executeTransaction(sqLiteDatabase -> sqLiteDatabase.delete(table.getTableName(), null, null));
refresh(table);
}
// Experimental. This allows for reactivity.
private List<WeakReference<LiveResults<?>>> liveDatas = Collections.synchronizedList(new LinkedList<>());
public <T> LiveResults<T> findAllWithChanges(Table table, Mapper<T> mapper, QueryDefinition queryDefinition) {
return new LiveResults<>(backgroundScheduler, this, table, mapper, queryDefinition);
}
void addLiveResults(LiveResults<?> liveResults) {
synchronized(this) {
this.liveDatas.add(new WeakReference<>(liveResults));
}
}
public void refresh() {
synchronized(this) {
Iterator<WeakReference<LiveResults<?>>> iterator = liveDatas.iterator();
while(iterator.hasNext()) {
WeakReference<LiveResults<?>> weakReference = iterator.next();
LiveResults<?> liveData = weakReference.get();
if(liveData == null) {
iterator.remove();
} else {
liveData.refresh();
}
}
}
}
public void refresh(Table... tables) {
synchronized(this) {
Iterator<WeakReference<LiveResults<?>>> iterator = liveDatas.iterator();
while(iterator.hasNext()) {
WeakReference<LiveResults<?>> weakReference = iterator.next();
LiveResults<?> liveData = weakReference.get();
if(liveData == null) {
iterator.remove();
} else {
boolean isInTables = false;
Table table = liveData.table;
for(Table currentTable: tables) {
if(currentTable == table) {
isInTables = true;
break;
}
}
if(isInTables) {
liveData.refresh();
}
}
}
}
}
}