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