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.
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.
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/>.
18 package net.ktnx.mobileledger.utils;
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;
37 import net.ktnx.mobileledger.model.Data;
39 import org.jetbrains.annotations.NonNls;
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;
47 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
48 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
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";
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() {
61 throw new IllegalStateException("First call init with a valid context");
63 public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
67 if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
68 return helperForReading.getReadableDatabase();
71 if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
72 return helperForWriting.getWritableDatabase();
75 public static SQLiteDatabase getReadableDatabase() {
76 return getDatabase(READ);
78 public static SQLiteDatabase getWritableDatabase() {
79 return getDatabase(WRITE);
81 static public int getIntOption(String name, int default_value) {
82 String s = getOption(name, String.valueOf(default_value));
84 return Integer.parseInt(s);
87 Log.d("db", "returning default int value of " + name, e);
91 static public long getLongOption(String name, long default_value) {
92 String s = getOption(name, String.valueOf(default_value));
94 return Long.parseLong(s);
97 Log.d("db", "returning default long value of " + name, e);
101 static public String getOption(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}))
107 if (cursor.moveToFirst()) {
108 String result = cursor.getString(0);
110 if (result == null) result = default_value;
112 Log.d("db", "option " + name + "=" + result);
115 else return default_value;
117 catch (Exception e) {
118 Log.d("db", "returning default value for " + name, e);
119 return default_value;
122 static public void setOption(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});
128 static public void setLongOption(String name, long value) {
129 setOption(name, String.valueOf(value));
131 @TargetApi(Build.VERSION_CODES.N)
132 public static void hookAutocompletionAdapter(final Context context,
133 final AutoCompleteTextView view,
134 final String table, final String field,
135 final boolean profileSpecific) {
136 hookAutocompletionAdapter(context, view, table, field, profileSpecific, null);
138 @TargetApi(Build.VERSION_CODES.N)
139 public static void hookAutocompletionAdapter(final Context context,
140 final AutoCompleteTextView view,
141 final String table, final String field,
142 final boolean profileSpecific,
143 final View nextView) {
144 String[] from = {field};
145 int[] to = {android.R.id.text1};
146 SimpleCursorAdapter adapter =
147 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
149 adapter.setStringConversionColumn(1);
151 FilterQueryProvider provider = constraint -> {
152 if (constraint == null) return null;
154 String str = constraint.toString().toUpperCase();
155 Log.d("autocompletion", "Looking for " + str);
156 String[] col_names = {FontsContract.Columns._ID, field};
157 MatrixCursor c = new MatrixCursor(col_names);
161 if (profileSpecific) {
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 " +
166 "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
167 "ORDER BY 2, 1;", field, field, field, field, table, field);
168 params = new String[]{str, str, str, Data.profile.get().getUuid(), str};
171 sql = String.format("SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
172 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
173 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
174 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
175 "ORDER BY 2, 1;", field, field, field, field, table, field);
176 params = new String[]{str, str, str, str};
178 Log.d("autocompletion", sql);
179 SQLiteDatabase db = MLDB.getReadableDatabase();
181 try (Cursor matches = db.rawQuery(sql, params)) {
183 while (matches.moveToNext()) {
184 String match = matches.getString(0);
185 int order = matches.getInt(1);
186 Log.d("autocompletion", String.format("match: %s |%d", match, order));
187 c.newRow().add(i++).add(match);
195 adapter.setFilterQueryProvider(provider);
197 view.setAdapter(adapter);
199 if (nextView != null) {
200 view.setOnItemClickListener((parent, itemView, position, id) -> {
201 nextView.requestFocus(View.FOCUS_FORWARD);
205 public static void init(Application context) {
206 MLDB.context = context;
208 public static void done() {
209 if (helperForReading != null) helperForReading.close();
211 if ((helperForWriting != helperForReading) && (helperForWriting != null))
212 helperForWriting.close();
215 public enum DatabaseMode {READ, WRITE}
218 class MobileLedgerDatabase extends SQLiteOpenHelper implements AutoCloseable {
219 public static final String DB_NAME = "mobile-ledger.db";
220 public static final int LATEST_REVISION = 17;
222 private final Application mContext;
224 public MobileLedgerDatabase(Application context) {
225 super(context, DB_NAME, null, LATEST_REVISION);
226 Log.d("db", "creating helper instance");
228 super.setWriteAheadLoggingEnabled(true);
232 public void onCreate(SQLiteDatabase db) {
233 Log.d("db", "onCreate called");
234 onUpgrade(db, -1, LATEST_REVISION);
238 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
239 Log.d("db", "onUpgrade called");
240 for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
243 private void applyRevision(SQLiteDatabase db, int rev_no) {
244 final Resources rm = mContext.getResources();
245 String rev_file = String.format(Locale.US, "sql_%d", rev_no);
247 int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
249 throw new SQLException(String.format(Locale.US, "No resource for revision %d", rev_no));
250 db.beginTransaction();
251 try (InputStream res = rm.openRawResource(res_id)) {
252 Log.d("db", "Applying revision " + String.valueOf(rev_no));
253 InputStreamReader isr = new InputStreamReader(res);
254 BufferedReader reader = new BufferedReader(isr);
258 while ((line = reader.readLine()) != null) {
259 if (line.startsWith("--")) {
263 if (line.isEmpty()) {
270 catch (Exception e) {
271 throw new RuntimeException(
272 String.format("Error applying revision %d, line %d", rev_no, line_no),
278 db.setTransactionSuccessful();
280 catch (IOException e) {
281 Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));