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 org.jetbrains.annotations.NonNls;
38 import java.io.BufferedReader;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.io.InputStreamReader;
42 import java.util.Locale;
44 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
45 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
47 public final class MLDB {
48 public static final String ACCOUNTS_TABLE = "accounts";
49 public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
50 public static final String OPT_TRANSACTION_LIST_STAMP = "transaction_list_last_update";
51 public static final String OPT_LAST_REFRESH = "last_refresh";
53 public static final String OPT_PROFILE_UUID = "profile_uuid";
54 private static MobileLedgerDatabase helperForReading, helperForWriting;
55 private static Application context;
56 private static void checkState() {
58 throw new IllegalStateException("First call init with a valid context");
60 public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
64 if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
65 return helperForReading.getReadableDatabase();
68 if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
69 return helperForWriting.getWritableDatabase();
72 public static SQLiteDatabase getReadableDatabase() {
73 return getDatabase(READ);
75 public static SQLiteDatabase getWritableDatabase() {
76 return getDatabase(WRITE);
78 static public int get_option_value(String name, int default_value) {
79 String s = get_option_value(name, String.valueOf(default_value));
81 return Integer.parseInt(s);
84 Log.d("db", "returning default int value of " + name, e);
88 static public long get_option_value(String name, long default_value) {
89 String s = get_option_value(name, String.valueOf(default_value));
91 return Long.parseLong(s);
94 Log.d("db", "returning default long value of " + name, e);
98 static public String get_option_value(String name, String default_value) {
99 Log.d("db", "about to fetch option " + name);
100 SQLiteDatabase db = getReadableDatabase();
101 try (Cursor cursor = db
102 .rawQuery("select value from options where name=?", new String[]{name}))
104 if (cursor.moveToFirst()) {
105 String result = cursor.getString(0);
107 if (result == null) result = default_value;
109 Log.d("db", "option " + name + "=" + result);
112 else return default_value;
114 catch (Exception e) {
115 Log.d("db", "returning default value for " + name, e);
116 return default_value;
119 static public void set_option_value(String name, String value) {
120 Log.d("db", "setting option " + name + "=" + value);
121 SQLiteDatabase db = getWritableDatabase();
122 db.execSQL("insert or replace into options(name, value) values(?, ?);",
123 new String[]{name, value});
125 static public void set_option_value(String name, long value) {
126 set_option_value(name, String.valueOf(value));
128 @TargetApi(Build.VERSION_CODES.N)
129 public static void hook_autocompletion_adapter(final Context context,
130 final AutoCompleteTextView view,
131 final String table, final String field) {
132 String[] from = {field};
133 int[] to = {android.R.id.text1};
134 SimpleCursorAdapter adapter =
135 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
137 adapter.setStringConversionColumn(1);
139 FilterQueryProvider provider = new FilterQueryProvider() {
141 public Cursor runQuery(CharSequence constraint) {
142 if (constraint == null) return null;
144 String str = constraint.toString().toUpperCase();
145 Log.d("autocompletion", "Looking for " + str);
146 String[] col_names = {FontsContract.Columns._ID, field};
147 MatrixCursor c = new MatrixCursor(col_names);
149 SQLiteDatabase db = MLDB.getReadableDatabase();
151 try (Cursor matches = db.rawQuery(String.format(
152 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
153 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
154 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " + "FROM %s " +
155 "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 2, 1;", field, field,
156 field, field, table, field), new String[]{str, str, str, str}))
159 while (matches.moveToNext()) {
160 String match = matches.getString(0);
161 int order = matches.getInt(1);
162 Log.d("autocompletion", String.format("match: %s |%d", match, order));
163 c.newRow().add(i++).add(match);
172 adapter.setFilterQueryProvider(provider);
174 view.setAdapter(adapter);
176 public static void init(Application context) {
177 MLDB.context = context;
179 public static void done() {
180 if (helperForReading != null)
181 helperForReading.close();
183 if ((helperForWriting != helperForReading) && (helperForWriting != null))
184 helperForWriting.close();
186 public enum DatabaseMode {READ, WRITE}
189 class MobileLedgerDatabase extends SQLiteOpenHelper implements AutoCloseable {
190 public static final String DB_NAME = "mobile-ledger.db";
191 public static final int LATEST_REVISION = 11;
193 private final Application mContext;
195 public MobileLedgerDatabase(Application context) {
196 super(context, DB_NAME, null, LATEST_REVISION);
197 Log.d("db", "creating helper instance");
199 super.setWriteAheadLoggingEnabled(true);
203 public void onCreate(SQLiteDatabase db) {
204 Log.d("db", "onCreate called");
205 onUpgrade(db, -1, LATEST_REVISION);
209 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
210 Log.d("db", "onUpgrade called");
211 for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
214 private void applyRevision(SQLiteDatabase db, int rev_no) {
215 final Resources rm = mContext.getResources();
216 String rev_file = String.format(Locale.US, "sql_%d", rev_no);
218 int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
220 throw new SQLException(String.format(Locale.US, "No resource for revision %d", rev_no));
221 db.beginTransaction();
222 try (InputStream res = rm.openRawResource(res_id)) {
223 Log.d("db", "Applying revision " + String.valueOf(rev_no));
224 InputStreamReader isr = new InputStreamReader(res);
225 BufferedReader reader = new BufferedReader(isr);
228 while ((line = reader.readLine()) != null) {
232 db.setTransactionSuccessful();
234 catch (IOException e) {
235 Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));