]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
d6fa7774f7e3bdef5fb4a51f39b26bc51e45d832
[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 org.jetbrains.annotations.NonNls;
37
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;
43
44 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.READ;
45 import static net.ktnx.mobileledger.utils.MLDB.DatabaseMode.WRITE;
46
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";
52     @NonNls
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() {
57         if (context == null)
58             throw new IllegalStateException("First call init with a valid context");
59     }
60     public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
61         checkState();
62
63         if (mode == READ) {
64             if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
65             return helperForReading.getReadableDatabase();
66         }
67         else {
68             if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
69             return helperForWriting.getWritableDatabase();
70         }
71     }
72     public static SQLiteDatabase getReadableDatabase() {
73         return getDatabase(READ);
74     }
75     public static SQLiteDatabase getWritableDatabase() {
76         return getDatabase(WRITE);
77     }
78     static public int get_option_value(String name, int default_value) {
79         String s = get_option_value(name, String.valueOf(default_value));
80         try {
81             return Integer.parseInt(s);
82         }
83         catch (Exception e) {
84             Log.d("db", "returning default int value of " + name, e);
85             return default_value;
86         }
87     }
88     static public long get_option_value(String name, long default_value) {
89         String s = get_option_value(name, String.valueOf(default_value));
90         try {
91             return Long.parseLong(s);
92         }
93         catch (Exception e) {
94             Log.d("db", "returning default long value of " + name, e);
95             return default_value;
96         }
97     }
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}))
103         {
104             if (cursor.moveToFirst()) {
105                 String result = cursor.getString(0);
106
107                 if (result == null) result = default_value;
108
109                 Log.d("db", "option " + name + "=" + result);
110                 return result;
111             }
112             else return default_value;
113         }
114         catch (Exception e) {
115             Log.d("db", "returning default value for " + name, e);
116             return default_value;
117         }
118     }
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});
124     }
125     static public void set_option_value(String name, long value) {
126         set_option_value(name, String.valueOf(value));
127     }
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,
136                         from, to, 0);
137         adapter.setStringConversionColumn(1);
138
139         FilterQueryProvider provider = new FilterQueryProvider() {
140             @Override
141             public Cursor runQuery(CharSequence constraint) {
142                 if (constraint == null) return null;
143
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);
148
149                 SQLiteDatabase db = MLDB.getReadableDatabase();
150
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}))
157                 {
158                     int i = 0;
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);
164                     }
165                 }
166
167                 return c;
168
169             }
170         };
171
172         adapter.setFilterQueryProvider(provider);
173
174         view.setAdapter(adapter);
175     }
176     public static void init(Application context) {
177         MLDB.context = context;
178     }
179     public static void done() {
180         if (helperForReading != null)
181             helperForReading.close();
182
183         if ((helperForWriting != helperForReading) && (helperForWriting != null))
184             helperForWriting.close();
185     }
186     public enum DatabaseMode {READ, WRITE}
187 }
188
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;
192
193     private final Application mContext;
194
195     public MobileLedgerDatabase(Application context) {
196         super(context, DB_NAME, null, LATEST_REVISION);
197         Log.d("db", "creating helper instance");
198         mContext = context;
199         super.setWriteAheadLoggingEnabled(true);
200     }
201
202     @Override
203     public void onCreate(SQLiteDatabase db) {
204         Log.d("db", "onCreate called");
205         onUpgrade(db, -1, LATEST_REVISION);
206     }
207
208     @Override
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);
212     }
213
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);
217
218         int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
219         if (res_id == 0)
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);
226
227             String line;
228             while ((line = reader.readLine()) != null) {
229                 db.execSQL(line);
230             }
231
232             db.setTransactionSuccessful();
233         }
234         catch (IOException e) {
235             Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));
236             e.printStackTrace();
237         }
238         finally {
239             db.endTransaction();
240         }
241     }
242 }