如果 SQLite 中不存在,则更改表添加列

2021-11-27 00:00:00 sqlite alter-table

我们最近需要向一些现有的 SQLite 数据库表添加列.这可以通过 ALTER TABLE ADD COLUMN 来完成.当然,如果表已经被改变了,我们想不管它.不幸的是,SQLite 不支持 ALTER TABLE 上的 IF NOT EXISTS 子句.

We've recently had the need to add columns to a few of our existing SQLite database tables. This can be done with ALTER TABLE ADD COLUMN. Of course, if the table has already been altered, we want to leave it alone. Unfortunately, SQLite doesn't support an IF NOT EXISTS clause on ALTER TABLE.

我们目前的解决方法是执行 ALTER TABLE 语句并忽略任何重复列名"错误,就像 这个 Python 示例(但在 C++ 中).

Our current workaround is to execute the ALTER TABLE statement and ignore any "duplicate column name" errors, just like this Python example (but in C++).

然而,我们通常设置数据库模式的方法是使用包含 CREATE TABLE IF NOT EXISTSCREATE INDEX IF NOT EXISTS 语句的 .sql 脚本,它们可以使用 sqlite3_execsqlite3 命令行工具执行.我们不能将 ALTER TABLE 放在这些脚本文件中,因为如果该语句失败,则不会执行其后的任何内容.

However, our usual approach to setting up database schemas is to have a .sql script containing CREATE TABLE IF NOT EXISTS and CREATE INDEX IF NOT EXISTS statements, which can be executed using sqlite3_exec or the sqlite3 command-line tool. We can't put ALTER TABLE in these script files because if that statement fails, anything after it won't be executed.

我想将表定义放在一个地方,而不是在 .sql 和 .cpp 文件之间拆分.有没有办法在纯 SQLite SQL 中为 ALTER TABLE ADD COLUMN IF NOT EXISTS 编写解决方法?

I want to have the table definitions in one place and not split between .sql and .cpp files. Is there a way to write a workaround to ALTER TABLE ADD COLUMN IF NOT EXISTS in pure SQLite SQL?

推荐答案

我有一个 99% 的纯 SQL 方法.这个想法是对您的架构进行版本控制.您可以通过两种方式执行此操作:

I have a 99% pure SQL method. The idea is to version your schema. You can do this in two ways:

  • 使用user_version"编译指示命令(PRAGMA user_version) 存储数据库架构版本的增量编号.

  • Use the 'user_version' pragma command (PRAGMA user_version) to store an incremental number for your database schema version.

将您的版本号存储在您自己定义的表中.

Store your version number in your own defined table.

这样,当软件启动时,它可以检查数据库架构,如果需要,运行您的ALTER TABLE 查询,然后增加存储的版本.这比盲目"尝试各种更新要好得多,尤其是在您的数据库多年来增长和更改了几次的情况下.

In this way, when the software is started, it can check the database schema and, if needed, run your ALTER TABLE query, then increment the stored version. This is by far better than attempting various updates "blind", especially if your database grows and changes a few times over the years.

相关文章