]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
42996c9f36bfe40fb09e8bbb46ec1f548b4267ac
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / utils / MLDB.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.utils;
19
20 import android.annotation.TargetApi;
21 import android.app.Application;
22 import android.content.Context;
23 import android.content.res.Resources;
24 import android.database.Cursor;
25 import android.database.MatrixCursor;
26 import android.database.SQLException;
27 import android.database.sqlite.SQLiteDatabase;
28 import android.database.sqlite.SQLiteOpenHelper;
29 import android.os.Build;
30 import android.provider.FontsContract;
31 import android.util.Log;
32 import android.view.View;
33 import android.widget.AutoCompleteTextView;
34 import android.widget.FilterQueryProvider;
35 import android.widget.SimpleCursorAdapter;
36
37 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
38 import net.ktnx.mobileledger.model.Data;
39
40 import org.jetbrains.annotations.NonNls;
41
42 import java.io.BufferedReader;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.InputStreamReader;
46 import java.util.Locale;
47
48 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
49 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
50
51 public final class MLDB {
52     public static final String ACCOUNTS_TABLE = "accounts";
53     public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
54     public static final String OPT_LAST_SCRAPE = "last_scrape";
55     @NonNls
56     public static final String OPT_PROFILE_UUID = "profile_uuid";
57     private static final String NO_PROFILE = "-";
58     private static MobileLedgerDatabase helperForReading, helperForWriting;
59     private static Application context;
60     private static void checkState() {
61         if (context == null)
62             throw new IllegalStateException("First call init with a valid context");
63     }
64     public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
65         checkState();
66
67         SQLiteDatabase db;
68
69         if (mode == READ) {
70             if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
71             db = helperForReading.getReadableDatabase();
72         }
73         else {
74             if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
75             db = helperForWriting.getWritableDatabase();
76         }
77
78         db.execSQL("pragma case_sensitive_like=ON;");
79         return db;
80     }
81     public static SQLiteDatabase getReadableDatabase() {
82         return getDatabase(READ);
83     }
84     public static SQLiteDatabase getWritableDatabase() {
85         return getDatabase(WRITE);
86     }
87     static public int getIntOption(String name, int default_value) {
88         String s = getOption(name, String.valueOf(default_value));
89         try {
90             return Integer.parseInt(s);
91         }
92         catch (Exception e) {
93             Log.d("db", "returning default int value of " + name, e);
94             return default_value;
95         }
96     }
97     static public long getLongOption(String name, long default_value) {
98         String s = getOption(name, String.valueOf(default_value));
99         try {
100             return Long.parseLong(s);
101         }
102         catch (Exception e) {
103             Log.d("db", "returning default long value of " + name, e);
104             return default_value;
105         }
106     }
107     static public String getOption(String name, String default_value) {
108         Log.d("db", "about to fetch option " + name);
109         SQLiteDatabase db = getReadableDatabase();
110         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
111                 new String[]{NO_PROFILE, name}))
112         {
113             if (cursor.moveToFirst()) {
114                 String result = cursor.getString(0);
115
116                 if (result == null) result = default_value;
117
118                 Log.d("db", "option " + name + "=" + result);
119                 return result;
120             }
121             else return default_value;
122         }
123         catch (Exception e) {
124             Log.d("db", "returning default value for " + name, e);
125             return default_value;
126         }
127     }
128     static public void setOption(String name, String value) {
129         Log.d("option", String.format("%s := %s", name, value));
130         SQLiteDatabase db = MLDB.getWritableDatabase();
131         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
132                 new String[]{NO_PROFILE, name, value});
133     }
134     static public void setLongOption(String name, long value) {
135         setOption(name, String.valueOf(value));
136     }
137     @TargetApi(Build.VERSION_CODES.N)
138     public static void hookAutocompletionAdapter(final Context context,
139                                                  final AutoCompleteTextView view,
140                                                  final String table, final String field,
141                                                  final boolean profileSpecific) {
142         hookAutocompletionAdapter(context, view, table, field, profileSpecific, null, null);
143     }
144     @TargetApi(Build.VERSION_CODES.N)
145     public static void hookAutocompletionAdapter(final Context context,
146                                                  final AutoCompleteTextView view,
147                                                  final String table, final String field,
148                                                  final boolean profileSpecific, final View nextView,
149                                                  final DescriptionSelectedCallback callback) {
150         String[] from = {field};
151         int[] to = {android.R.id.text1};
152         SimpleCursorAdapter adapter =
153                 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
154                         from, to, 0);
155         adapter.setStringConversionColumn(1);
156
157         FilterQueryProvider provider = constraint -> {
158             if (constraint == null) return null;
159
160             String str = constraint.toString().toUpperCase();
161             Log.d("autocompletion", "Looking for " + str);
162             String[] col_names = {FontsContract.Columns._ID, field};
163             MatrixCursor c = new MatrixCursor(col_names);
164
165             String sql;
166             String[] params;
167             if (profileSpecific) {
168                 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
169                                     "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
170                                     "WHEN %s_upper LIKE '%% '||?||'%%' then 3 else 9 end " +
171                                     "FROM %s " +
172                                     "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
173                                     "ORDER BY 2, 1;", field, field, field, field, table, field);
174                 params = new String[]{str, str, str, Data.profile.get().getUuid(), str};
175             }
176             else {
177                 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
178                                     "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
179                                     "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
180                                     "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
181                                     "ORDER BY 2, 1;", field, field, field, field, table, field);
182                 params = new String[]{str, str, str, str};
183             }
184             Log.d("autocompletion", sql);
185             SQLiteDatabase db = MLDB.getReadableDatabase();
186
187             try (Cursor matches = db.rawQuery(sql, params)) {
188                 int i = 0;
189                 while (matches.moveToNext()) {
190                     String match = matches.getString(0);
191                     int order = matches.getInt(1);
192                     Log.d("autocompletion", String.format("match: %s |%d", match, order));
193                     c.newRow().add(i++).add(match);
194                 }
195             }
196
197             return c;
198
199         };
200
201         adapter.setFilterQueryProvider(provider);
202
203         view.setAdapter(adapter);
204
205         if (nextView != null) {
206             view.setOnItemClickListener((parent, itemView, position, id) -> {
207                 nextView.requestFocus(View.FOCUS_FORWARD);
208                 if (callback != null) {
209                     callback.descriptionSelected(String.valueOf(view.getText()));
210                 }
211             });
212         }
213     }
214     public static void init(Application context) {
215         MLDB.context = context;
216     }
217     public static void done() {
218         if (helperForReading != null) helperForReading.close();
219
220         if ((helperForWriting != helperForReading) && (helperForWriting != null))
221             helperForWriting.close();
222     }
223
224     public enum DatabaseMode {READ, WRITE}
225 }
226
227 class MobileLedgerDatabase extends SQLiteOpenHelper implements AutoCloseable {
228     public static final String DB_NAME = "MoLe.db";
229     public static final int LATEST_REVISION = 20;
230
231     private final Application mContext;
232
233     public MobileLedgerDatabase(Application context) {
234         super(context, DB_NAME, null, LATEST_REVISION);
235         Log.d("db", "creating helper instance");
236         mContext = context;
237         super.setWriteAheadLoggingEnabled(true);
238     }
239
240     @Override
241     public void onCreate(SQLiteDatabase db) {
242         Log.d("db", "onCreate called");
243         onUpgrade(db, -1, LATEST_REVISION);
244     }
245
246     @Override
247     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
248         Log.d("db", "onUpgrade called");
249         for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
250     }
251
252     private void applyRevision(SQLiteDatabase db, int rev_no) {
253         final Resources rm = mContext.getResources();
254         String rev_file = String.format(Locale.US, "sql_%d", rev_no);
255
256         int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
257         if (res_id == 0)
258             throw new SQLException(String.format(Locale.US, "No resource for revision %d", rev_no));
259         db.beginTransaction();
260         try (InputStream res = rm.openRawResource(res_id)) {
261             Log.d("db", "Applying revision " + String.valueOf(rev_no));
262             InputStreamReader isr = new InputStreamReader(res);
263             BufferedReader reader = new BufferedReader(isr);
264
265             String line;
266             int line_no = 1;
267             while ((line = reader.readLine()) != null) {
268                 if (line.startsWith("--")) {
269                     line_no++;
270                     continue;
271                 }
272                 if (line.isEmpty()) {
273                     line_no++;
274                     continue;
275                 }
276                 try {
277                     db.execSQL(line);
278                 }
279                 catch (Exception e) {
280                     throw new RuntimeException(
281                             String.format("Error applying revision %d, line %d", rev_no, line_no),
282                             e);
283                 }
284                 line_no++;
285             }
286
287             db.setTransactionSuccessful();
288         }
289         catch (IOException e) {
290             Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));
291             e.printStackTrace();
292         }
293         finally {
294             db.endTransaction();
295         }
296     }
297 }