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 java.io.BufferedReader;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.InputStreamReader;
40 import java.util.Locale;
42 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
43 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
45 public final class MLDB {
46 public static final String ACCOUNTS_TABLE = "accounts";
47 public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
48 public static final String OPT_TRANSACTION_LIST_STAMP = "transaction_list_last_update";
49 public static final String OPT_LAST_REFRESH = "last_refresh";
50 private static MobileLedgerDatabase helperForReading, helperForWriting;
51 private static Application context;
52 private static void checkState() {
54 throw new IllegalStateException("First call init with a valid context");
56 public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
60 if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
61 return helperForReading.getReadableDatabase();
64 if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
65 return helperForWriting.getWritableDatabase();
68 public static SQLiteDatabase getReadableDatabase() {
69 return getDatabase(READ);
71 public static SQLiteDatabase getWritableDatabase() {
72 return getDatabase(WRITE);
74 static public int get_option_value(String name, int default_value) {
75 String s = get_option_value(name, String.valueOf(default_value));
77 return Integer.parseInt(s);
80 Log.d("db", "returning default int value of " + name, e);
84 static public long get_option_value(String name, long default_value) {
85 String s = get_option_value(name, String.valueOf(default_value));
87 return Long.parseLong(s);
90 Log.d("db", "returning default long value of " + name, e);
94 static public String get_option_value(String name, String default_value) {
95 Log.d("db", "about to fetch option " + name);
96 SQLiteDatabase db = getReadableDatabase();
97 try (Cursor cursor = db
98 .rawQuery("select value from options where name=?", new String[]{name}))
100 if (cursor.moveToFirst()) {
101 String result = cursor.getString(0);
103 if (result == null) result = default_value;
105 Log.d("db", "option " + name + "=" + result);
108 else return default_value;
110 catch (Exception e) {
111 Log.d("db", "returning default value for " + name, e);
112 return default_value;
115 static public void set_option_value(String name, String value) {
116 Log.d("db", "setting option " + name + "=" + value);
117 SQLiteDatabase db = getWritableDatabase();
118 db.execSQL("insert or replace into options(name, value) values(?, ?);",
119 new String[]{name, value});
121 static public void set_option_value(String name, long value) {
122 set_option_value(name, String.valueOf(value));
124 @TargetApi(Build.VERSION_CODES.N)
125 public static void hook_autocompletion_adapter(final Context context,
126 final AutoCompleteTextView view,
127 final String table, final String field) {
128 String[] from = {field};
129 int[] to = {android.R.id.text1};
130 SimpleCursorAdapter adapter =
131 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
133 adapter.setStringConversionColumn(1);
135 FilterQueryProvider provider = new FilterQueryProvider() {
137 public Cursor runQuery(CharSequence constraint) {
138 if (constraint == null) return null;
140 String str = constraint.toString().toUpperCase();
141 Log.d("autocompletion", "Looking for " + str);
142 String[] col_names = {FontsContract.Columns._ID, field};
143 MatrixCursor c = new MatrixCursor(col_names);
145 SQLiteDatabase db = MLDB.getReadableDatabase();
147 try (Cursor matches = db.rawQuery(String.format(
148 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
149 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
150 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " + "FROM %s " +
151 "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 2, 1;", field, field,
152 field, field, table, field), new String[]{str, str, str, str}))
155 while (matches.moveToNext()) {
156 String match = matches.getString(0);
157 int order = matches.getInt(1);
158 Log.d("autocompletion", String.format("match: %s |%d", match, order));
159 c.newRow().add(i++).add(match);
168 adapter.setFilterQueryProvider(provider);
170 view.setAdapter(adapter);
172 public static void init(Application context) {
173 MLDB.context = context;
175 public static void done() {
176 if (helperForReading != null)
177 helperForReading.close();
179 if ((helperForWriting != helperForReading) && (helperForWriting != null))
180 helperForWriting.close();
182 public enum DatabaseMode {READ, WRITE}
185 class MobileLedgerDatabase extends SQLiteOpenHelper implements AutoCloseable {
186 public static final String DB_NAME = "mobile-ledger.db";
187 public static final int LATEST_REVISION = 10;
189 private final Context mContext;
191 public MobileLedgerDatabase(Context context) {
192 super(context, DB_NAME, null, LATEST_REVISION);
193 Log.d("db", "creating helper instance");
195 super.setWriteAheadLoggingEnabled(true);
199 public void onCreate(SQLiteDatabase db) {
200 Log.d("db", "onCreate called");
201 onUpgrade(db, -1, LATEST_REVISION);
205 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
206 Log.d("db", "onUpgrade called");
207 for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
210 private void applyRevision(SQLiteDatabase db, int rev_no) {
211 final Resources rm = mContext.getResources();
212 String rev_file = String.format(Locale.US, "sql_%d", rev_no);
214 int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
216 throw new SQLException(String.format(Locale.US, "No resource for revision %d", rev_no));
217 db.beginTransaction();
218 try (InputStream res = rm.openRawResource(res_id)) {
219 Log.d("db", "Applying revision " + String.valueOf(rev_no));
220 InputStreamReader isr = new InputStreamReader(res);
221 BufferedReader reader = new BufferedReader(isr);
224 while ((line = reader.readLine()) != null) {
228 db.setTransactionSuccessful();
230 catch (IOException e) {
231 Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));