Objectbox,如何在冲突上掉落所有的迁移?

发布于 2025-01-30 03:54:49 字数 711 浏览 4 评论 0原文

在我的情况下,可以保存的数据可以在不担心模型更改的情况下清理,这是一种更好的方法来做到这一点?

private val dataSource = try {
    MyObjectBox.builder().androidContext(context).build().boxFor(XXXX::class)
} catch (e: Exception) {
    BoxStore.deleteAllFiles(context, BoxStoreBuilder.DEFAULT_NAME)
    MyObjectBox.builder().androidContext(context).build().boxFor(XXXX::class)
}

我想知道是否有这样的事情: https://developer.android.com/reference/android/arch/persistence/persistence/room/room/roomdatabase.builder#fallbacktodstodesteructivemigration()

In my case saved data can be cleaned without fear in case of model changes, there is a better way to do this ?

private val dataSource = try {
    MyObjectBox.builder().androidContext(context).build().boxFor(XXXX::class)
} catch (e: Exception) {
    BoxStore.deleteAllFiles(context, BoxStoreBuilder.DEFAULT_NAME)
    MyObjectBox.builder().androidContext(context).build().boxFor(XXXX::class)
}

I'm wondering if there is such a thing as this: https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.Builder#fallbackToDestructiveMigration()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

相思碎 2025-02-06 03:54:49

这种方法有点骇人听闻,但是为什么不呢!我的意思是,如果您不在乎失去现有数据...

我可以建议的两个可能的改进:

  • boxfor()应该在之外尝试,因为这里的任何错误都会与模型更改无关。
  • 您可能更具体而不是异常。例如dbschemaexception用于模型相关的异常,或作为“内在”解决方案,dbexception用于捕获任何与DB相关的异常(包括dbschemaexception) 。

因此,要调整您的代码,它看起来可能是这样:

private val store = try {
    MyObjectBox.builder().androidContext(context).build()
} catch (e: DbSchemaException) {
    BoxStore.deleteAllFiles(context, BoxStoreBuilder.DEFAULT_NAME)
    MyObjectBox.builder().androidContext(context).build()
}
private val box = store.boxFor(XXXX::class)

This approach is a bit hacky, but why not!? I mean, if you don't care about loosing existing data...

Two possible refinements I can suggest:

  • boxFor() should be outside the try because any error here would be unrelated to model changes.
  • Instead of Exception, you could be more specific. E.g. DbSchemaException for model related exceptions, or as an "in-between" solution, DbException for catching any DB-related exceptions (including DbSchemaException).

So, to adapt your code it could look like this:

private val store = try {
    MyObjectBox.builder().androidContext(context).build()
} catch (e: DbSchemaException) {
    BoxStore.deleteAllFiles(context, BoxStoreBuilder.DEFAULT_NAME)
    MyObjectBox.builder().androidContext(context).build()
}
private val box = store.boxFor(XXXX::class)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文