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