1 package net.ktnx.mobileledger;
3 import android.content.res.Resources;
4 import android.database.Cursor;
5 import android.database.sqlite.SQLiteDatabase;
6 import android.util.Log;
8 import java.io.BufferedReader;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
12 class MobileLedgerDB {
13 static final String DATABASE_NAME = "accounts";
14 private static String db_filename;
15 static SQLiteDatabase db;
17 static String getDb_filename() {
21 static void setDb_filename(String db_filename) {
22 MobileLedgerDB.db_filename = db_filename;
25 static void initDB() {
26 db = SQLiteDatabase.openOrCreateDatabase(db_filename, null);
28 db.execSQL("create table if not exists accounts(name varchar);");
29 db.execSQL("create index if not exists idx_accounts_name on accounts(name);");
30 db.execSQL("create table if not exists options(name varchar, value varchar);");
31 db.execSQL("create unique index if not exists idx_options_name on options(name);");
34 static void applyRevisions(Resources rm) {
35 int next_ver = Integer.parseInt(get_option_value("db_version", "0")) + 1;
37 while (applyRevision(rm, next_ver)) {
41 private static boolean applyRevision(Resources rm, int next_ver) {
42 try (InputStream res = rm.openRawResource(next_ver)) {
43 Log.d("db", "Applying revision " + String.valueOf(next_ver));
44 InputStreamReader isr = new InputStreamReader(res);
45 BufferedReader reader = new BufferedReader(isr);
48 while ((line = reader.readLine()) != null) {
52 db.setTransactionSuccessful();
53 } catch (Exception e) {
63 static int get_option_value(String name, int default_value) {
64 String s = get_option_value(name, String.valueOf(default_value));
66 return Integer.parseInt(s);
73 static long get_option_value(String name, long default_value) {
74 String s = get_option_value(name, String.valueOf(default_value));
76 return Long.parseLong(s);
79 Log.d("db", "returning default long value of "+name, e);
84 static String get_option_value(String name, String default_value) {
85 Log.d("db", "about fo fetch option "+name);
86 try (Cursor cursor = db.rawQuery("select value from options where name=?", new String[]{name})) {
87 if (cursor.moveToFirst()) {
88 String result = cursor.getString(0);
90 if (result == null ) result = default_value;
92 Log.d("db", "option "+name+"="+result);
95 else return default_value;
98 Log.d("db", "returning default value for "+name, e);
103 static void set_option_value(String name, String value) {
104 Log.d("db", "setting option "+name+"="+value);
105 db.execSQL("insert or replace into options(name, value) values(?, ?);", new String[]{name, value});
108 static void set_option_value(String name, long value) {
109 set_option_value(name, String.valueOf(value));