Last active
March 1, 2019 06:22
-
-
Save hborders/7a7e588192552a4cd46a581097cd367f to your computer and use it in GitHub Desktop.
Moves a subscription row after a given reference subscription row
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Moves moving_id after reference_id by finding the next row after | |
reference_id and setting moving_id.sort to be the midpoint of | |
reference_id.sort and next_reference_id.sort | |
*/ | |
UPDATE subscription | |
SET sort = ( | |
CASE WHEN ( | |
/* | |
Get the first sort value after the reference_id | |
Have to wrap in another SELECT to change an empty rowset | |
to a NULL value. | |
*/ | |
SELECT ( | |
/* | |
Find the next row after reference_id | |
I repeat this below. Is there a way to abstract it? | |
*/ | |
SELECT sort | |
FROM subscription | |
WHERE sort > ( | |
/* | |
I also repeat this 3 times. Is there a way to abstract it? | |
*/ | |
SELECT sort | |
FROM subscription | |
WHERE _id = ? /* reference_id */ | |
) LIMIT 1 | |
) as max_sort | |
) IS NULL THEN ( | |
/* | |
There is no sort value after the reference_id, | |
so moving_id's sort becomes MAX(SORT) + 1 | |
*/ | |
SELECT IFNULL(MAX(sort), 0) + 1 | |
FROM subscription | |
) ELSE ( | |
/* | |
There is a sort value after reference_id, | |
so moving_id's sort becomes: | |
( reference_id.sort + after_reference_id.sort ) / 2 | |
*/ | |
( | |
( | |
/* This is repeated from above */ | |
SELECT sort | |
FROM subscription | |
WHERE sort > ( | |
/* This is repeated from above */ | |
SELECT sort | |
FROM subscription | |
WHERE _id = ? /* reference_id */ | |
) LIMIT 1 | |
) + ( | |
/* This is repeated twice from above */ | |
SELECT sort | |
FROM subscription | |
WHERE _id = ? /* reference_id */ | |
) | |
) / 2 | |
) END | |
) WHERE _id = ? /* moving_id */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE subscription ( | |
_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | |
sort REAL NOT NULL UNIQUE DEFAULT 0 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I did get this working with
SQLite 3.27.0