6

首先,一些背景:

我的Android应用程序有很多四列行的数据库表。它向服务器发送请求,服务器仅在所有这四个值都“有效”时做出响应。数以千计的用户中的一些人报告说某些东西对他们不起作用(因为有一段时间他们没有从服务器获得结果) - 我试图找出导致问题的原因,结果发现唯一可能的原因是未检测到的数据库损坏。

在 ACRA 日志中,我收到了一些带有 SQL 错误的消息,但这些消息是关于应用程序由于文件损坏而无法打开文件。这给了我一些线索,但我仍然不相信这是问题所在。因此,我创建了一个非常简单的 Python 脚本,它更改 DB 文件中的随机字节并检查 SQLite 将如何处理它:

import random
import array
import sqlite3

db = array.array('B')
db.fromstring(open('db').read())

ta =  [x for x in sqlite3.connect('db').execute('SELECT * FROM table ORDER BY _id')]

results = [0,0,0,0]
tries = 1000

for i in xrange(0,tries):
    work = db[:]
    while work == db: 
        for j in xrange(0,random.randint(1,5)):
            work[random.randint(1,len(db))-1] = random.randint(0,255)

    work.tofile(open('outdb','w'))

    try:
        c = sqlite3.connect('outdb')
        results[0] += 1

        for r in c.execute('PRAGMA integrity_check;'):
        results[1] += 1 if (r[0] == 'ok') else 0 
    except:
        continue    

    try:
        results[3] += 1 if [x for x in c.execute('SELECT * FROM table ORDER BY _id')] != ta else 0
        results[2] += 1
    except:
        c.close()
        continue

print 'Results for '+str(tries)+' tests:'
print 'Creating connection failed '+str(tries-results[0])+ ' times'
print 'Integrity check failed '+str(results[0]-results[1])+ ' times'
print 'Running a SELECT * query failed '+str(results[1]-results[2])+ ' times'
print 'Data was succesfully altered '+str(results[3])+ ' times'

结果表明,以这种方式“编辑”表格数据是完全可以的:

Results for 1000 tests:
Creating connection failed 0 times
Integrity check failed 503 times
Running a SELECT * query failed 289 times
Data was succesfully altered 193 times

通常有趣的是,对于完整性检查未检测到的一半修改运行查询失败,但对我来说最有趣的是,我的数据库中的某些东西可能会交换随机字节,从而使我的应用程序对我的一部分用户无用。

我已经阅读了 SQLite 网站和 StackOverflow 上可能导致损坏的原因,我知道强制应用程序关闭可能会对数据库造成伤害。我只想知道是否有可能实现快速、更强大的数据库完整性检查。

我在启动时从整个表的一列中读取数据(用于自动完成),所以我想从所有值中计算一些哈希值 - 我认为这会很好,因为一些哈希函数只是为了做完整性检查,但也许有一个更简单、更快和更好的解决方案——我问你,如果你知道的话。

4

1 回答 1

1

我不知道任何这样的 SQLite 特性,所以我想说计算哈希是最简单的解决方案,先看看这个MessageDigest类。

于 2013-01-01T15:46:18.773 回答