Best practices for in-app database migration for Sqlite

前端 未结 8 2064
囚心锁ツ
囚心锁ツ 2020-11-30 16:31

I am using sqlite for my iphone and I anticipate the database schema might change over time. What are the gotchas, naming conventions and things to watch out for to do a su

8条回答
  •  爱一瞬间的悲伤
    2020-11-30 16:58

    The answer from Just Curious is dead-on (you got my point!), and it's what we use to track the version of the database schema that is currently in the app.

    To run through the migrations that need to occur to get user_version matching the app's expected schema version, we use a switch statement. Here's a cut-up example of what this look like in our app Strip:

    - (void) migrateToSchemaFromVersion:(NSInteger)fromVersion toVersion:(NSInteger)toVersion { 
        // allow migrations to fall thru switch cases to do a complete run
        // start with current version + 1
        [self beginTransaction];
        switch (fromVersion + 1) {
            case 3:
                // change pin type to mode 'pin' for keyboard handling changes
                // removing types from previous schema
                sqlite3_exec(db, "DELETE FROM types;", NULL, NULL, NULL);
                NSLog(@"installing current types");
                [self loadInitialData];
            case 4:
                //adds support for recent view tracking
                sqlite3_exec(db, "ALTER TABLE entries ADD COLUMN touched_at TEXT;", NULL, NULL, NULL);
            case 5:
                {
                    sqlite3_exec(db, "ALTER TABLE categories ADD COLUMN image TEXT;", NULL, NULL, NULL);
                    sqlite3_exec(db, "ALTER TABLE categories ADD COLUMN entry_count INTEGER;", NULL, NULL, NULL);
                    sqlite3_exec(db, "CREATE INDEX IF NOT EXISTS categories_id_idx ON categories(id);", NULL, NULL, NULL);
                    sqlite3_exec(db, "CREATE INDEX IF NOT EXISTS categories_name_id ON categories(name);", NULL, NULL, NULL);
                    sqlite3_exec(db, "CREATE INDEX IF NOT EXISTS entries_id_idx ON entries(id);", NULL, NULL, NULL);
    
                   // etc...
                }
        }
    
        [self setSchemaVersion];
        [self endTransaction];
    }
    

提交回复
热议问题