aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/utils/DbUtils.kt
blob: 5b10e5814c2e48f9af3df27344589a39706f853b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.pitchedapps.frost.utils

import android.content.Context
import com.raizlabs.android.dbflow.config.FlowManager
import com.raizlabs.android.dbflow.kotlinextensions.processInTransactionAsync
import com.raizlabs.android.dbflow.kotlinextensions.save
import com.raizlabs.android.dbflow.structure.database.transaction.Transaction

/**
 * Created by Allan Wang on 2017-05-30.
 */

object DbUtils {

    fun db(name: String) = FlowManager.getDatabase(name)
    fun dbName(name: String) = "$name.db"
    fun deleteDatabase(c: Context, name: String) = c.deleteDatabase(dbName(name))

}

inline fun <reified T : Any> List<T>.replace(context: Context, dbName: String,
                                             crossinline callback: ((successful: Boolean) -> Unit)) {
    L.d("Replacing $dbName.db")
    DbUtils.db(dbName).reset(context)
    this.processInTransactionAsync({
        t, databaseWrapper ->
        t.save(databaseWrapper)
    },
            Transaction.Success {
                callback.invoke(true)
            },
            Transaction.Error { _, error ->
                L.e(error.message ?: "DbReplace error")
                callback.invoke(false)
            })
}