Best practices for in-app database migration for Sqlite

前端 未结 8 2058
囚心锁ツ
囚心锁ツ 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:59

    1. Create /migrations folder with the list of SQL-based migrations, where each migration looks something like this:

    /migrations/001-categories.sql

    -- Up
    CREATE TABLE Category (id INTEGER PRIMARY KEY, name TEXT);
    INSERT INTO Category (id, name) VALUES (1, 'Test');
    
    -- Down
    DROP TABLE User;
    

    /migrations/002-posts.sql

    -- Up
    CREATE TABLE Post (id INTEGER PRIMARY KEY, categoryId INTEGER, text TEXT);
    
    -- Down
    DROP TABLE Post;
    

    2. Create db table containing the list of applied migrations, for example:

    CREATE TABLE Migration (name TEXT);
    

    3. Update application bootstrap logic so that before it starts, it grabs the list of migrations from the /migrations folder and runs the migrations that have not yet been applied.

    Here is an example implemented with JavaScript: SQLite Client for Node.js Apps

提交回复
热议问题