Created
October 28, 2021 11:11
-
-
Save albttx/6c77a9e52befffa4a0ced52055e06b97 to your computer and use it in GitHub Desktop.
Glide SQL keys
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
DROP TABLE IF EXISTS keys; | |
CREATE TABLE keys ( | |
key_name VARCHAR(128) UNIQUE NOT NULL PRIMARY KEY, | |
context VARCHAR(128) NOT NULL, | |
position INTEGER NOT NULL, | |
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | |
UNIQUE (context, position) DEFERRABLE | |
); | |
CREATE OR REPLACE FUNCTION glide_keys_position() | |
RETURNS TRIGGER AS $$ | |
BEGIN | |
UPDATE keys | |
SET position = position + 1 | |
WHERE | |
context = NEW.context AND position >= NEW.position; | |
RETURN NEW; | |
END; | |
$$ LANGUAGE plpgsql; | |
CREATE TRIGGER trg_glide_keys_position | |
BEFORE INSERT ON keys | |
FOR EACH ROW EXECUTE PROCEDURE glide_keys_position(); | |
-- here a sample of data | |
INSERT INTO keys (key_name, context, position) | |
VALUES | |
('A.1', 'ctx_A', 0), | |
('A.2', 'ctx_A', 1), | |
('A.3', 'ctx_A', 2), | |
('A.4', 'ctx_A', 3), | |
('B.1', 'ctx_B', 0), | |
('B.2', 'ctx_B', 1), | |
('B.3', 'ctx_B', 2), | |
('B.4', 'ctx_B', 3); | |
-- UPDATE keys SET position = position + 1 WHERE context = 'ctx_A' AND position > 1; | |
INSERT INTO keys (key_name, context, position) VALUES ('A.10', 'ctx_A', 2); | |
BEGIN; | |
SET CONSTRAINTS keys_context_position_key DEFERRED; | |
UPDATE keys | |
SET position = CASE key_name | |
WHEN 'A.4' THEN (SELECT position FROM keys WHERE context='ctx_A' AND key_name = 'A.3') | |
WHEN 'A.3' THEN (SELECT position FROM keys WHERE context='ctx_A' AND key_name = 'A.4') | |
END | |
WHERE key_name IN ('A.3', 'A.4'); | |
COMMIT; | |
SELECT * FROM keys WHERE context='ctx_A' ORDER BY position; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: