How can a model keep multiple historical versions but only one active version?

A unique partial index enforces uniqueness only among rows satisfying its predicate.

SQLite example and interpretation

Index the model name only where active is one. A second active row conflicts while archived versions occupy no active slot. The example ignores that conflict to inspect the count.

CREATE TABLE v(name TEXT NOT NULL,active INTEGER);
CREATE UNIQUE INDEX current_v ON v(name) WHERE active=1;
INSERT OR IGNORE INTO v VALUES('A',0),('A',1),('A',1);
SELECT count(*),sum(active) FROM v;

Result [[2, 1]]

中文

如何允许多个历史模型版本,但只允许一个现役版本?

带 WHERE 的唯一索引只在满足谓词的行内执行唯一性条件。

SQLite 示例与适用条件

对 active=1 的模型名加唯一索引,第二条现役记录发生冲突,已归档记录不占名额。例中用忽略冲突观察最终计数。

CREATE TABLE v(name TEXT NOT NULL,active INTEGER);
CREATE UNIQUE INDEX current_v ON v(name) WHERE active=1;
INSERT OR IGNORE INTO v VALUES('A',0),('A',1),('A',1);
SELECT count(*),sum(active) FROM v;

结果 [[2, 1]]

References / 参考来源

Keep reading / 继续阅读