Replace path string in SQLite DB causes unexpected violated unique constraint

时间秒杀一切 提交于 2019-12-25 00:13:56

问题


I'm not sure whether I've found a bug in SQLite or whether I'm simply not using it correctly. I'm storing relative file paths (as you know them from UNIX file systems) in a DB. For safety I've marked the column to be unique.

Below is a self-explanatory example where the last command unexpectedly fails with a violated UNIQUE constraint. My goal is to rename the directory with path "a" to "d"

CREATE TABLE test (db_id INTEGER PRIMARY KEY, path TEXT UNIQUE);
INSERT INTO test (path) VALUES ('a');
INSERT INTO test (path) VALUES ('a/d/a');
INSERT INTO test (path) VALUES ('a/d');
INSERT INTO test (path) VALUES ('a/d/c');
INSERT INTO test (path) VALUES ('a/a');
INSERT INTO test (path) VALUES ('a/c');
INSERT INTO test (path) VALUES ('a/a/a');
UPDATE test SET path = 'd' WHERE db_id = 1;
UPDATE test SET path = replace(path, 'a/', 'd/') WHERE path GLOB 'a/*'

Any ideas are welcome. I'm using SQlite v2.6.0.


回答1:


INSERT INTO test (path) VALUES ('a/d/a');
INSERT INTO test (path) VALUES ('a/a/a');

After replacing a/ with d/, both values are d/d/a.

If you want to change only an a/ at the start of the string, you cannot use replace():

UPDATE test
SET path = 'd/' || substr(path, 3)
WHERE path GLOB 'a/*';


来源:https://stackoverflow.com/questions/50161090/replace-path-string-in-sqlite-db-causes-unexpected-violated-unique-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!