sl@0: /* sl@0: ** This program tests the ability of SQLite database to recover from a crash. sl@0: ** This program runs under Unix only, but the results are applicable to all sl@0: ** systems. sl@0: ** sl@0: ** The main process first constructs a test database, then starts creating sl@0: ** subprocesses that write to that database. Each subprocess is killed off, sl@0: ** without a chance to clean up its database connection, after a random sl@0: ** delay. This killing of the subprocesses simulates a crash or power sl@0: ** failure. The next subprocess to open the database should rollback sl@0: ** whatever operation was in process at the time of the simulated crash. sl@0: ** sl@0: ** If any problems are encountered, an error is reported and the test stops. sl@0: ** If no problems are seen after a large number of tests, we assume that sl@0: ** the rollback mechanism is working. sl@0: */ sl@0: #include sl@0: #include sl@0: #include sl@0: #include sl@0: #include sl@0: #include sl@0: #include sl@0: #include sl@0: #include "sqlite.h" sl@0: sl@0: static void do_some_sql(int parent){ sl@0: char *zErr; sl@0: int rc = SQLITE_OK; sl@0: sqlite *db; sl@0: int cnt = 0; sl@0: static char zBig[] = sl@0: "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sl@0: "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; sl@0: sl@0: if( access("./test.db-journal",0)==0 ){ sl@0: /*printf("pid %d: journal exists. rollback will be required\n",getpid());*/ unlink("test.db-saved"); sl@0: system("cp test.db test.db-saved"); sl@0: unlink("test.db-journal-saved"); sl@0: system("cp test.db-journal test.db-journal-saved"); sl@0: } sl@0: db = sqlite_open("./test.db", 0, &zErr); sl@0: if( db==0 ){ sl@0: printf("ERROR: %s\n", zErr); sl@0: if( strcmp(zErr,"database disk image is malformed")==0 ){ sl@0: kill(parent, SIGKILL); sl@0: } sl@0: exit(1); sl@0: } sl@0: srand(getpid()); sl@0: while( rc==SQLITE_OK ){ sl@0: cnt++; sl@0: rc = sqlite_exec_printf(db, sl@0: "INSERT INTO t1 VALUES(%d,'%d%s')", 0, 0, &zErr, sl@0: rand(), rand(), zBig); sl@0: } sl@0: if( rc!=SQLITE_OK ){ sl@0: printf("ERROR #%d: %s\n", rc, zErr); sl@0: if( rc==SQLITE_CORRUPT ){ sl@0: kill(parent, SIGKILL); sl@0: } sl@0: } sl@0: printf("pid %d: cnt=%d\n", getpid(), cnt); sl@0: } sl@0: sl@0: sl@0: int main(int argc, char **argv){ sl@0: int i; sl@0: sqlite *db; sl@0: char *zErr; sl@0: int status; sl@0: int parent = getpid(); sl@0: sl@0: unlink("test.db"); sl@0: unlink("test.db-journal"); sl@0: db = sqlite_open("test.db", 0, &zErr); sl@0: if( db==0 ){ sl@0: printf("Cannot initialize: %s\n", zErr); sl@0: return 1; sl@0: } sl@0: sqlite_exec(db, "CREATE TABLE t1(a,b)", 0, 0, 0); sl@0: sqlite_close(db); sl@0: for(i=0; i<10000; i++){ sl@0: int pid = fork(); sl@0: if( pid==0 ){ sl@0: sched_yield(); sl@0: do_some_sql(parent); sl@0: return 0; sl@0: } sl@0: printf("test %d, pid=%d\n", i, pid); sl@0: usleep(rand()%10000 + 1000); sl@0: kill(pid, SIGKILL); sl@0: waitpid(pid, &status, 0); sl@0: } sl@0: return 0; sl@0: }