如果SQLite中的模式不匹配,请替换表

问题描述 投票:0回答:1

我正在开发很多使用SQLite3的应用程序,并希望确保表格正常:它们是我对它们的期望(具有正确的列,列类型,notnull等)。我当前的apporach是手动检查PRAGMA table_info()返回的数据,如果错误则删除表。

CREATE TABLE IF NOT EXISTS只检查表存在,但不匹配传递描述。它通常很有用,但不适用于类型检查。

有没有办法让这种检查比我现在做的更好?

sqlite database-schema
1个回答
1
投票

我这样做的方法是使用数据库user_version来跟踪架构更改。所以一般程序是:

在初始数据库创建时,将用户版本设置为1,PRAGMA USER_VERSION = 1

在您的程序中,检查表是否需要使用类似下面的伪代码更新/删除/重新创建表(current_schema_version最初为1但在每次模式更改时都会增加)。

if user_version == 0
    new database, so create all tables in the database
    set user_version = current_schema_version
else if user_version == current_schema_version - 1
    create/recreate tables, or whatever other adjustments have to be made for new schema
    set user_version = current_schema_version
endif
© www.soinside.com 2019 - 2024. All rights reserved.