Skip to content

Instantly share code, notes, and snippets.

@pyramation
Created November 8, 2020 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyramation/56a4f48b630f3ff06b6aa2ba284c0e98 to your computer and use it in GitHub Desktop.
Save pyramation/56a4f48b630f3ff06b6aa2ba284c0e98 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION smart_comments(tags jsonb, description text default null)
RETURNS text
AS $$
DECLARE
key text;
value jsonb;
tvalue text;
attrs text[] = ARRAY[]::text[];
_key text;
_value text;
BEGIN
FOR key IN SELECT jsonb_object_keys(tags)
LOOP
value = tags->key;
tvalue = tags->>key;
IF (jsonb_typeof(value) = 'boolean') THEN
IF (tvalue = 'true') THEN
attrs = array_append(attrs, concat('@', key));
END IF;
ELSIF (jsonb_typeof(value) = 'array') THEN
FOR _value IN SELECT * FROM jsonb_array_elements(value)
LOOP
-- json text includes double quotes, so lets remove them!
attrs = array_append(attrs, concat('@', key, ' ', trim(both '"' from _value)));
END LOOP;
ELSE
attrs = array_append(attrs, concat('@', key, ' ', tvalue));
END IF;
END LOOP;
IF (description IS NOT NULL) THEN
attrs = array_append(attrs, description);
END IF;
IF (array_length(attrs, 1) > 0) THEN
RETURN array_to_string(attrs, '\n');
END IF;
RETURN NULL;
END;
$$
LANGUAGE 'plpgsql'
STABLE;
SELECT * FROM smart_comments('{"a":1}', 'my description');
@pyramation
Copy link
Author

trim(both '"' from _value) should probably be array_to_json(ARRAY[_value])->>0

It's a bit weird, but it's the best way I know of turning a string JSON type (as opposed to object, array, boolean, null, number) back to the actual string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment