【发布时间】:2014-02-20 04:03:04
【问题描述】:
我在服务器上有一个(概念上的)sqlite 数据库,旨在与我要开发的 Android 应用程序的 sqlite 数据库保持一致。
我为每个名为 _id 变体的表使用自动增量整数主键,例如_entry_id 或 _goal_id。
我正在通过为每个表创建一个“修改”表来处理同步,该表详细说明了哪个表发生了哪些操作以及该表中的哪些条目。
用户可以选择与服务器同步,但这不是必需的。这一点至关重要,遗憾的是,强制人们在使用应用程序时与服务器同步的选项是不可能的。
我在概念上遇到以下问题:
假设服务器数据库有一个带有字段的表“条目”:
- '_entry_id' 是一个自动增量整数主要
- 'title' 是一个文本字段。
数据库当前没有条目。
假设有两台设备正在运行该应用。应用和服务器使用相同的数据库架构。
假设 device1 有条目:
- 0, dev1entry0
- 1, dev1entry1
如果 device1 决定同步,系统将通过一些不重要的魔法确定这两个条目是新条目并将它们添加到服务器数据库中,因此服务器数据库现在具有条目:
- 0, dev1entry0
- 1, dev1entry1
现在说 device2 决定不与服务器数据库同步,然后在其数据库中创建一些新条目,现在有了这些条目:
- 0, dev2entry0
- 1,dev2entry1
如果它现在决定同步,那么系统将决定这些是新条目并将它们添加到数据库中,以便数据库现在拥有这些条目:
- 0, dev1entry0
- 1, dev1entry1
- 2, dev2entry0
- 3、dev2entry1
现在 device2 有了条目:
- 0, dev2entry0
- 1,dev2entry1
- 2、dev1entry0
- 3、dev1entry1
现在,对 device2 上的条目所做的任何修改都会修改服务器上的错误条目,因为主键不正确。
我想了一个办法来解决这个问题。因为这(据我所知)只是将新条目插入表时的一个问题。我的想法如下:
Assume the same entries for the server database as above
Assume that a new device, device3, has an entry:
- 0, dev3entry0
when an insert needs to occur when syncinc
get the id that's been assigned to device3's entry: 0
check the id against the largest id that's already been assigned to the server's db: 3
if 0 == 3 + 1 (the next increment to be assigned)
then insert the new entry to the database, the keys are the same
otherwise
duplicate the entry in device3 so that the key == 3 + 1
delete the original entry
使用此算法(当您不考虑同步到 device3 时)您应该在服务器数据库中留下以下内容:
- 0, dev2entry0
- 1,dev2entry1
- 2、dev1entry0
- 3、dev1entry1
- 4,dev3entry0
还有 device3 的数据库中的以下内容:
- 4,dev3entry0
意味着所有主键都是一致的。
这个算法在sqlite中可行吗?
如果不是,或者如果这个算法不是最好的,那么处理这个问题的另一种方法是什么?
我希望我的解释已经足够清楚了。
干杯。
【问题讨论】:
-
我遇到了类似的问题。你找到解决办法了吗?
-
还没有。我已经推迟了在我的软件中进行同步的工作,直到它绝对需要实施。
标签: android database sqlite auto-increment consistency