]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/MobileLedgerDatabase.java
another approach at supporting multi-line SQL statements
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / utils / MobileLedgerDatabase.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.app.Application;
21 import android.content.res.Resources;
22 import android.database.SQLException;
23 import android.database.sqlite.SQLiteDatabase;
24 import android.database.sqlite.SQLiteOpenHelper;
25
26 import androidx.lifecycle.MutableLiveData;
27
28 import net.ktnx.mobileledger.BuildConfig;
29
30 import java.io.BufferedReader;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.util.Locale;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37
38 import static net.ktnx.mobileledger.utils.Logger.debug;
39
40 public class MobileLedgerDatabase extends SQLiteOpenHelper {
41     public static final MutableLiveData<Boolean> initComplete = new MutableLiveData<>(false);
42     public static final String DB_NAME = "MoLe.db";
43     private static final int LATEST_REVISION = 57;
44     private static final String CREATE_DB_SQL = "create_db";
45     private final Application mContext;
46
47     public MobileLedgerDatabase(Application context) {
48         super(context, DB_NAME, null, LATEST_REVISION);
49         debug("db", "creating helper instance");
50         mContext = context;
51         super.setWriteAheadLoggingEnabled(true);
52     }
53
54     @Override
55     public void onCreate(SQLiteDatabase db) {
56         debug("db", "onCreate called");
57         applyRevisionFile(db, CREATE_DB_SQL);
58     }
59
60     @Override
61     public void onConfigure(SQLiteDatabase db) {
62         super.onConfigure(db);
63         db.execSQL("pragma case_sensitive_like=ON;");
64         if (BuildConfig.DEBUG)
65             db.execSQL("PRAGMA foreign_keys=ON");
66     }
67     @Override
68     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
69         debug("db",
70                 String.format(Locale.US, "needs upgrade from version %d to version %d", oldVersion,
71                         newVersion));
72         for (int i = oldVersion + 1; i <= newVersion; i++)
73             applyRevision(db, i);
74     }
75     private void applyRevision(SQLiteDatabase db, int rev_no) {
76         String rev_file = String.format(Locale.US, "sql_%d", rev_no);
77
78         applyRevisionFile(db, rev_file);
79     }
80     private void applyRevisionFile(SQLiteDatabase db, String revFile) {
81         final Resources rm = mContext.getResources();
82         int res_id = rm.getIdentifier(revFile, "raw", mContext.getPackageName());
83         if (res_id == 0)
84             throw new SQLException(String.format(Locale.US, "No resource for %s", revFile));
85
86         try (InputStream res = rm.openRawResource(res_id)) {
87             debug("db", "Applying " + revFile);
88             InputStreamReader isr = new InputStreamReader(res);
89             BufferedReader reader = new BufferedReader(isr);
90
91             Pattern endOfStatement = Pattern.compile(";\\s*(?:--.*)$");
92
93             String line;
94             String sqlStatement = null;
95             int lineNo = 0;
96             while ((line = reader.readLine()) != null) {
97                 lineNo++;
98                 if (line.startsWith("--"))
99                     continue;
100                 if (line.isEmpty())
101                     continue;
102
103                 if (sqlStatement == null)
104                     sqlStatement = line;
105                 else
106                     sqlStatement = sqlStatement.concat(line);
107
108                 Matcher m = endOfStatement.matcher(line);
109                 if (!m.find())
110                     continue;
111
112                 try {
113                     db.execSQL(sqlStatement);
114                     sqlStatement = null;
115                 }
116                 catch (Exception e) {
117                     throw new RuntimeException(
118                             String.format("Error applying %s, line %d, statement: %s", revFile,
119                                     lineNo, sqlStatement), e);
120                 }
121             }
122
123             if (sqlStatement != null)
124                 throw new RuntimeException(
125                         String.format("Error applying %s: EOF after continuation", revFile));
126
127         }
128         catch (IOException e) {
129             throw new RuntimeException(String.format("Error opening raw resource for %s", revFile),
130                     e);
131         }
132     }
133 }