Skip to content

Commit

Permalink
Optimize the logic related to table structure upgrade.(#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
dora4 committed Nov 8, 2024
1 parent 3aa3778 commit 9327252
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
2 changes: 1 addition & 1 deletion dcache/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ afterEvaluate {
from(components["release"])
groupId = "com.github.dora4"
artifactId = "dcache-android"
version = "2.5.7"
version = "2.5.8"
}
}
}
Expand Down
16 changes: 13 additions & 3 deletions dcache/src/main/java/dora/db/Orm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@ object Orm {
val name: String = config.databaseName
val versionCode: Int = config.versionCode
val tables: Array<Class<out OrmTable>>? = config.tables
dbHelper = OrmSQLiteOpenHelper(context, name, versionCode, tables)
database = dbHelper!!.writableDatabase
prepare()
prepare(context, name, versionCode, tables)
dbHelper!!.onCreate(database)
}

Expand All @@ -45,7 +44,18 @@ object Orm {
throw OrmStateException("Database is not exists.")
}

fun prepare() {
fun prepare(helper: OrmSQLiteOpenHelper) {
dbHelper = helper
dbState = STATE_DATABASE_EXISTS
}

fun prepare(
context: Context,
name: String,
versionCode: Int,
tables: Array<Class<out OrmTable>>?
) {
dbHelper = OrmSQLiteOpenHelper(context, name, versionCode, tables)
dbState = STATE_DATABASE_EXISTS
}

Expand Down
5 changes: 2 additions & 3 deletions dcache/src/main/java/dora/db/OrmSQLiteOpenHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import android.content.Context
import android.database.DatabaseErrorHandler
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import dora.db.dao.OrmDao
import dora.db.exception.OrmMigrationException
import dora.db.migration.OrmMigration
import dora.db.table.OrmTable
Expand All @@ -19,7 +18,7 @@ import java.lang.reflect.InvocationTargetException
* 简体中文:一个帮助类,用于管理数据库的创建和版本管理。你需要在[Orm.init]函数中创建所有表,不建议使用
* [TableManager]自行创建表。如果你需要升级数据的表结构,需要使用[OrmMigration]的数组指定每一次版本的变动。
*/
class OrmSQLiteOpenHelper(context: Context, name: String, version: Int,
class OrmSQLiteOpenHelper(private val context: Context, name: String, version: Int,
private val tables: Array<Class<out OrmTable>>?) :
SQLiteOpenHelper(context, name, null, version, DatabaseErrorHandler {
dbObj -> OrmLog.e(dbObj.toString()) }) {
Expand Down Expand Up @@ -100,7 +99,7 @@ class OrmSQLiteOpenHelper(context: Context, name: String, version: Int,
continue
}
if (migration.fromVersion == curVersion) {
Orm.prepare()
Orm.prepare(this)
val ok = Transaction.execute(it.javaClass as Class<out OrmTable>) { dao ->
migration.migrate(dao)
} as Boolean
Expand Down

0 comments on commit 9327252

Please sign in to comment.