]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
add color setting to profile data
[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         if (mode == READ) {
68             if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
69             return helperForReading.getReadableDatabase();
70         }
71         else {
72             if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
73             return helperForWriting.getWritableDatabase();
74         }
75     }
76     public static SQLiteDatabase getReadableDatabase() {
77         return getDatabase(READ);
78     }
79     public static SQLiteDatabase getWritableDatabase() {
80         return getDatabase(WRITE);
81     }
82     static public int getIntOption(String name, int default_value) {
83         String s = getOption(name, String.valueOf(default_value));
84         try {
85             return Integer.parseInt(s);
86         }
87         catch (Exception e) {
88             Log.d("db", "returning default int value of " + name, e);
89             return default_value;
90         }
91     }
92     static public long getLongOption(String name, long default_value) {
93         String s = getOption(name, String.valueOf(default_value));
94         try {
95             return Long.parseLong(s);
96         }
97         catch (Exception e) {
98             Log.d("db", "returning default long value of " + name, e);
99             return default_value;
100         }
101     }
102     static public String getOption(String name, String default_value) {
103         Log.d("db", "about to fetch option " + name);
104         SQLiteDatabase db = getReadableDatabase();
105         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
106                 new String[]{NO_PROFILE, name}))
107         {
108             if (cursor.moveToFirst()) {
109                 String result = cursor.getString(0);
110
111                 if (result == null) result = default_value;
112
113                 Log.d("db", "option " + name + "=" + result);
114                 return result;
115             }
116             else return default_value;
117         }
118         catch (Exception e) {
119             Log.d("db", "returning default value for " + name, e);
120             return default_value;
121         }
122     }
123     static public void setOption(String name, String value) {
124         Log.d("option", String.format("%s := %s", name, value));
125         SQLiteDatabase db = MLDB.getWritableDatabase();
126         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
127                 new String[]{NO_PROFILE, name, value});
128     }
129     static public void setLongOption(String name, long value) {
130         setOption(name, String.valueOf(value));
131     }
132     @TargetApi(Build.VERSION_CODES.N)
133     public static void hookAutocompletionAdapter(final Context context,
134                                                  final AutoCompleteTextView view,
135                                                  final String table, final String field,
136                                                  final boolean profileSpecific) {
137         hookAutocompletionAdapter(context, view, table, field, profileSpecific, null, null);
138     }
139     @TargetApi(Build.VERSION_CODES.N)
140     public static void hookAutocompletionAdapter(final Context context,
141                                                  final AutoCompleteTextView view,
142                                                  final String table, final String field,
143                                                  final boolean profileSpecific,
144                                                  final View nextView,
145                                                  final DescriptionSelectedCallback callback) {
146         String[] from = {field};
147         int[] to = {android.R.id.text1};
148         SimpleCursorAdapter adapter =
149                 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
150                         from, to, 0);
151         adapter.setStringConversionColumn(1);
152
153         FilterQueryProvider provider = constraint -> {
154             if (constraint == null) return null;
155
156             String str = constraint.toString().toUpperCase();
157             Log.d("autocompletion", "Looking for " + str);
158             String[] col_names = {FontsContract.Columns._ID, field};
159             MatrixCursor c = new MatrixCursor(col_names);
160
161             String sql;
162             String[] params;
163             if (profileSpecific) {
164                 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
165                                     "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
166                                     "WHEN %s_upper LIKE '%% '||?||'%%' then 3 else 9 end " +
167                                     "FROM %s " +
168                                     "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
169                                     "ORDER BY 2, 1;", field, field, field, field, table, field);
170                 params = new String[]{str, str, str, Data.profile.get().getUuid(), str};
171             }
172             else {
173                 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
174                                     "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
175                                     "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
176                                     "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
177                                     "ORDER BY 2, 1;", field, field, field, field, table, field);
178                 params = new String[]{str, str, str, str};
179             }
180             Log.d("autocompletion", sql);
181             SQLiteDatabase db = MLDB.getReadableDatabase();
182
183             try (Cursor matches = db.rawQuery(sql, params)) {
184                 int i = 0;
185                 while (matches.moveToNext()) {
186                     String match = matches.getString(0);
187                     int order = matches.getInt(1);
188                     Log.d("autocompletion", String.format("match: %s |%d", match, order));
189                     c.newRow().add(i++).add(match);
190                 }
191             }
192
193             return c;
194
195         };
196
197         adapter.setFilterQueryProvider(provider);
198
199         view.setAdapter(adapter);
200
201         if (nextView != null) {
202             view.setOnItemClickListener((parent, itemView, position, id) -> {
203                 nextView.requestFocus(View.FOCUS_FORWARD);
204                 if (callback != null) {
205                     callback.descriptionSelected(String.valueOf(view.getText()));
206                 }
207             });
208         }
209     }
210     public static void init(Application context) {
211         MLDB.context = context;
212     }
213     public static void done() {
214         if (helperForReading != null) helperForReading.close();
215
216         if ((helperForWriting != helperForReading) && (helperForWriting != null))
217             helperForWriting.close();
218     }
219
220     public enum DatabaseMode {READ, WRITE}
221 }
222
223 class MobileLedgerDatabase extends SQLiteOpenHelper implements AutoCloseable {
224     public static final String DB_NAME = "MoLe.db";
225     public static final int LATEST_REVISION = 18;
226
227     private final Application mContext;
228
229     public MobileLedgerDatabase(Application context) {
230         super(context, DB_NAME, null, LATEST_REVISION);
231         Log.d("db", "creating helper instance");
232         mContext = context;
233         super.setWriteAheadLoggingEnabled(true);
234     }
235
236     @Override
237     public void onCreate(SQLiteDatabase db) {
238         Log.d("db", "onCreate called");
239         onUpgrade(db, -1, LATEST_REVISION);
240     }
241
242     @Override
243     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
244         Log.d("db", "onUpgrade called");
245         for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
246     }
247
248     private void applyRevision(SQLiteDatabase db, int rev_no) {
249         final Resources rm = mContext.getResources();
250         String rev_file = String.format(Locale.US, "sql_%d", rev_no);
251
252         int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
253         if (res_id == 0)
254             throw new SQLException(String.format(Locale.US, "No resource for revision %d", rev_no));
255         db.beginTransaction();
256         try (InputStream res = rm.openRawResource(res_id)) {
257             Log.d("db", "Applying revision " + String.valueOf(rev_no));
258             InputStreamReader isr = new InputStreamReader(res);
259             BufferedReader reader = new BufferedReader(isr);
260
261             String line;
262             int line_no = 1;
263             while ((line = reader.readLine()) != null) {
264                 if (line.startsWith("--")) {
265                     line_no++;
266                     continue;
267                 }
268                 if (line.isEmpty()) {
269                     line_no++;
270                     continue;
271                 }
272                 try {
273                     db.execSQL(line);
274                 }
275                 catch (Exception e) {
276                     throw new RuntimeException(
277                             String.format("Error applying revision %d, line %d", rev_no, line_no),
278                             e);
279                 }
280                 line_no++;
281             }
282
283             db.setTransactionSuccessful();
284         }
285         catch (IOException e) {
286             Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));
287             e.printStackTrace();
288         }
289         finally {
290             db.endTransaction();
291         }
292     }
293 }