Last active
April 6, 2022 23:17
-
-
Save CodyKochmann/32d8457110187770cd21e50e102c2748 to your computer and use it in GitHub Desktop.
postgres function based kv storage for sql algorithms.
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
-- ------------------------------------------- | |
-- This is an implementation of a key, value | |
-- store for function based kv storage for | |
-- different sql based algorithms to utilize | |
-- in postgres. | |
-- ------------------------------------------- | |
-- Author: Cody Kochmann | |
-- license: MIT | |
-- ------------------------------------------- | |
CREATE TABLE IF NOT EXISTS _kv( | |
k TEXT UNIQUE primary key, | |
v TEXT | |
); | |
DROP FUNCTION IF EXISTS kv_del; | |
CREATE FUNCTION kv_del(target_key TEXT) RETURNS BOOLEAN AS $$ | |
BEGIN | |
DELETE FROM _kv WHERE k=target_key; | |
RETURN true; | |
END; | |
$$ language plpgsql; | |
DROP FUNCTION IF EXISTS kv_set; | |
CREATE FUNCTION kv_set(target_key TEXT, target_value TEXT) RETURNS VOID AS $$ | |
BEGIN | |
INSERT INTO _kv (k, v) VALUES (target_key, target_value) on conflict(k) do update set v=target_value; | |
END; | |
$$ language plpgsql; | |
DROP FUNCTION IF EXISTS kv_get; | |
CREATE FUNCTION kv_get(target_key TEXT) RETURNS TEXT | |
AS $$ | |
DECLARE | |
out TEXT; | |
BEGIN | |
SELECT v FROM _kv INTO out WHERE k=target_key LIMIT 1; | |
RETURN out; | |
END; | |
$$ language plpgsql; | |
-- ------------------------------------------- | |
-- Example code below to show functionality | |
-- ------------------------------------------- | |
-- SELECT kv_set('waffles', 'please'); | |
-- SELECT kv_get('waffles'); | |
-- SELECT * from _kv; | |
-- | |
-- SELECT kv_set('waffles', 'yes more'); | |
-- SELECT kv_get('waffles'); | |
-- SELECT * from _kv; | |
-- | |
-- SELECT kv_del('waffles'); | |
-- SELECT * from _kv; | |
-- SELECT kv_get('waffles'); | |
-- ------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment