]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java
migrate to surrogate IDs for all database objects
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / utils / MLDB.java
1 /*
2  * Copyright © 2021 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.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.os.AsyncTask;
23
24 import androidx.annotation.NonNull;
25
26 import net.ktnx.mobileledger.App;
27 import net.ktnx.mobileledger.async.DbOpQueue;
28
29 import org.jetbrains.annotations.NonNls;
30
31 import static net.ktnx.mobileledger.utils.Logger.debug;
32
33 public final class MLDB {
34     public static final String ACCOUNTS_TABLE = "accounts";
35     public static final String DESCRIPTION_HISTORY_TABLE = "description_history";
36     public static final String OPT_LAST_SCRAPE = "last_scrape";
37     @NonNls
38     public static final String OPT_PROFILE_ID = "profile_id";
39     private static final String NO_PROFILE = "-";
40     @SuppressWarnings("unused")
41     static public int getIntOption(String name, int default_value) {
42         String s = getOption(name, String.valueOf(default_value));
43         try {
44             return Integer.parseInt(s);
45         }
46         catch (Exception e) {
47             debug("db", "returning default int value of " + name, e);
48             return default_value;
49         }
50     }
51     @SuppressWarnings("unused")
52     static public long getLongOption(String name, long default_value) {
53         String s = getOption(name, String.valueOf(default_value));
54         try {
55             return Long.parseLong(s);
56         }
57         catch (Exception e) {
58             debug("db", "returning default long value of " + name, e);
59             return default_value;
60         }
61     }
62     static public void getOption(String name, String defaultValue, GetOptCallback cb) {
63         AsyncTask<Void, Void, String> t = new AsyncTask<Void, Void, String>() {
64             @Override
65             protected String doInBackground(Void... params) {
66                 SQLiteDatabase db = App.getDatabase();
67                 try (Cursor cursor = db.rawQuery(
68                         "select value from options where profile=? and name=?",
69                         new String[]{NO_PROFILE, name}))
70                 {
71                     if (cursor.moveToFirst()) {
72                         String result = cursor.getString(0);
73
74                         if (result == null)
75                             result = defaultValue;
76
77                         debug("async-db", "option " + name + "=" + result);
78                         return result;
79                     }
80                     else
81                         return defaultValue;
82                 }
83                 catch (Exception e) {
84                     debug("db", "returning default value for " + name, e);
85                     return defaultValue;
86                 }
87             }
88             @Override
89             protected void onPostExecute(String result) {
90                 cb.onResult(result);
91             }
92         };
93
94         t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
95     }
96     static public String getOption(String name, String default_value) {
97         debug("db", "about to fetch option " + name);
98         SQLiteDatabase db = App.getDatabase();
99         try (Cursor cursor = db.rawQuery("select value from options where profile=? and name=?",
100                 new String[]{NO_PROFILE, name}))
101         {
102             if (cursor.moveToFirst()) {
103                 String result = cursor.getString(0);
104
105                 if (result == null)
106                     result = default_value;
107
108                 debug("db", "option " + name + "=" + result);
109                 return result;
110             }
111             else
112                 return default_value;
113         }
114         catch (Exception e) {
115             debug("db", "returning default value for " + name, e);
116             return default_value;
117         }
118     }
119     static public void setOption(String name, String value) {
120         debug("option", String.format("%s := %s", name, value));
121         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
122                 new String[]{NO_PROFILE, name, value});
123     }
124     @SuppressWarnings("unused")
125     static public void setLongOption(String name, long value) {
126         setOption(name, String.valueOf(value));
127     }
128     public static void queryInBackground(@NonNull String statement, String[] params,
129                                          @NonNull final CallbackHelper callbackHelper) {
130         /* All callbacks are called in the new (asynchronous) thread! */
131         Thread t = new Thread(() -> {
132             callbackHelper.onStart();
133             try {
134                 SQLiteDatabase db = App.getDatabase();
135
136                 try (Cursor cursor = db.rawQuery(statement, params)) {
137                     boolean gotRow = false;
138                     while (cursor.moveToNext()) {
139                         gotRow = true;
140                         if (!callbackHelper.onRow(cursor))
141                             break;
142                     }
143                     if (!gotRow) {
144                         callbackHelper.onNoRows();
145                     }
146                 }
147             }
148             catch (Exception e) {
149                 callbackHelper.onException(e);
150             }
151             finally {
152                 callbackHelper.onDone();
153             }
154         });
155
156         t.start();
157     }
158     /* MLDB.CallbackHelper -- Abstract class for asynchronous SQL query callbacks */
159     @SuppressWarnings("WeakerAccess")
160     abstract public static class CallbackHelper {
161         public void onStart() {}
162         public abstract boolean onRow(@NonNull Cursor cursor);
163         public void onNoRows() {}
164         public void onException(Exception exception) {
165             Logger.debug("MLDB", "Exception in asynchronous SQL", exception);
166         }
167         public void onDone() {}
168     }
169 }
170