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.widget.AutoCompleteTextView;
33 import android.widget.FilterQueryProvider;
34 import android.widget.SimpleCursorAdapter;
36 import net.ktnx.mobileledger.model.Data;
38 import org.jetbrains.annotations.NonNls;
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;
46 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
47 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
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";
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() {
60 throw new IllegalStateException("First call init with a valid context");
62 public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
66 if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
67 return helperForReading.getReadableDatabase();
70 if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
71 return helperForWriting.getWritableDatabase();
74 public static SQLiteDatabase getReadableDatabase() {
75 return getDatabase(READ);
77 public static SQLiteDatabase getWritableDatabase() {
78 return getDatabase(WRITE);
80 static public int get_option_value(String name, int default_value) {
81 String s = get_option_value(name, String.valueOf(default_value));
83 return Integer.parseInt(s);
86 Log.d("db", "returning default int value of " + name, e);
90 static public long get_option_value(String name, long default_value) {
91 String s = get_option_value(name, String.valueOf(default_value));
93 return Long.parseLong(s);
96 Log.d("db", "returning default long value of " + name, e);
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}))
106 if (cursor.moveToFirst()) {
107 String result = cursor.getString(0);
109 if (result == null) result = default_value;
111 Log.d("db", "option " + name + "=" + result);
114 else return default_value;
116 catch (Exception e) {
117 Log.d("db", "returning default value for " + name, e);
118 return default_value;
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});
127 static public void set_option_value(String name, long value) {
128 set_option_value(name, value);
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,
140 adapter.setStringConversionColumn(1);
142 FilterQueryProvider provider = new FilterQueryProvider() {
144 public Cursor runQuery(CharSequence constraint) {
145 if (constraint == null) return null;
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);
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};
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};
172 Log.d("autocompletion", sql);
173 SQLiteDatabase db = MLDB.getReadableDatabase();
175 try (Cursor matches = db.rawQuery(sql, params)) {
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);
190 adapter.setFilterQueryProvider(provider);
192 view.setAdapter(adapter);
194 public static void init(Application context) {
195 MLDB.context = context;
197 public static void done() {
198 if (helperForReading != null) helperForReading.close();
200 if ((helperForWriting != helperForReading) && (helperForWriting != null))
201 helperForWriting.close();
204 public enum DatabaseMode {READ, WRITE}
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;
211 private final Application mContext;
213 public MobileLedgerDatabase(Application context) {
214 super(context, DB_NAME, null, LATEST_REVISION);
215 Log.d("db", "creating helper instance");
217 super.setWriteAheadLoggingEnabled(true);
221 public void onCreate(SQLiteDatabase db) {
222 Log.d("db", "onCreate called");
223 onUpgrade(db, -1, LATEST_REVISION);
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);
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);
236 int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
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);
247 while ((line = reader.readLine()) != null) {
248 if (line.startsWith("--")) {
252 if (line.isEmpty()) {
259 catch (Exception e) {
260 throw new RuntimeException(
261 String.format("Error applying revision %d, line %d", rev_no, line_no),
267 db.setTransactionSuccessful();
269 catch (IOException e) {
270 Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));