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