]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
MLDB: store the application instance in the context variable
[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 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.
8  *
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.
13  *
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/>.
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.widget.AutoCompleteTextView;
33 import android.widget.FilterQueryProvider;
34 import android.widget.SimpleCursorAdapter;
35
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;
41
42 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
43 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
44
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() {
53         if (context == null)
54             throw new IllegalStateException("First call init with a valid context");
55     }
56     public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
57         checkState();
58
59         if (mode == READ) {
60             if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
61             return helperForReading.getReadableDatabase();
62         }
63         else {
64             if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
65             return helperForWriting.getWritableDatabase();
66         }
67     }
68     public static SQLiteDatabase getReadableDatabase() {
69         return getDatabase(READ);
70     }
71     public static SQLiteDatabase getWritableDatabase() {
72         return getDatabase(WRITE);
73     }
74     static public int get_option_value(String name, int default_value) {
75         String s = get_option_value(name, String.valueOf(default_value));
76         try {
77             return Integer.parseInt(s);
78         }
79         catch (Exception e) {
80             Log.d("db", "returning default int value of " + name, e);
81             return default_value;
82         }
83     }
84     static public long get_option_value(String name, long default_value) {
85         String s = get_option_value(name, String.valueOf(default_value));
86         try {
87             return Long.parseLong(s);
88         }
89         catch (Exception e) {
90             Log.d("db", "returning default long value of " + name, e);
91             return default_value;
92         }
93     }
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}))
99         {
100             if (cursor.moveToFirst()) {
101                 String result = cursor.getString(0);
102
103                 if (result == null) result = default_value;
104
105                 Log.d("db", "option " + name + "=" + result);
106                 return result;
107             }
108             else return default_value;
109         }
110         catch (Exception e) {
111             Log.d("db", "returning default value for " + name, e);
112             return default_value;
113         }
114     }
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});
120     }
121     static public void set_option_value(String name, long value) {
122         set_option_value(name, String.valueOf(value));
123     }
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,
132                         from, to, 0);
133         adapter.setStringConversionColumn(1);
134
135         FilterQueryProvider provider = new FilterQueryProvider() {
136             @Override
137             public Cursor runQuery(CharSequence constraint) {
138                 if (constraint == null) return null;
139
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);
144
145                 SQLiteDatabase db = MLDB.getReadableDatabase();
146
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}))
153                 {
154                     int i = 0;
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);
160                     }
161                 }
162
163                 return c;
164
165             }
166         };
167
168         adapter.setFilterQueryProvider(provider);
169
170         view.setAdapter(adapter);
171     }
172     public static void init(Application context) {
173         MLDB.context = context;
174     }
175     public static void done() {
176         if (helperForReading != null)
177             helperForReading.close();
178
179         if ((helperForWriting != helperForReading) && (helperForWriting != null))
180             helperForWriting.close();
181     }
182     public enum DatabaseMode {READ, WRITE}
183 }
184
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;
188
189     private final Context mContext;
190
191     public MobileLedgerDatabase(Context context) {
192         super(context, DB_NAME, null, LATEST_REVISION);
193         Log.d("db", "creating helper instance");
194         mContext = context;
195         super.setWriteAheadLoggingEnabled(true);
196     }
197
198     @Override
199     public void onCreate(SQLiteDatabase db) {
200         Log.d("db", "onCreate called");
201         onUpgrade(db, -1, LATEST_REVISION);
202     }
203
204     @Override
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);
208     }
209
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);
213
214         int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
215         if (res_id == 0)
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);
222
223             String line;
224             while ((line = reader.readLine()) != null) {
225                 db.execSQL(line);
226             }
227
228             db.setTransactionSuccessful();
229         }
230         catch (IOException e) {
231             Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));
232             e.printStackTrace();
233         }
234         finally {
235             db.endTransaction();
236         }
237     }
238 }