ServiceDB.kt 10.6 KB
Newer Older
rhi's avatar
rhi committed
1
/*
rhi's avatar
rhi committed
2
 * Copyright © Ricki Hirner (bitfire web engineering).
rhi's avatar
rhi committed
3
4
5
6
7
8
9
10
11
12
13
14
15
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 */

package at.bitfire.davdroid.model

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
16
17
import android.preference.PreferenceManager
import at.bitfire.davdroid.App
rhi's avatar
rhi committed
18
import at.bitfire.davdroid.log.Logger
19
20
import at.bitfire.davdroid.ui.StartupDialogFragment
import java.util.logging.Level
rhi's avatar
rhi committed
21
22
23
24

class ServiceDB {

    object Services {
rhi's avatar
rhi committed
25
26
27
28
29
        const val _TABLE = "services"
        const val ID = "_id"
        const val ACCOUNT_NAME = "accountName"
        const val SERVICE = "service"
        const val PRINCIPAL = "principal"
rhi's avatar
rhi committed
30
31

        // allowed values for SERVICE column
rhi's avatar
rhi committed
32
33
        const val SERVICE_CALDAV = "caldav"
        const val SERVICE_CARDDAV = "carddav"
rhi's avatar
rhi committed
34
35
36
    }

    object HomeSets {
rhi's avatar
rhi committed
37
38
39
40
        const val _TABLE = "homesets"
        const val ID = "_id"
        const val SERVICE_ID = "serviceID"
        const val URL = "url"
rhi's avatar
rhi committed
41
42
43
    }

    object Collections {
rhi's avatar
rhi committed
44
45
46
47
48
        const val _TABLE = "collections"
        const val ID = "_id"
        const val TYPE = "type"
        const val SERVICE_ID = "serviceID"
        const val URL = "url"
rhi's avatar
rhi committed
49
50
        const val PRIV_WRITE_CONTENT = "privWriteContent"
        const val PRIV_UNBIND = "privUnbind"
rhi's avatar
rhi committed
51
52
53
54
55
56
57
58
59
        const val FORCE_READ_ONLY = "forceReadOnly"
        const val DISPLAY_NAME = "displayName"
        const val DESCRIPTION = "description"
        const val COLOR = "color"
        const val TIME_ZONE = "timezone"
        const val SUPPORTS_VEVENT = "supportsVEVENT"
        const val SUPPORTS_VTODO = "supportsVTODO"
        const val SOURCE = "source"
        const val SYNC = "sync"
rhi's avatar
rhi committed
60
61
62
63
64
65
66
    }

    companion object {

        fun onRenameAccount(db: SQLiteDatabase, oldName: String, newName: String) {
            val values = ContentValues(1)
            values.put(Services.ACCOUNT_NAME, newName)
rhi's avatar
rhi committed
67
            db.updateWithOnConflict(Services._TABLE, values, Services.ACCOUNT_NAME + "=?", arrayOf(oldName), SQLiteDatabase.CONFLICT_REPLACE)
rhi's avatar
rhi committed
68
69
70
71
72
73
        }

    }


    class OpenHelper(
74
            val context: Context
rhi's avatar
rhi committed
75
    ): SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION), AutoCloseable {
rhi's avatar
rhi committed
76
77

        companion object {
rhi's avatar
rhi committed
78
            const val DATABASE_NAME = "services.db"
rhi's avatar
rhi committed
79
            const val DATABASE_VERSION = 5
rhi's avatar
rhi committed
80
81
82
83
84
85
86
87
        }

        override fun onConfigure(db: SQLiteDatabase) {
            setWriteAheadLoggingEnabled(true)
            db.setForeignKeyConstraintsEnabled(true)
        }

        override fun onCreate(db: SQLiteDatabase) {
rhi's avatar
rhi committed
88
            Logger.log.info("Creating database " + db.path)
rhi's avatar
rhi committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

            db.execSQL("CREATE TABLE ${Services._TABLE}(" +
                    "${Services.ID} INTEGER PRIMARY KEY AUTOINCREMENT," +
                    "${Services.ACCOUNT_NAME} TEXT NOT NULL," +
                    "${Services.SERVICE} TEXT NOT NULL," +
                    "${Services.PRINCIPAL} TEXT NULL)")
            db.execSQL("CREATE UNIQUE INDEX services_account ON ${Services._TABLE} (${Services.ACCOUNT_NAME},${Services.SERVICE})")

            db.execSQL("CREATE TABLE ${HomeSets._TABLE}(" +
                    "${HomeSets.ID} INTEGER PRIMARY KEY AUTOINCREMENT," +
                    "${HomeSets.SERVICE_ID} INTEGER NOT NULL REFERENCES ${Services._TABLE} ON DELETE CASCADE," +
                    "${HomeSets.URL} TEXT NOT NULL)")
            db.execSQL("CREATE UNIQUE INDEX homesets_service_url ON ${HomeSets._TABLE}(${HomeSets.SERVICE_ID},${HomeSets.URL})")

            db.execSQL("CREATE TABLE ${Collections._TABLE}(" +
                    "${Collections.ID} INTEGER PRIMARY KEY AUTOINCREMENT," +
                    "${Collections.SERVICE_ID} INTEGER NOT NULL REFERENCES ${Services._TABLE} ON DELETE CASCADE," +
106
                    "${Collections.TYPE} TEXT NOT NULL," +
rhi's avatar
rhi committed
107
                    "${Collections.URL} TEXT NOT NULL," +
rhi's avatar
rhi committed
108
109
                    "${Collections.PRIV_WRITE_CONTENT} INTEGER DEFAULT 0 NOT NULL," +
                    "${Collections.PRIV_UNBIND} INTEGER DEFAULT 0 NOT NULL," +
110
                    "${Collections.FORCE_READ_ONLY} INTEGER DEFAULT 0 NOT NULL," +
rhi's avatar
rhi committed
111
112
113
114
115
116
                    "${Collections.DISPLAY_NAME} TEXT NULL," +
                    "${Collections.DESCRIPTION} TEXT NULL," +
                    "${Collections.COLOR} INTEGER NULL," +
                    "${Collections.TIME_ZONE} TEXT NULL," +
                    "${Collections.SUPPORTS_VEVENT} INTEGER NULL," +
                    "${Collections.SUPPORTS_VTODO} INTEGER NULL," +
117
                    "${Collections.SOURCE} TEXT NULL," +
rhi's avatar
rhi committed
118
119
120
121
122
                    "${Collections.SYNC} INTEGER DEFAULT 0 NOT NULL)")
            db.execSQL("CREATE UNIQUE INDEX collections_service_url ON ${Collections._TABLE}(${Collections.SERVICE_ID},${Collections.URL})")
        }

        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
123
            for (upgradeFrom in oldVersion until newVersion) {
rhi's avatar
rhi committed
124
                val upgradeTo = upgradeFrom + 1
125
126
127
128
129
130
131
                Logger.log.info("Upgrading database from version $upgradeFrom to $upgradeTo")
                try {
                    val upgradeProc = this::class.java.getDeclaredMethod("upgrade_${upgradeFrom}_$upgradeTo", SQLiteDatabase::class.java)
                    upgradeProc.invoke(this, db)
                } catch(e: Exception) {
                    Logger.log.log(Level.SEVERE, "Couldn't upgrade database", e)
                }
132
            }
rhi's avatar
rhi committed
133
134
        }

rhi's avatar
rhi committed
135
136
137
138
139
140
141
142
143
144
145
        @Suppress("unused")
        private fun upgrade_4_5(db: SQLiteDatabase) {
            db.execSQL("ALTER TABLE ${Collections._TABLE} ADD COLUMN ${Collections.PRIV_WRITE_CONTENT} INTEGER DEFAULT 0 NOT NULL")
            db.execSQL("UPDATE ${Collections._TABLE} SET ${Collections.PRIV_WRITE_CONTENT}=NOT readOnly")

            db.execSQL("ALTER TABLE ${Collections._TABLE} ADD COLUMN ${Collections.PRIV_UNBIND} INTEGER DEFAULT 0 NOT NULL")
            db.execSQL("UPDATE ${Collections._TABLE} SET ${Collections.PRIV_UNBIND}=NOT readOnly")

            // there's no DROP COLUMN in SQLite, so just keep the "readOnly" column
        }

146
147
148
149
150
        @Suppress("unused")
        private fun upgrade_3_4(db: SQLiteDatabase) {
            db.execSQL("ALTER TABLE ${Collections._TABLE} ADD COLUMN ${Collections.FORCE_READ_ONLY} INTEGER DEFAULT 0 NOT NULL")
        }

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
        @Suppress("unused")
        private fun upgrade_2_3(db: SQLiteDatabase) {
            val edit = PreferenceManager.getDefaultSharedPreferences(context).edit()
            try {
                db.query("settings", arrayOf("setting", "value"), null, null, null, null, null).use { cursor ->
                    while (cursor.moveToNext()) {
                        when (cursor.getString(0)) {
                            "distrustSystemCerts" -> edit.putBoolean(App.DISTRUST_SYSTEM_CERTIFICATES, cursor.getInt(1) != 0)
                            "overrideProxy" -> edit.putBoolean(App.OVERRIDE_PROXY, cursor.getInt(1) != 0)
                            "overrideProxyHost" -> edit.putString(App.OVERRIDE_PROXY_HOST, cursor.getString(1))
                            "overrideProxyPort" -> edit.putInt(App.OVERRIDE_PROXY_PORT, cursor.getInt(1))

                            StartupDialogFragment.HINT_GOOGLE_PLAY_ACCOUNTS_REMOVED ->
                                edit.putBoolean(StartupDialogFragment.HINT_GOOGLE_PLAY_ACCOUNTS_REMOVED, cursor.getInt(1) != 0)
                            StartupDialogFragment.HINT_OPENTASKS_NOT_INSTALLED ->
                                edit.putBoolean(StartupDialogFragment.HINT_OPENTASKS_NOT_INSTALLED, cursor.getInt(1) != 0)
                        }
                    }
                }
                db.execSQL("DROP TABLE settings")
            } finally {
                edit.apply()
            }
        }

        @Suppress("unused")
        private fun upgrade_1_2(db: SQLiteDatabase) {
            db.execSQL("ALTER TABLE ${Collections._TABLE} ADD COLUMN ${Collections.TYPE} TEXT NOT NULL DEFAULT ''")
            db.execSQL("ALTER TABLE ${Collections._TABLE} ADD COLUMN ${Collections.SOURCE} TEXT NULL")
            db.execSQL("UPDATE ${Collections._TABLE} SET ${Collections.TYPE}=(" +
                    "SELECT CASE ${Services.SERVICE} WHEN ? THEN ? ELSE ? END " +
                    "FROM ${Services._TABLE} WHERE ${Services.ID}=${Collections._TABLE}.${Collections.SERVICE_ID}" +
                    ")",
                    arrayOf(Services.SERVICE_CALDAV, CollectionInfo.Type.CALENDAR, CollectionInfo.Type.ADDRESS_BOOK))
        }

rhi's avatar
rhi committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200

        fun dump(sb: StringBuilder) {
            val db = readableDatabase
            db.beginTransactionNonExclusive()

            // iterate through all tables
            db.query("sqlite_master", arrayOf("name"), "type='table'", null, null, null, null).use { cursorTables ->
                while (cursorTables.moveToNext()) {
                    val table = cursorTables.getString(0)
                    sb.append(table).append("\n")
                    db.query(table, null, null, null, null, null, null).use { cursor ->
                        // print columns
                        val cols = cursor.columnCount
                        sb.append("\t| ")
rhi's avatar
rhi committed
201
                        for (i in 0 until cols)
rhi's avatar
rhi committed
202
203
204
205
206
207
208
209
                            sb  .append(" ")
                                .append(cursor.getColumnName(i))
                                .append(" |")
                        sb.append("\n")

                        // print rows
                        while (cursor.moveToNext()) {
                            sb.append("\t| ")
rhi's avatar
rhi committed
210
                            for (i in 0 until cols) {
rhi's avatar
rhi committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
                                sb.append(" ")
                                try {
                                    val value = cursor.getString(i)
                                    if (value != null)
                                        sb.append(value
                                                .replace("\r", "<CR>")
                                                .replace("\n", "<LF>"))
                                    else
                                        sb.append("<null>")

                                } catch (e: SQLiteException) {
                                    sb.append("<unprintable>")
                                }
                                sb.append(" |")
                            }
                            sb.append("\n")
                        }
                        sb.append("----------\n")
                    }
                }
                db.endTransaction()
            }
        }
    }

rhi's avatar
rhi committed
236
}