]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
stop closing acuired db handles and leave that for the application termination
[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.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     public static final String OPT_LAST_REFRESH = "last_refresh";
49     private static MobileLedgerDatabase helperForReading, helperForWriting;
50     private static Context context;
51     private static void checkState() {
52         if (context == null)
53             throw new IllegalStateException("First call init with a valid context");
54     }
55     public static synchronized SQLiteDatabase getDatabase(DatabaseMode mode) {
56         checkState();
57
58         if (mode == READ) {
59             if (helperForReading == null) helperForReading = new MobileLedgerDatabase(context);
60             return helperForReading.getReadableDatabase();
61         }
62         else {
63             if (helperForWriting == null) helperForWriting = new MobileLedgerDatabase(context);
64             return helperForWriting.getWritableDatabase();
65         }
66     }
67     public static SQLiteDatabase getReadableDatabase() {
68         return getDatabase(READ);
69     }
70     public static SQLiteDatabase getWritableDatabase() {
71         return getDatabase(WRITE);
72     }
73     static public int get_option_value(String name, int default_value) {
74         String s = get_option_value(name, String.valueOf(default_value));
75         try {
76             return Integer.parseInt(s);
77         }
78         catch (Exception e) {
79             Log.d("db", "returning default int value of " + name, e);
80             return default_value;
81         }
82     }
83     static public long get_option_value(String name, long default_value) {
84         String s = get_option_value(name, String.valueOf(default_value));
85         try {
86             return Long.parseLong(s);
87         }
88         catch (Exception e) {
89             Log.d("db", "returning default long value of " + name, e);
90             return default_value;
91         }
92     }
93     static public String get_option_value(String name, String default_value) {
94         Log.d("db", "about to fetch option " + name);
95         SQLiteDatabase db = getReadableDatabase();
96         try (Cursor cursor = db
97                 .rawQuery("select value from options where name=?", new String[]{name}))
98         {
99             if (cursor.moveToFirst()) {
100                 String result = cursor.getString(0);
101
102                 if (result == null) result = default_value;
103
104                 Log.d("db", "option " + name + "=" + result);
105                 return result;
106             }
107             else return default_value;
108         }
109         catch (Exception e) {
110             Log.d("db", "returning default value for " + name, e);
111             return default_value;
112         }
113     }
114     static public void set_option_value(String name, String value) {
115         Log.d("db", "setting option " + name + "=" + value);
116         SQLiteDatabase db = getWritableDatabase();
117         db.execSQL("insert or replace into options(name, value) values(?, ?);",
118                 new String[]{name, value});
119     }
120     static public void set_option_value(String name, long value) {
121         set_option_value(name, String.valueOf(value));
122     }
123     @TargetApi(Build.VERSION_CODES.N)
124     public static void hook_autocompletion_adapter(final Context context,
125                                                    final AutoCompleteTextView view,
126                                                    final String table, final String field) {
127         String[] from = {field};
128         int[] to = {android.R.id.text1};
129         SimpleCursorAdapter adapter =
130                 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
131                         from, to, 0);
132         adapter.setStringConversionColumn(1);
133
134         FilterQueryProvider provider = new FilterQueryProvider() {
135             @Override
136             public Cursor runQuery(CharSequence constraint) {
137                 if (constraint == null) return null;
138
139                 String str = constraint.toString().toUpperCase();
140                 Log.d("autocompletion", "Looking for " + str);
141                 String[] col_names = {FontsContract.Columns._ID, field};
142                 MatrixCursor c = new MatrixCursor(col_names);
143
144                 SQLiteDatabase db = MLDB.getReadableDatabase();
145
146                 try (Cursor matches = db.rawQuery(String.format(
147                         "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
148                         "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
149                         "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " + "FROM %s " +
150                         "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 2, 1;", field, field,
151                         field, field, table, field), new String[]{str, str, str, str}))
152                 {
153                     int i = 0;
154                     while (matches.moveToNext()) {
155                         String match = matches.getString(0);
156                         int order = matches.getInt(1);
157                         Log.d("autocompletion", String.format("match: %s |%d", match, order));
158                         c.newRow().add(i++).add(match);
159                     }
160                 }
161
162                 return c;
163             }
164         };
165
166         adapter.setFilterQueryProvider(provider);
167
168         view.setAdapter(adapter);
169     }
170     public static void init(Context context) {
171         MLDB.context = context.getApplicationContext();
172     }
173     public static void done() {
174         if (helperForReading != null)
175             helperForReading.close();
176
177         if ((helperForWriting != helperForReading) && (helperForWriting != null))
178             helperForWriting.close();
179     }
180     public enum DatabaseMode {READ, WRITE}
181 }
182
183 class MobileLedgerDatabase extends SQLiteOpenHelper implements AutoCloseable {
184     public static final String DB_NAME = "mobile-ledger.db";
185     public static final int LATEST_REVISION = 10;
186
187     private final Context mContext;
188
189     public MobileLedgerDatabase(Context context) {
190         super(context, DB_NAME, null, LATEST_REVISION);
191         Log.d("db", "creating helper instance");
192         mContext = context;
193         super.setWriteAheadLoggingEnabled(true);
194     }
195
196     @Override
197     public void onCreate(SQLiteDatabase db) {
198         Log.d("db", "onCreate called");
199         onUpgrade(db, -1, LATEST_REVISION);
200     }
201
202     @Override
203     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
204         Log.d("db", "onUpgrade called");
205         for (int i = oldVersion + 1; i <= newVersion; i++) applyRevision(db, i);
206     }
207
208     private void applyRevision(SQLiteDatabase db, int rev_no) {
209         final Resources rm = mContext.getResources();
210         String rev_file = String.format(Locale.US, "sql_%d", rev_no);
211
212         int res_id = rm.getIdentifier(rev_file, "raw", mContext.getPackageName());
213         if (res_id == 0)
214             throw new SQLException(String.format(Locale.US, "No resource for revision %d", rev_no));
215         db.beginTransaction();
216         try (InputStream res = rm.openRawResource(res_id)) {
217             Log.d("db", "Applying revision " + String.valueOf(rev_no));
218             InputStreamReader isr = new InputStreamReader(res);
219             BufferedReader reader = new BufferedReader(isr);
220
221             String line;
222             while ((line = reader.readLine()) != null) {
223                 db.execSQL(line);
224             }
225
226             db.setTransactionSuccessful();
227         }
228         catch (IOException e) {
229             Log.e("db", String.format("Error opening raw resource for revision %d", rev_no));
230             e.printStackTrace();
231         }
232         finally {
233             db.endTransaction();
234         }
235     }
236 }