SQLite Forum

table locked when dropping a temp table
Login
I have a table that I want to keep ordered based on an "order" field. I also have a unique index on the same field to ensure that no two records have the same order.
If I want to insert an element, I cannot simply do an

UPDATE variables SET order=order+1 WHERE order>x

because it would fail the unique constraint, so I did this:

BEGIN;
DROP TABLE IF EXISTS x;
CREATE TEMP TABLE x AS SELECT * FROM variables WHERE order>=:order;
UPDATE x SET order=order+1;
DELETE FROM variables WHERE order>=:order;
INSERT INTO variables SELECT * FROM x;
DROP TABLE x;
COMMIT;

and it worked yesterday. Today it says "Table locked" when it tries to DROP TABLE x. I changed it to

BEGIN;
CREATE TEMP TABLE IF NOT EXISTS x AS SELECT * FROM variables LIMIT 1;
DELETE FROM x;
INSERT INTO x SELECT * FROM variables WHERE order>=:order;
UPDATE x SET order=order+1;
DELETE FROM variables WHERE order>=:order;
INSERT INTO variables SELECT * FROM x;
COMMIT;


And this causes no "table locked" error.
Two questions:

1) is there a simpler way (i.t. like PRAGMA defer_foreign_keys = ON but for unique indexes).

2) why the table is locked?