我有下表:
CREATE TABLE methods (
id INTEGER NOT NULL,
version INTEGER NOT NULL,
text TEXT NOT NULL,
PRIMARY KEY (id,version)
);
我希望列'id'在新行上为null时自动递增,我还希望将列'version'设置为1.
我想将自动增量值存储在sqlite_sequence中。
当插入一行'id'时,我希望'version'增加1。
我已经在应用程序级别复制了这个,但我需要在数据库级别,我知道我必须创建一个或两个触发器。
由于
更新
这只是一个版本文档的模式,它可能不是最好的,也可能不安全。有没有人看到这个错误或更好的实施方法?
更新2:
我添加了一个“当前”列来跟踪当前版本。
更新时,我添加了一个查询以提取该ID的最高版本,然后添加1.
我还添加了另一个触发器来阻止更新任何非当前版本。
我已经开始工作了:
CREATE TABLE IF NOT EXISTS 'methods' (
'id' INTEGER NULL,
'version' INTEGER NULL,
'current' INTEGER NOT NULL DEFAULT 0,
'name' TEXT NOT NULL,
PRIMARY KEY ('id','version')
);
INSERT INTO sqlite_sequence (name,seq) VALUES ('methods',0);
CREATE TRIGGER method_insert AFTER INSERT ON "methods" WHEN (NEW.id IS NULL)
BEGIN
UPDATE sqlite_sequence SET seq = seq + 1 WHERE name = 'methods';
UPDATE methods SET id = (
SELECT seq FROM sqlite_sequence WHERE name = 'methods'
), version = 1 WHERE ROWID = NEW.ROWID;
END;
CREATE TRIGGER method_update_not_current BEFORE UPDATE ON methods WHEN (OLD.current != 1)
BEGIN
SELECT RAISE(ABORT,'Only current version of method can be updated.');
END;
CREATE TRIGGER method_update AFTER UPDATE ON methods WHEN (OLD.id == NEW.id)
BEGIN
UPDATE methods SET current = 0 WHERE id = OLD.id;
UPDATE methods SET version = (
SELECT MAX(version) FROM methods WHERE id = OLD.id
) + 1 WHERE ROWID = OLD.ROWID;
INSERT INTO methods (id,version,name) VALUES (OLD.id,OLD.version,OLD.name);
END;
INSERT INTO methods (name) VALUES ('Test');
INSERT INTO methods (name) VALUES ('Test2');
UPDATE methods SET name = 'Tested' WHERE id = 1;
SELECT * FROM methods;
1|2|1|Tested
2|1|1|Test2
1|1|0|Test