]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
streamlined database utility, fed with the application context upon startup
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / utils / MLDB.java
1 /*
2  * Copyright © 2018 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.content.Context;
22 import android.content.res.Resources;
23 import android.database.Cursor;
24 import android.database.MatrixCursor;
25 import android.database.SQLException;
26 import android.database.sqlite.SQLiteDatabase;
27 import android.database.sqlite.SQLiteOpenHelper;
28 import android.os.Build;
29 import android.provider.FontsContract;
30 import android.util.Log;
31 import android.widget.AutoCompleteTextView;
32 import android.widget.FilterQueryProvider;
33 import android.widget.SimpleCursorAdapter;
34
35 import java.io.BufferedReader;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.InputStreamReader;
39 import java.util.Locale;
40
41 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
42 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
43
44 public final class MLDB {
45     public static final String ACCOUNTS_TABLE = "accounts";
46     public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
47     public static final String OPT_TRANSACTION_LIST_STAMP = "transaction_list_last_update";
48     private static MobileLedgerDatabase helperForReading, helperForWriting;
49     private static Context context;
50     private static void checkState() {
51         if (context == null)
52             throw new IllegalStateException("First call init with a valid context");
53     }
54     public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
55         checkState();
56
57         if (mode == READ) {
58             if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
59             return helperForReading.getReadableDatabase();
60         }
61         else {
62             if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
63             return helperForWriting.getWritableDatabase();
64         }
65     }
66     public static SQLiteDatabase getReadableDatabase() {
67         return getDatabase(READ);
68     }
69     public static SQLiteDatabase getWritableDatabase(Context context) {
70         return getDatabase(WRITE);
71     }
72     static public int get_option_value(Context context, String name, int default_value) {
73         String s = get_option_value(context, name, String.valueOf(default_value));
74         try {
75             return Integer.parseInt(s);
76         }
77         catch (Exception e) {
78             Log.d("db", "returning default int value of " + name, e);
79             return default_value;
80         }
81     }
82     static public long get_option_value(Context context, String name, long default_value) {
83         String s = get_option_value(context, name, String.valueOf(default_value));
84         try {
85             return Long.parseLong(s);
86         }
87         catch (Exception e) {
88             Log.d("db", "returning default long value of " + name, e);
89             return default_value;
90         }
91     }
92     static public String get_option_value(Context context, String name, String default_value) {
93         Log.d("db", "about to fetch option " + name);
94         try (SQLiteDatabase db = getReadableDatabase()) {
95             try (Cursor cursor = db
96                     .rawQuery("select value from options where name=?", new String[]{name}))
97             {
98                 if (cursor.moveToFirst()) {
99                     String result = cursor.getString(0);
100
101                     if (result == null) result = default_value;
102
103                     Log.d("db", "option " + name + "=" + result);
104                     return result;
105                 }
106                 else return default_value;
107             }
108             catch (Exception e) {
109                 Log.d("db", "returning default value for " + name, e);
110                 return default_value;
111             }
112         }
113     }
114     static public void set_option_value(Context context, String name, String value) {
115         Log.d("db", "setting option " + name + "=" + value);
116         try (SQLiteDatabase db = getWritableDatabase(context)) {
117             db.execSQL("insert or replace into options(name, value) values(?, ?);",
118                     new String[]{name, value});
119         }
120     }
121     static public void set_option_value(Context context, String name, long value) {
122         set_option_value(context, 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                 try (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 " +
151                             "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 2, 1;",
152                             field, field, field, field, table, field),
153                             new String[]{str, str, str, str}))
154                     {
155                         int i = 0;
156                         while (matches.moveToNext()) {
157                             String match = matches.getString(0);
158                             int order = matches.getInt(1);
159                             Log.d("autocompletion", String.format("match: %s |%d", match, order));
160                             c.newRow().add(i++).add(match);
161                         }
162                     }
163
164                     return c;
165                 }
166
167             }
168         };
169
170         adapter.setFilterQueryProvider(provider);
171
172         view.setAdapter(adapter);
173     }
174     public static void init(Context context) {
175         MLDB.context = context.getApplicationContext();
176     }
177     public enum DatabaseMode {READ, WRITE}
178 }
179
180 class MobileLedgerDatabase extends SQLiteOpenHelper implements AutoCloseable {
181     public static final String DB_NAME = "mobile-ledger.db";
182     public static final int LATEST_REVISION = 10;
183
184     private final Context mContext;
185
186     public MobileLedgerDatabase(Context context) {
187         super(context, DB_NAME, null, LATEST_REVISION);
188         Log.d("db", "creating helper instance");
189         mContext = context;
190         super.setWriteAheadLoggingEnabled(true);
191     }
192
193     @Override
194     public void onCreate(SQLiteDatabase db) {
195         Log.d("db", "onCreate called");
196         onUpgrade(db, -1, LATEST_REVISION);
197     }
198
199     @Override
200     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
201         Log.d("db", "onUpgrade called");
202         for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
203     }
204
205     private void applyRevision(SQLiteDatabase db, int rev_no) {
206         final Resources rm = mContext.getResources();
207         String rev_file = String.format(Locale.US, "sql_%d", rev_no);
208
209         int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
210         if (res_id == 0)
211             throw new SQLException(String.format(Locale.US, "No resource for revision %d", rev_no));
212         db.beginTransaction();
213         try (InputStream res = rm.openRawResource(res_id)) {
214             Log.d("db", "Applying revision " + String.valueOf(rev_no));
215             InputStreamReader isr = new InputStreamReader(res);
216             BufferedReader reader = new BufferedReader(isr);
217
218             String line;
219             while ((line = reader.readLine()) != null) {
220                 db.execSQL(line);
221             }
222
223             db.setTransactionSuccessful();
224         }
225         catch (IOException e) {
226             Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));
227             e.printStackTrace();
228         }
229         finally {
230             db.endTransaction();
231         }
232     }
233 }