]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
178b7b2017484f6e93fa16bf09a60dbc8671b76e
[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 MoLe.
4  * MoLe 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  * MoLe 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 MoLe. 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.database.Cursor;
23 import android.database.sqlite.SQLiteDatabase;
24 import android.os.AsyncTask;
25 import android.os.Build;
26 import android.widget.AutoCompleteTextView;
27 import android.widget.FilterQueryProvider;
28 import android.widget.SimpleCursorAdapter;
29
30 import androidx.annotation.NonNull;
31
32 import net.ktnx.mobileledger.App;
33 import net.ktnx.mobileledger.async.DbOpQueue;
34 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
35 import net.ktnx.mobileledger.model.Data;
36 import net.ktnx.mobileledger.model.MobileLedgerProfile;
37
38 import org.jetbrains.annotations.NonNls;
39
40 import static net.ktnx.mobileledger.utils.Logger.debug;
41
42 public final class MLDB {
43     public static final String ACCOUNTS_TABLE = "accounts";
44     public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
45     public static final String OPT_LAST_SCRAPE = "last_scrape";
46     @NonNls
47     public static final String OPT_PROFILE_UUID = "profile_uuid";
48     private static final String NO_PROFILE = "-";
49     @SuppressWarnings("unused")
50     static public int getIntOption(String name, int default_value) {
51         String s = getOption(name, String.valueOf(default_value));
52         try {
53             return Integer.parseInt(s);
54         }
55         catch (Exception e) {
56             debug("db", "returning default int value of " + name, e);
57             return default_value;
58         }
59     }
60     @SuppressWarnings("unused")
61     static public long getLongOption(String name, long default_value) {
62         String s = getOption(name, String.valueOf(default_value));
63         try {
64             return Long.parseLong(s);
65         }
66         catch (Exception e) {
67             debug("db", "returning default long value of " + name, e);
68             return default_value;
69         }
70     }
71     static public void getOption(String name, String defaultValue, GetOptCallback cb) {
72         AsyncTask<Void, Void, String> t = new AsyncTask<Void, Void, String>() {
73             @Override
74             protected String doInBackground(Void... params) {
75                 SQLiteDatabase db = App.getDatabase();
76                 try (Cursor cursor = db.rawQuery(
77                         "select value from options where profile=? and name=?",
78                         new String[]{NO_PROFILE, name}))
79                 {
80                     if (cursor.moveToFirst()) {
81                         String result = cursor.getString(0);
82
83                         if (result == null)
84                             result = defaultValue;
85
86                         debug("async-db", "option " + name + "=" + result);
87                         return result;
88                     }
89                     else
90                         return defaultValue;
91                 }
92                 catch (Exception e) {
93                     debug("db", "returning default value for " + name, e);
94                     return defaultValue;
95                 }
96             }
97             @Override
98             protected void onPostExecute(String result) {
99                 cb.onResult(result);
100             }
101         };
102
103         t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
104     }
105     static public String getOption(String name, String default_value) {
106         debug("db", "about to fetch option " + name);
107         SQLiteDatabase db = App.getDatabase();
108         try (Cursor cursor = db.rawQuery("select value from options where profile=? and name=?",
109                 new String[]{NO_PROFILE, name}))
110         {
111             if (cursor.moveToFirst()) {
112                 String result = cursor.getString(0);
113
114                 if (result == null)
115                     result = default_value;
116
117                 debug("db", "option " + name + "=" + result);
118                 return result;
119             }
120             else
121                 return default_value;
122         }
123         catch (Exception e) {
124             debug("db", "returning default value for " + name, e);
125             return default_value;
126         }
127     }
128     static public void setOption(String name, String value) {
129         debug("option", String.format("%s := %s", name, value));
130         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
131                 new String[]{NO_PROFILE, name, value});
132     }
133     @SuppressWarnings("unused")
134     static public void setLongOption(String name, long value) {
135         setOption(name, String.valueOf(value));
136     }
137     @TargetApi(Build.VERSION_CODES.N)
138     public static void hookAutocompletionAdapter(final Context context,
139                                                  final AutoCompleteTextView view,
140                                                  final String table, final String field) {
141         hookAutocompletionAdapter(context, view, table, field, true, null, null);
142     }
143     @TargetApi(Build.VERSION_CODES.N)
144     public static void hookAutocompletionAdapter(final Context context,
145                                                  final AutoCompleteTextView view,
146                                                  final String table, final String field,
147                                                  final boolean profileSpecific,
148                                                  final DescriptionSelectedCallback callback,
149                                                  final MobileLedgerProfile profile) {
150         String[] from = {field};
151         int[] to = {android.R.id.text1};
152         SimpleCursorAdapter adapter =
153                 new SimpleCursorAdapter(context, android.R.layout.simple_dropdown_item_1line, null,
154                         from, to, 0);
155         adapter.setStringConversionColumn(1);
156
157         FilterQueryProvider provider = constraint -> {
158             if (constraint == null)
159                 return null;
160
161             String str = constraint.toString()
162                                    .toUpperCase();
163             debug("autocompletion", "Looking for " + str);
164
165             String sql;
166             String[] params;
167             if (profileSpecific) {
168                 MobileLedgerProfile p = (profile == null) ? Data.getProfile() : profile;
169                 sql = String.format(
170                         "SELECT rowid as _id, %s, CASE WHEN %s_upper LIKE ?||'%%' THEN 1 " +
171                         "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
172                         "WHEN %s_upper LIKE '%% '||?||'%%' THEN 3 " + "ELSE 9 END " + "FROM %s " +
173                         "WHERE profile=? AND %s_upper LIKE '%%'||?||'%%' " +
174                         "ORDER BY 3, %s_upper, 1;", field, field, field, field, table, field,
175                         field);
176                 params = new String[]{str, str, str, p.getUuid(), str};
177             }
178             else {
179                 sql = String.format(
180                         "SELECT rowid as _id, %s, CASE WHEN %s_upper LIKE ?||'%%' THEN 1 " +
181                         "WHEN %s_upper LIKE '%%:'||?||'%%' THEN 2 " +
182                         "WHEN %s_upper LIKE '%% '||?||'%%' THEN 3 " + "ELSE 9 END " + "FROM %s " +
183                         "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 3, %s_upper, 1;", field,
184                         field, field, field, table, field, field);
185                 params = new String[]{str, str, str, str};
186             }
187             debug("autocompletion", sql);
188             SQLiteDatabase db = App.getDatabase();
189
190             return db.rawQuery(sql, params);
191         };
192
193         adapter.setFilterQueryProvider(provider);
194
195         view.setAdapter(adapter);
196
197         if (callback != null)
198             view.setOnItemClickListener(
199                     (parent, itemView, position, id) -> callback.descriptionSelected(
200                             String.valueOf(view.getText())));
201     }
202     public static void queryInBackground(@NonNull String statement, @NonNull String[] params,
203                                          @NonNull CallbackHelper callbackHelper) {
204         /* All callbacks are called in the new (asynchronous) thread! */
205         Thread t = new Thread(() -> {
206             callbackHelper.onStart();
207             try {
208                 SQLiteDatabase db = App.getDatabase();
209
210                 try (Cursor cursor = db.rawQuery(statement, params)) {
211                     boolean gotRow = false;
212                     while (cursor.moveToNext()) {
213                         gotRow = true;
214                         if (!callbackHelper.onRow(cursor))
215                             break;
216                     }
217                     if (!gotRow) {
218                         callbackHelper.onNoRows();
219                     }
220                 }
221             }
222             catch (Exception e) {
223                 callbackHelper.onException(e);
224             }
225             finally {
226                 callbackHelper.onDone();
227             }
228         });
229
230         t.start();
231     }
232     /* MLDB.CallbackHelper -- Abstract class for asynchronous SQL query callbacks */
233     @SuppressWarnings("WeakerAccess")
234     abstract public static class CallbackHelper {
235         public void onStart() {}
236         public abstract boolean onRow(@NonNull Cursor cursor);
237         public void onNoRows() {}
238         public void onException(Exception exception) {
239             Logger.debug("MLDB", "Exception in asynchronous SQL", exception);
240         }
241         public void onDone() {}
242     }
243 }
244