最近遇到一個問題,用戶數據丟失,拿到用戶資料庫文件以後,發現資料庫損壞。database disk image is malformed因此希望可以找到一種方法,可以檢測出來資料庫是否損壞,經過google,找到了一種方法,先記錄下來。+ (BOOL)checkIntegrity { NSStrin... ...
最近遇到一個問題,用戶數據丟失,拿到用戶資料庫文件以後,發現資料庫損壞。
database disk image is malformed
因此希望可以找到一種方法,可以檢測出來資料庫是否損壞,經過google,找到了一種方法,先記錄下來。
+ (BOOL)checkIntegrity {
NSString *databasePath = [self databaseFilePath];
// File not exists = okay
if ( ! [[NSFileManager defaultManager] fileExistsAtPath:databasePath] ) {
return YES;
}
const char *filename = ( const char * )[databasePath cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3 *database = NULL;
if ( sqlite3_open( filename, &database ) != SQLITE_OK ) {
sqlite3_close( database );
return NO;
}
BOOL integrityVerified = NO;
sqlite3_stmt *integrity = NULL;
if ( sqlite3_prepare_v2( database, "PRAGMA integrity_check;", -1, &integrity, NULL ) == SQLITE_OK ) {
while ( sqlite3_step( integrity ) == SQLITE_ROW ) {
const unsigned char *result = sqlite3_column_text( integrity, 0 );
if ( result && strcmp( ( const char * )result, (const char *)"ok" ) == 0 ) {
integrityVerified = YES;
break;
}
}
sqlite3_finalize( integrity );
}
sqlite3_close( database );
return integrityVerified;
}
PRAGMA schema.integrity_check;
PRAGMA schema.integrity_check(N)This pragma does an integrity check of the entire database. The integrity_check pragma looks for out-of-order records, missing pages, malformed records, missing index entries, and UNIQUE and NOT NULL constraint errors. If the integrity_check pragma finds problems, strings are returned (as multiple rows with a single column per row) which describe the problems. Pragma integrity_check will return at most N errors before the analysis quits, with N defaulting to 100. If pragma integrity_check finds no errors, a single row with the value 'ok' is returned.
重點在這句話as multiple rows with a single column per row)
這樣子,可以通過c代碼來實現
根據文檔,也可以使用quick_check來檢查。
PRAGMA schema.quick_check;
PRAGMA schema.quick_check(N)The pragma is like integrity_check except that it does not verify UNIQUE and NOT NULL constraints and does not verify that index content matches table content. By skipping UNIQUE and NOT NULL and index consistency checks, quick_check is able to run much faster than integrity_check. Otherwise the two pragmas are the same.
區別在於integrity_check檢查了
- out-of-order records(亂序的記錄)
- missing pages(缺頁)
- malformed records(錯誤的記錄)
- missing index entries(丟失的索引)
- UNIQUE constraint(唯一性約束)
- NOT NULL (非空約束)
而且耗時較多。
quick_check不檢查約束條件,耗時較短