已发布应用程序上的 Sqlite 表和数据库迁移?

Kak*_*kar 5 sqlite android database-migration react-native expo

我在 react-native 和 expo 中开发了一个 android 应用程序。我还在 google play 上发布了该应用程序。

现在,我在本地对我的 SQLite 数据库表进行了一些修改。

假设,在表的架构之前是这样的:

CREATE TABLE expenditures (id integer primary key, max_amount REAL not null);
Run Code Online (Sandbox Code Playgroud)

现在我想把它改成这样:

CREATE TABLE expenditures (id integer primary key, max_amount TEXT not null);
Run Code Online (Sandbox Code Playgroud)

在生产应用程序(谷歌游戏商店)上进行新的更新/升级后,有什么方法可以运行方法吗?这样升级后我只能更改一次表,其他新安装的用户不会受到此功能的影响。我在原生android上找到了两种方法:

  1. onCreate:需要创建表时第一次调用。
  2. onUpgrade:升级数据库版本时调用此方法。

但是由于我使用 react-native 和 expo 开发了我的应用程序,所以我不能使用上述方法。虽然我onUpgrade 在 expo 代码中找到,但我不确定如何在 expo 中使用此功能。

或者有没有更好的方法来处理在 react-native 和 expo 中发布的应用程序上的数据库迁移?

sja*_*aan 2

我认为您不能真正使用链接到的版本控制内容,因为这会删除您的数据库并从头开始重新创建它,因此您会丢失数据。

对此的一个简单解决方案是手动跟踪已在表中执行的迁移。然后,如果该表尚不存在,则可以创建该表(这可以通过首先尝试查询它来以非常愚蠢的方式完成,如果失败,则创建它)。如果您有按顺序排列的所有已知迁移的列表,则只需删除表中已有条目的项目并运行其余的项目即可。

我在一个旧的 Cordova 应用程序中编写了这段代码(是的,它真的很旧,它仍然使用 Require JS 来定义模块):

/**
 * Provide access to an SQL database, using the SQLite plugin for
 * Cordova devices so we aren't limited in how much data we can store,
 * and falling back to browser native support on desktop.
 *
 * Unfortunately webSQL is deprecated and slowly being phased out.
 */
define(['require', 'module', 'deviceReady!'], function(require, module, isCordova) {
    'use strict';

    var dbRootObject = isCordova ? window.sqlitePlugin : window,
    config = module.config();

    if (typeof dbRootObject.openDatabase == 'undefined') {
        window.alert('Your browser has no SQL support!  Please try a Webkit-based browser');
        return null;
    } else {
        var db = dbRootObject.openDatabase(config.dbName, '', 'Direct Result database', null),
        transaction = function(callback) {
            // We go through this trouble to automatically provide
            // error reporting and auto-rollback.
            var makeFacade = function(t) {
                return {
                    sql: function(sql, args, okCallback, errorCallback) {
                        var okFn, errFn;
                        if (okCallback) {
                            okFn = function(t, r) { return okCallback(makeFacade(t), r); };
                        } else {
                            okFn = null;
                        }
                        if (errorCallback) {
                            errFn = function(t, e) { console.log('SQL error: '+sql, e); return errorCallback(makeFacade(t), e); };
                        } else {
                            errFn = function(t, e) {
                                // It's important we throw an exn,
                                // else the txn won't be aborted!
                                window.alert(e.message + ' sql: '+sql);
                                throw(e.message + ' sql: '+sql);
                            };
                        }
                        return t.executeSql(sql, args, okFn, errFn);
                    }
                };
            };
            return db.transaction(function(t) {
                return callback(makeFacade(t));
            }, function(e) { console.log('error'); console.log(e); });
        },

        // We're going to have to create or own migrations, because
        // both the Cordova SQLite plugin and the Firefox WebSQL
        // extension don't implement versioning in their WebSQL API.
        migrate = function(version, upFn, done, txn) { // "Down" migrations are currently not supported
            var doIt = function(t) {
                t.sql('SELECT NOT EXISTS (SELECT version FROM sqldb_migrations WHERE version = ?) AS missing',
                      [version], function(t, r) {
                          if (r.rows.item(0).missing == '1') {
                              upFn(t, function() {
                                  t.sql('INSERT INTO sqldb_migrations (version)'+
                                        'VALUES (?)', [version], done);
                              });
                          } else {
                              done(t);
                          }
                      });
            };
            if (txn) doIt(txn);
            else transaction(doIt);
        },

        maybeRunMigrations = function(callback) {
            var migrations = [],
            addMigration = function(name, migration) {
                migrations.push([name, migration]);
            },
            runMigrations = function(t) {
                if (migrations.length === 0) {
                    callback(t);
                } else {
                    var m = migrations.shift(),
                    name = m[0],
                    migration = m[1];
                    migrate(name, migration, runMigrations, t);
                }
            };

            // ADD MIGRATIONS HERE. The idea is you can just add migrations
            // in a queue and they'll be run in sequence.

            // Here are two example migrations
            addMigration('1', function (t, done) {
                t.sql('CREATE TABLE people ('+
                      '  id integer PRIMARY KEY NOT NULL, '+
                      '  initials text NOT NULL, '+
                      '  first_name text NOT NULL, '+
                      '  family_name text NOT NULL, '+
                      '  email text NOT NULL, ', [], done);
            });
            addMigration('2', function(t, done) {
                t.sql('ALTER TABLE people ADD COLUMN phone_number text', [], done);
            });

            transaction(function(t) {
                t.sql('CREATE TABLE IF NOT EXISTS sqldb_migrations ('+
                      '  version int UNIQUE, '+
                      '  timestamp_applied text NOT NULL DEFAULT CURRENT_TIMESTAMP '+
                      ')', [], function (t, r) { runMigrations(t, migrations); });
            });
        };

        // Expose "migrate" just in case
        return {transaction: transaction, migrate: migrate, maybeRunMigrations: maybeRunMigrations};
    }
});
Run Code Online (Sandbox Code Playgroud)

您还需要非常小心,因为我发现您实际上无法使用 SQLite 更改甚至删除列(或者至少在我编写此代码时不能使用 Cordova 插件)!因此,也要非常小心限制,否则你最终会把自己逼到墙角。

我还没有尝试过,但如果您重命名旧表,使用更改后的列再次创建新表,然后复制数据,则可能会发生这种情况。